text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { App, Component, ComponentPublicInstance, ComponentOptions } from 'vue' import { LooseDictionary } from './ts-helpers' export interface AddressbarColor { /** * Sets addressbar color (for browsers that support it) * @param hexColor Color in hex format */ set (hexColor : string): void } export interface AppFullscreen { /** * Does browser support it? */ isCapable : boolean /** * Is Fullscreen active? */ isActive : boolean /** * The DOM element used as root for fullscreen, otherwise 'null' */ activeEl : LooseDictionary /** * Request going into Fullscreen (with optional target) * @param target Optional CSS selector of target to request Fullscreen on * @returns A Promise with the outcome (true -> validation was a success, false -> invalid models detected) */ request (target? : string): Promise<any> /** * Request exiting out of Fullscreen mode * @returns A Promise with the outcome (true -> validation was a success, false -> invalid models detected) */ exit (): Promise<any> /** * Request toggling Fullscreen mode (with optional target if requesting going into Fullscreen only) * @param target Optional CSS selector of target to request Fullscreen on * @returns A Promise with the outcome (true -> validation was a success, false -> invalid models detected) */ toggle (target? : string): Promise<any> } export interface AppVisibility { /** * Does the app have user focus? Or the app runs in the background / another tab has the user's attention */ appVisible : boolean } export interface BottomSheet { /** * Creates an ad-hoc Bottom Sheet; Same as calling $q.bottomSheet(...) * @param opts Bottom Sheet options * @returns Chainable Object */ create (opts : { /** * CSS Class name to apply to the Dialog's QCard */ class? : string | any[] | LooseDictionary /** * CSS style to apply to the Dialog's QCard */ style? : string | any[] | LooseDictionary /** * Title */ title? : string /** * Message */ message? : string /** * Array of Objects, each Object defining an action */ actions? : { /** * CSS classes for this action */ classes? : string | any[] | LooseDictionary /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ icon? : string /** * Path to an image for this action */ img? : string /** * Display img as avatar (round borders) */ avatar? : boolean /** * Action label */ label? : string | number }[] /** * Display actions as a grid instead of as a list */ grid? : boolean /** * Apply dark mode */ dark? : boolean /** * Put Bottom Sheet into seamless mode; Does not use a backdrop so user is able to interact with the rest of the page too */ seamless? : boolean /** * User cannot dismiss Bottom Sheet if clicking outside of it or hitting ESC key */ persistent? : boolean }): DialogChainObject } export interface Cookies { /** * Get cookie * @param name Cookie name * @returns Cookie value; Returns null if cookie not found */ get: CookiesGetMethodType /** * Get all cookies * @returns Object with cookie names (as keys) and their values */ getAll (): LooseDictionary /** * Set cookie * @param name Cookie name * @param value Cookie value * @param options Cookie options */ set (name : string, value : string, options? : { /** * Cookie expires detail; If specified as Number, then the unit is days; If specified as String, it can either be raw stringified date or in Xd Xh Xm Xs format (see examples) */ expires? : number | string | Date /** * Cookie path */ path? : string /** * Cookie domain */ domain? : string /** * SameSite cookie option (not supported by IE11) */ sameSite? : string /** * Is cookie Http Only? */ httpOnly? : boolean /** * Is cookie secure? (https only) */ secure? : boolean /** * Raw string for other cookie options; To be used as a last resort for possible newer props that are currently not yet implemented in Quasar */ other? : string }): void /** * Check if cookie exists * @param name Cookie name * @returns Does cookie exists or not? */ has (name : string): boolean /** * Remove a cookie * @param name Cookie name * @param options Cookie options */ remove (name : string, options? : { /** * Cookie path */ path? : string /** * Cookie domain */ domain? : string }): void /** * For SSR usage only, and only on the global import (not on $q.cookies) * @param ssrContext SSR Context Object * @returns Cookie object (like $q.cookies) for SSR usage purposes */ parseSSR (ssrContext : LooseDictionary): Cookies } export interface Dark { /** * Is Dark mode active? */ isActive : boolean /** * Dark mode configuration (not status) */ mode : boolean | 'auto' /** * Set dark mode status * @param status Dark mode status */ set (status : boolean | 'auto'): void /** * Toggle dark mode status */ toggle (): void } export interface Dialog { /** * Creates an ad-hoc Dialog; Same as calling $q.dialog(...) * @param opts Dialog options * @returns Chainable Object */ create (opts : QDialogOptions): DialogChainObject } export interface Loading { /** * Is Loading active? */ isActive : boolean /** * Activate and show * @param opts All props are optional */ show (opts? : { /** * Wait a number of millisecond before showing; Not worth showing for 100ms for example then hiding it, so wait until you're sure it's a process that will take some considerable amount of time */ delay? : number /** * Message to display */ message? : string /** * Render the message as HTML; This can lead to XSS attacks so make sure that you sanitize the message first */ html? : boolean /** * Spinner size (in pixels) */ spinnerSize? : number /** * Color name for spinner from the Quasar Color Palette */ spinnerColor? : string /** * Color name for text from the Quasar Color Palette */ messageColor? : string /** * Color name for background from the Quasar Color Palette */ backgroundColor? : string /** * One of the QSpinners */ spinner? : Component /** * Add a CSS class to easily customize the component */ customClass? : string /** * Ignore the default configuration (set by setDefaults()) for this instance only */ ignoreDefaults? : boolean }): void /** * Hide it */ hide (): void /** * Merge options into the default ones * @param opts Pick the subprop you want to define */ setDefaults (opts : { /** * Wait a number of millisecond before showing; Not worth showing for 100ms for example then hiding it, so wait until you're sure it's a process that will take some considerable amount of time */ delay? : number /** * Message to display */ message? : string /** * Spinner size (in pixels) */ spinnerSize? : number /** * Color name for spinner from the Quasar Color Palette */ spinnerColor? : string /** * Color name for text from the Quasar Color Palette */ messageColor? : string /** * Color name for background from the Quasar Color Palette */ backgroundColor? : string /** * One of the QSpinners */ spinner? : Component /** * Add a CSS class to easily customize the component */ customClass? : string }): void } export interface LoadingBar { /** * Notify bar you've started a background activity * @param speed Delay (in milliseconds) between bar progress increments */ start (speed? : number): void /** * Notify bar one background activity has finalized */ stop (): void /** * Manually trigger a bar progress increment * @param amount Amount (0.0 < x < 1.0) to increment with */ increment (amount? : number): void /** * Set the inner QAjaxBar's props * @param ...props QAjaxBar component props */ setDefaults (...props: any[]): void } export interface LocalStorage { /** * Check if storage item exists * @param key Entry key * @returns Does the item exists or not? */ has (key : string): boolean /** * Get storage number of entries * @returns Number of entries */ getLength (): number /** * Get a storage item value * @param key Entry key * @returns Storage item value */ getItem: WebStorageGetItemMethodType /** * Get the storage item value at specific index * @param index Entry index * @returns Storage item index */ getIndex: WebStorageGetIndexMethodType /** * Get the storage key at specific index * @param index Entry index * @returns Storage key */ getKey: WebStorageGetKeyMethodType /** * Retrieve all items in storage * @returns Object syntax: item name as Object key and its value */ getAll (): LooseDictionary /** * Retrieve all keys in storage * @returns Storage keys (Array of Strings) */ getAllKeys: WebStorageGetAllKeysMethodType /** * Set item in storage * @param key Entry key * @param value Entry value */ set (key : string, value : Date | RegExp | number | boolean | Function | LooseDictionary | any[] | string | null): void /** * Remove a storage item * @param key Storage key */ remove (key : string): void /** * Remove everything from the storage */ clear (): void /** * Determine if storage has any items * @returns Tells if storage is empty or not */ isEmpty (): boolean } export interface Meta { } export interface Notify { /** * Creates a notification; Same as calling $q.notify(...) * @param opts Notification options * @returns Calling this function with no parameters hides the notification; When called with one Object parameter (the original notification must NOT be grouped), it updates the notification (specified properties are shallow merged with previous ones; note that group and position cannot be changed while updating and so they are ignored) */ create (opts : { /** * Optional type (that has been previously registered) or one of the out of the box ones ('positive', 'negative', 'warning', 'info', 'ongoing') */ type? : string /** * Color name for component from the Quasar Color Palette */ color? : string /** * Color name for component from the Quasar Color Palette */ textColor? : string /** * The content of your message */ message? : string /** * The content of your optional caption */ caption? : string /** * Render message as HTML; This can lead to XSS attacks, so make sure that you sanitize the message first */ html? : boolean /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ icon? : string /** * URL to an avatar/image; Suggestion: use statics folder */ avatar? : string /** * Useful for notifications that are updated; Displays a Quasar spinner instead of an avatar or icon; If value is Boolean 'true' then the default QSpinner is shown */ spinner? : boolean | Component /** * Window side/corner to stick to */ position? : 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' | 'top' | 'bottom' | 'left' | 'right' | 'center' /** * Override the auto generated group with custom one; Grouped notifications cannot be updated; String or number value inform this is part of a specific group, regardless of its options; When a new notification is triggered with same group name, it replaces the old one and shows a badge with how many times the notification was triggered */ group? : boolean | string | number /** * Color name for the badge from the Quasar Color Palette */ badgeColor? : string /** * Color name for the badge text from the Quasar Color Palette */ badgeTextColor? : string /** * Notification corner to stick badge to; If notification is on the left side then default is top-right otherwise it is top-left */ badgePosition? : 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' /** * Style definitions to be attributed to the badge */ badgeStyle? : any[] | string | LooseDictionary /** * Class definitions to be attributed to the badge */ badgeClass? : any[] | string | LooseDictionary /** * Show progress bar to detail when notification will disappear automatically (unless timeout is 0) */ progress? : boolean /** * Class definitions to be attributed to the progress bar */ progressClass? : any[] | string | LooseDictionary /** * Add CSS class(es) to the notification for easier customization */ classes? : string /** * Key-value for attributes to be set on the notification */ attrs? : LooseDictionary /** * Amount of time to display (in milliseconds) */ timeout? : number /** * Notification actions (buttons); If a 'handler' is specified or not, clicking/tapping on the button will also close the notification; Also check 'closeBtn' convenience prop */ actions? : any[] /** * Function to call when notification gets dismissed */ onDismiss? : Function /** * Convenience way to add a dismiss button with a specific label, without using the 'actions' prop; If set to true, it uses a label accordding to the current Quasar language */ closeBtn? : boolean | string /** * Put notification into multi-line mode; If this prop isn't used and more than one 'action' is specified then notification goes into multi-line mode by default */ multiLine? : boolean /** * Ignore the default configuration (set by setDefaults()) for this instance only */ ignoreDefaults? : boolean } | string): Function /** * Merge options into the default ones * @param opts Notification options */ setDefaults (opts : { /** * Optional type (that has been previously registered) or one of the out of the box ones ('positive', 'negative', 'warning', 'info', 'ongoing') */ type? : string /** * Color name for component from the Quasar Color Palette */ color? : string /** * Color name for component from the Quasar Color Palette */ textColor? : string /** * The content of your message */ message? : string /** * The content of your optional caption */ caption? : string /** * Render message as HTML; This can lead to XSS attacks, so make sure that you sanitize the message first */ html? : boolean /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ icon? : string /** * URL to an avatar/image; Suggestion: use statics folder */ avatar? : string /** * Useful for notifications that are updated; Displays a Quasar spinner instead of an avatar or icon; If value is Boolean 'true' then the default QSpinner is shown */ spinner? : boolean | Component /** * Window side/corner to stick to */ position? : 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' | 'top' | 'bottom' | 'left' | 'right' | 'center' /** * Color name for the badge from the Quasar Color Palette */ badgeColor? : string /** * Color name for the badge text from the Quasar Color Palette */ badgeTextColor? : string /** * Notification corner to stick badge to; If notification is on the left side then default is top-right otherwise it is top-left */ badgePosition? : 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' /** * Style definitions to be attributed to the badge */ badgeStyle? : any[] | string | LooseDictionary /** * Class definitions to be attributed to the badge */ badgeClass? : any[] | string | LooseDictionary /** * Show progress bar to detail when notification will disappear automatically (unless timeout is 0) */ progress? : boolean /** * Class definitions to be attributed to the progress bar */ progressClass? : any[] | string | LooseDictionary /** * Add CSS class(es) to the notification for easier customization */ classes? : string /** * Key-value for attributes to be set on the notification */ attrs? : LooseDictionary /** * Amount of time to display (in milliseconds) */ timeout? : number /** * Notification actions (buttons); If a 'handler' is specified or not, clicking/tapping on the button will also close the notification; Also check 'closeBtn' convenience prop */ actions? : any[] /** * Function to call when notification gets dismissed */ onDismiss? : Function /** * Convenience way to add a dismiss button with a specific label, without using the 'actions' prop; If set to true, it uses a label accordding to the current Quasar language */ closeBtn? : boolean | string /** * Put notification into multi-line mode; If this prop isn't used and more than one 'action' is specified then notification goes into multi-line mode by default */ multiLine? : boolean }): void /** * Register a new type of notification (or override an existing one) * @param typeName Name of the type (to be used as 'type' prop later on) * @param typeOpts Notification options */ registerType (typeName : string, typeOpts : { /** * Optional type (that has been previously registered) or one of the out of the box ones ('positive', 'negative', 'warning', 'info', 'ongoing') */ type? : string /** * Color name for component from the Quasar Color Palette */ color? : string /** * Color name for component from the Quasar Color Palette */ textColor? : string /** * The content of your message */ message? : string /** * The content of your optional caption */ caption? : string /** * Render message as HTML; This can lead to XSS attacks, so make sure that you sanitize the message first */ html? : boolean /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ icon? : string /** * URL to an avatar/image; Suggestion: use statics folder */ avatar? : string /** * Useful for notifications that are updated; Displays a Quasar spinner instead of an avatar or icon; If value is Boolean 'true' then the default QSpinner is shown */ spinner? : boolean | Component /** * Window side/corner to stick to */ position? : 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' | 'top' | 'bottom' | 'left' | 'right' | 'center' /** * Color name for the badge from the Quasar Color Palette */ badgeColor? : string /** * Color name for the badge text from the Quasar Color Palette */ badgeTextColor? : string /** * Notification corner to stick badge to; If notification is on the left side then default is top-right otherwise it is top-left */ badgePosition? : 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' /** * Style definitions to be attributed to the badge */ badgeStyle? : any[] | string | LooseDictionary /** * Class definitions to be attributed to the badge */ badgeClass? : any[] | string | LooseDictionary /** * Show progress bar to detail when notification will disappear automatically (unless timeout is 0) */ progress? : boolean /** * Class definitions to be attributed to the progress bar */ progressClass? : any[] | string | LooseDictionary /** * Add CSS class(es) to the notification for easier customization */ classes? : string /** * Key-value for attributes to be set on the notification */ attrs? : LooseDictionary /** * Amount of time to display (in milliseconds) */ timeout? : number /** * Notification actions (buttons); If a 'handler' is specified or not, clicking/tapping on the button will also close the notification; Also check 'closeBtn' convenience prop */ actions? : any[] /** * Function to call when notification gets dismissed */ onDismiss? : Function /** * Convenience way to add a dismiss button with a specific label, without using the 'actions' prop; If set to true, it uses a label accordding to the current Quasar language */ closeBtn? : boolean | string /** * Put notification into multi-line mode; If this prop isn't used and more than one 'action' is specified then notification goes into multi-line mode by default */ multiLine? : boolean }): void } export interface Platform { /** * Client browser User Agent */ userAgent : string /** * Client browser details (property names depend on browser) */ is : LooseDictionary /** * Client browser detectable properties */ has : { /** * Client browser runs on device with touch support */ touch : boolean /** * Client browser has Web Storage support */ webStorage : boolean } /** * Client browser environment */ within : { /** * Does the app run under an iframe? */ iframe : boolean } /** * For SSR usage only, and only on the global import (not on $q.platform) * @param ssrContext SSR Context Object * @returns Platform object (like $q.platform) for SSR usage purposes */ parseSSR (ssrContext : LooseDictionary): Platform } export interface Screen { /** * Screen width (in pixels) */ width : number /** * Screen height (in pixels) */ height : number /** * Tells current window breakpoint */ name : 'xs' | 'sm' | 'md' | 'lg' | 'xl' /** * Breakpoints (in pixels) */ sizes : { /** * Breakpoint width size (minimum size) */ sm : number /** * Breakpoint width size (minimum size) */ md : number /** * Breakpoint width size (minimum size) */ lg : number /** * Breakpoint width size (minimum size) */ xl : number } /** * Tells if current screen width is lower than breakpoint-name */ lt : { /** * Is current screen width lower than this breakpoint's lowest limit? */ sm : boolean /** * Is current screen width lower than this breakpoint's lowest limit? */ md : boolean /** * Is current screen width lower than this breakpoint's lowest limit? */ lg : boolean /** * Is current screen width lower than this breakpoint's lowest limit? */ xl : boolean } /** * Tells if current screen width is greater than breakpoint-name */ gt : { /** * Is current screen width greater than this breakpoint's max limit? */ xs : boolean /** * Is current screen width greater than this breakpoint's max limit? */ sm : boolean /** * Is current screen width greater than this breakpoint's max limit? */ md : boolean /** * Is current screen width greater than this breakpoint's max limit? */ lg : boolean } /** * Current screen width fits exactly 'xs' breakpoint */ xs : boolean /** * Current screen width fits exactly 'sm' breakpoint */ sm : boolean /** * Current screen width fits exactly 'md' breakpoint */ md : boolean /** * Current screen width fits exactly 'lg' breakpoint */ lg : boolean /** * Current screen width fits exactly 'xl' breakpoint */ xl : boolean /** * Override default breakpoint sizes * @param breakpoints Pick what you want to override */ setSizes (breakpoints : { /** * Breakpoint width size (minimum size) */ sm? : number /** * Breakpoint width size (minimum size) */ md? : number /** * Breakpoint width size (minimum size) */ lg? : number /** * Breakpoint width size (minimum size) */ xl? : number }): void /** * Debounce update of all props when screen width/height changes * @param amount Amount in milliseconds */ setDebounce (amount : number): void } export interface SessionStorage { /** * Check if storage item exists * @param key Entry key * @returns Does the item exists or not? */ has (key : string): boolean /** * Get storage number of entries * @returns Number of entries */ getLength (): number /** * Get a storage item value * @param key Entry key * @returns Storage item value */ getItem: WebStorageGetItemMethodType /** * Get the storage item value at specific index * @param index Entry index * @returns Storage item index */ getIndex: WebStorageGetIndexMethodType /** * Get the storage key at specific index * @param index Entry index * @returns Storage key */ getKey: WebStorageGetKeyMethodType /** * Retrieve all items in storage * @returns Object syntax: item name as Object key and its value */ getAll (): LooseDictionary /** * Retrieve all keys in storage * @returns Storage keys (Array of Strings) */ getAllKeys: WebStorageGetAllKeysMethodType /** * Set item in storage * @param key Entry key * @param value Entry value */ set (key : string, value : Date | RegExp | number | boolean | Function | LooseDictionary | any[] | string | null): void /** * Remove a storage item * @param key Storage key */ remove (key : string): void /** * Remove everything from the storage */ clear (): void /** * Determine if storage has any items * @returns Tells if storage is empty or not */ isEmpty (): boolean } export interface ClosePopup { } export interface Intersection { } export interface Morph { } export interface Mutation { } export interface Ripple { } export interface Scroll { } export interface ScrollFire { } export interface TouchHold { } export interface TouchPan { } export interface TouchRepeat { } export interface TouchSwipe { } export interface QAjaxBar extends ComponentPublicInstance { /** * Position within window of where QAjaxBar should be displayed */ position? : 'top' | 'right' | 'bottom' | 'left' /** * Size in CSS units, including unit name */ size? : string /** * Color name for component from the Quasar Color Palette */ color? : string /** * Skip Ajax hijacking (not a reactive prop) */ skipHijack? : boolean /** * Reverse direction of progress */ reverse? : boolean /** * Notify bar you are waiting for a new process to finish * @param speed Delay (in milliseconds) between progress auto-increments; If delay is 0 then it disables auto-incrementing */ start (speed? : number): void /** * Manually trigger a bar progress increment * @param amount Amount (0 < x <= 100) to increment with */ increment (amount? : number): void /** * Notify bar that one process you were waiting has finished */ stop (): void } export interface QAvatar extends ComponentPublicInstance { /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * The size in CSS units, including unit name, of the content (icon, text) */ fontSize? : string /** * Color name for component from the Quasar Color Palette */ color? : string /** * Overrides text color (if needed); Color name from the Quasar Color Palette */ textColor? : string /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ icon? : string /** * Removes border-radius so borders are squared */ square? : boolean /** * Applies a small standard border-radius for a squared shape of the component */ rounded? : boolean } export interface QBadge extends ComponentPublicInstance { /** * Color name for component from the Quasar Color Palette */ color? : string /** * Overrides text color (if needed); Color name from the Quasar Color Palette */ textColor? : string /** * Tell QBadge if it should float to the top right side of the relative positioned parent element or not */ floating? : boolean /** * Applies a 0.8 opacity; Useful especially for floating QBadge */ transparent? : boolean /** * Content can wrap to multiple lines */ multiLine? : boolean /** * Badge's content as string; overrides default slot if specified */ label? : string | number /** * Sets vertical-align CSS prop */ align? : 'top' | 'middle' | 'bottom' /** * Use 'outline' design (colored text and borders only) */ outline? : boolean /** * Makes a rounded shaped badge */ rounded? : boolean } export interface QBanner extends ComponentPublicInstance { /** * Display actions on same row as content */ inlineActions? : boolean /** * Dense mode; occupies less space */ dense? : boolean /** * Applies a small standard border-radius for a squared shape of the component */ rounded? : boolean /** * Notify the component that the background is a dark color */ dark? : boolean } export interface QBar extends ComponentPublicInstance { /** * Dense mode; occupies less space */ dense? : boolean /** * The component background color lights up the parent's background (as opposed to default behavior which is to darken it); Works unless you specify a CSS background color for it */ dark? : boolean } export interface QBreadcrumbs extends ComponentPublicInstance { /** * The string used to separate the breadcrumbs */ separator? : string /** * The color of the active breadcrumb, which can be any color from the Quasar Color Palette */ activeColor? : string /** * The gutter value allows you control over the space between the breadcrumb elements. */ gutter? : 'none' | 'xs' | 'sm' | 'md' | 'lg' | 'xl' /** * The color used to color the separator, which can be any color from the Quasar Color Palette */ separatorColor? : string /** * Specify how to align the breadcrumbs horizontally */ align? : 'left' | 'center' | 'right' | 'between' | 'around' | 'evenly' } export interface QBreadcrumbsEl extends ComponentPublicInstance { /** * Equivalent to Vue Router <router-link> 'to' property */ to? : string | LooseDictionary /** * Equivalent to Vue Router <router-link> 'exact' property */ exact? : boolean /** * Equivalent to Vue Router <router-link> 'replace' property */ replace? : boolean /** * Equivalent to Vue Router <router-link> 'active-class' property */ activeClass? : string /** * Equivalent to Vue Router <router-link> 'active-class' property */ exactActiveClass? : string /** * Put component in disabled mode */ disable? : boolean /** * The label text for the breadcrumb */ label? : string /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ icon? : string /** * HTML tag to use */ tag? : string /** * Configure material ripple (disable it by setting it to 'false' or supply a config object) */ ripple? : boolean | LooseDictionary } export interface QBtnDropdown extends ComponentPublicInstance { /** * Controls Menu show/hidden state; Either use this property (along with a listener for 'update:modelValue' event) OR use v-model directive */ modelValue : boolean /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * Define the button HTML DOM type */ type? : 'a' | 'submit' | 'button' | 'reset' /** * Equivalent to Vue Router <router-link> 'to' property */ to? : string | LooseDictionary /** * Equivalent to Vue Router <router-link> 'replace' property */ replace? : boolean /** * Equivalent to Vue Router <router-link> 'append' property */ append? : boolean /** * The text that will be shown on the button */ label? : string | number /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ icon? : string /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ iconRight? : string /** * Use 'outline' design */ outline? : boolean /** * Use 'flat' design */ flat? : boolean /** * Remove shadow */ unelevated? : boolean /** * Applies a more prominent border-radius for a squared shape button */ rounded? : boolean /** * Use 'push' design */ push? : boolean /** * Applies a glossy effect */ glossy? : boolean /** * Makes button size and shape to fit a Floating Action Button */ fab? : boolean /** * Makes button size and shape to fit a small Floating Action Button */ fabMini? : boolean /** * Apply custom padding (vertical [horizontal]); Size in CSS units, including unit name or standard size name (none|xs|sm|md|lg|xl); Also removes the min width and height when set */ padding? : string /** * Color name for component from the Quasar Color Palette */ color? : string /** * Overrides text color (if needed); Color name from the Quasar Color Palette */ textColor? : string /** * Avoid turning label text into caps (which happens by default) */ noCaps? : boolean /** * Avoid label text wrapping */ noWrap? : boolean /** * Dense mode; occupies less space */ dense? : boolean /** * Configure material ripple (disable it by setting it to 'false' or supply a config object) */ ripple? : boolean | LooseDictionary /** * Tabindex HTML attribute value */ tabindex? : number | string /** * Label or content alignment */ align? : 'left' | 'right' | 'center' | 'around' | 'between' | 'evenly' /** * Stack icon and label vertically instead of on same line (like it is by default) */ stack? : boolean /** * When used on flexbox parent, button will stretch to parent's height */ stretch? : boolean /** * Put button into loading state (displays a QSpinner -- can be overridden by using a 'loading' slot) */ loading? : boolean /** * Put component in disabled mode */ disable? : boolean /** * Split dropdown icon into its own button */ split? : boolean /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ dropdownIcon? : string /** * Disable main button (useful along with 'split' prop) */ disableMainBtn? : boolean /** * Disables dropdown (dropdown button if using along 'split' prop) */ disableDropdown? : boolean /** * Disables the rotation of the dropdown icon when state is toggled */ noIconAnimation? : boolean /** * Style definitions to be attributed to the menu */ contentStyle? : any[] | string | LooseDictionary /** * Class definitions to be attributed to the menu */ contentClass? : any[] | string | LooseDictionary /** * Allows the menu to cover the button. When used, the 'menu-self' and 'menu-fit' props are no longer effective */ cover? : boolean /** * Allows the menu to not be dismissed by a click/tap outside of the menu or by hitting the ESC key */ persistent? : boolean /** * Changing route app won't dismiss the popup; No need to set it if 'persistent' prop is also set */ noRouteDismiss? : boolean /** * Allows any click/tap in the menu to close it; Useful instead of attaching events to each menu item that should close the menu on click/tap */ autoClose? : boolean /** * Two values setting the starting position or anchor point of the menu relative to its target */ menuAnchor? : 'top left' | 'top middle' | 'top right' | 'top start' | 'top end' | 'center left' | 'center middle' | 'center right' | 'center start' | 'center end' | 'bottom left' | 'bottom middle' | 'bottom right' | 'bottom start' | 'bottom end' /** * Two values setting the menu's own position relative to its target */ menuSelf? : 'top left' | 'top middle' | 'top right' | 'top start' | 'top end' | 'center left' | 'center middle' | 'center right' | 'center start' | 'center end' | 'bottom left' | 'bottom middle' | 'bottom right' | 'bottom start' | 'bottom end' /** * An array of two numbers to offset the menu horizontally and vertically in pixels */ menuOffset? : any[] /** * Triggers component to show * @param evt JS event object */ show (evt? : LooseDictionary): void /** * Triggers component to hide * @param evt JS event object */ hide (evt? : LooseDictionary): void /** * Triggers component to toggle between show/hide * @param evt JS event object */ toggle (evt? : LooseDictionary): void } export interface QBtnGroup extends ComponentPublicInstance { /** * Spread horizontally to all available space */ spread? : boolean /** * Use 'outline' design for buttons */ outline? : boolean /** * Use 'flat' design for buttons */ flat? : boolean /** * Remove shadow on buttons */ unelevated? : boolean /** * Applies a more prominent border-radius for squared shape buttons */ rounded? : boolean /** * Use 'push' design for buttons */ push? : boolean /** * When used on flexbox parent, buttons will stretch to parent's height */ stretch? : boolean /** * Applies a glossy effect */ glossy? : boolean } export interface QBtnToggle extends ComponentPublicInstance { /** * Used to specify the name of the control; Useful if dealing with forms submitted directly to a URL */ name? : string /** * Model of the component; Either use this property (along with a listener for 'update:modelValue' event) OR use v-model directive */ modelValue : any /** * Array of Objects defining each option */ options : { /** * Key-value for attributes to be set on the button */ attrs? : LooseDictionary /** * Label of option button; Use this prop and/or 'icon', but at least one is required */ label? : string /** * Icon of option button; Use this prop and/or 'label', but at least one is required */ icon? : string /** * Value of the option that will be used by component model */ value : any /** * Slot name to use for this button content; Useful for customizing content or even add tooltips */ slot? : string [index: string]: any }[] /** * Color name for component from the Quasar Color Palette */ color? : string /** * Overrides text color (if needed); Color name from the Quasar Color Palette */ textColor? : string /** * Color name for component from the Quasar Color Palette */ toggleColor? : string /** * Overrides text color (if needed); Color name from the Quasar Color Palette */ toggleTextColor? : string /** * Spread horizontally to all available space */ spread? : boolean /** * Use 'outline' design */ outline? : boolean /** * Use 'flat' design */ flat? : boolean /** * Remove shadow */ unelevated? : boolean /** * Applies a more prominent border-radius for a squared shape button */ rounded? : boolean /** * Use 'push' design */ push? : boolean /** * Applies a glossy effect */ glossy? : boolean /** * Button size name or a CSS unit including unit name */ size? : string /** * Apply custom padding (vertical [horizontal]); Size in CSS units, including unit name or standard size name (none|xs|sm|md|lg|xl); Also removes the min width and height when set */ padding? : string /** * Avoid turning label text into caps (which happens by default) */ noCaps? : boolean /** * Avoid label text wrapping */ noWrap? : boolean /** * Configure material ripple (disable it by setting it to 'false' or supply a config object) */ ripple? : boolean | LooseDictionary /** * Dense mode; occupies less space */ dense? : boolean /** * Put component in readonly mode */ readonly? : boolean /** * Put component in disabled mode */ disable? : boolean /** * Stack icon and label vertically instead of on same line (like it is by default) */ stack? : boolean /** * When used on flexbox parent, button will stretch to parent's height */ stretch? : boolean /** * Clears model on click of the already selected button */ clearable? : boolean } export interface QBtn extends ComponentPublicInstance { /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * Define the button HTML DOM type */ type? : 'a' | 'submit' | 'button' | 'reset' /** * Equivalent to Vue Router <router-link> 'to' property */ to? : string | LooseDictionary /** * Equivalent to Vue Router <router-link> 'replace' property */ replace? : boolean /** * Equivalent to Vue Router <router-link> 'append' property */ append? : boolean /** * The text that will be shown on the button */ label? : string | number /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ icon? : string /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ iconRight? : string /** * Use 'outline' design */ outline? : boolean /** * Use 'flat' design */ flat? : boolean /** * Remove shadow */ unelevated? : boolean /** * Applies a more prominent border-radius for a squared shape button */ rounded? : boolean /** * Use 'push' design */ push? : boolean /** * Applies a glossy effect */ glossy? : boolean /** * Makes button size and shape to fit a Floating Action Button */ fab? : boolean /** * Makes button size and shape to fit a small Floating Action Button */ fabMini? : boolean /** * Apply custom padding (vertical [horizontal]); Size in CSS units, including unit name or standard size name (none|xs|sm|md|lg|xl); Also removes the min width and height when set */ padding? : string /** * Color name for component from the Quasar Color Palette */ color? : string /** * Overrides text color (if needed); Color name from the Quasar Color Palette */ textColor? : string /** * Avoid turning label text into caps (which happens by default) */ noCaps? : boolean /** * Avoid label text wrapping */ noWrap? : boolean /** * Dense mode; occupies less space */ dense? : boolean /** * Configure material ripple (disable it by setting it to 'false' or supply a config object) */ ripple? : boolean | LooseDictionary /** * Tabindex HTML attribute value */ tabindex? : number | string /** * Label or content alignment */ align? : 'left' | 'right' | 'center' | 'around' | 'between' | 'evenly' /** * Stack icon and label vertically instead of on same line (like it is by default) */ stack? : boolean /** * When used on flexbox parent, button will stretch to parent's height */ stretch? : boolean /** * Put button into loading state (displays a QSpinner -- can be overridden by using a 'loading' slot) */ loading? : boolean /** * Put component in disabled mode */ disable? : boolean /** * Makes a circle shaped button */ round? : boolean /** * Percentage (0.0 < x < 100.0); To be used along 'loading' prop; Display a progress bar on the background */ percentage? : number /** * Progress bar on the background should have dark color; To be used along with 'percentage' and 'loading' props */ darkPercentage? : boolean /** * Emulate click on QBtn * @param evt JS event object */ click (evt? : LooseDictionary): void } export interface QCard extends ComponentPublicInstance { /** * Notify the component that the background is a dark color */ dark? : boolean /** * Removes border-radius so borders are squared */ square? : boolean /** * Applies a 'flat' design (no default shadow) */ flat? : boolean /** * Applies a default border to the component */ bordered? : boolean /** * HTML tag to use */ tag? : string } export interface QCardActions extends ComponentPublicInstance { /** * Specify how to align the actions */ align? : 'left' | 'center' | 'right' | 'between' | 'around' | 'evenly' | 'stretch' /** * Display actions one below the other */ vertical? : boolean } export interface QCardSection extends ComponentPublicInstance { /** * Display a horizontal section (will have no padding and can contain other QCardSection) */ horizontal? : boolean /** * HTML tag to use */ tag? : string } export interface QCarousel extends ComponentPublicInstance { /** * Fullscreen mode */ fullscreen? : boolean /** * Changing route app won't exit fullscreen */ noRouteFullscreenExit? : boolean /** * Model of the component defining the current panel's name; If a Number is used, it does not define the panel's index, but rather the panel's name which can also be an Integer; Either use this property (along with a listener for 'update:model-value' event) OR use the v-model directive. */ modelValue? : any /** * Equivalent to using Vue's native <keep-alive> component on the content */ keepAlive? : boolean /** * Equivalent to using Vue's native include prop for <keep-alive>; Values must be valid Vue component names */ keepAliveInclude? : string | any[] | RegExp /** * Equivalent to using Vue's native exclude prop for <keep-alive>; Values must be valid Vue component names */ keepAliveExclude? : string | any[] | RegExp /** * Equivalent to using Vue's native max prop for <keep-alive> */ keepAliveMax? : number /** * Enable transitions between panel (also see 'transition-prev' and 'transition-next' props) */ animated? : boolean /** * Makes component appear as infinite (when reaching last panel, next one will become the first one) */ infinite? : boolean /** * Enable swipe events (may interfere with content's touch/mouse events) */ swipeable? : boolean /** * Default transitions and swipe actions will be on the vertical axis */ vertical? : boolean /** * One of Quasar's embedded transitions (has effect only if 'animated' prop is set) */ transitionPrev? : string /** * One of Quasar's embedded transitions (has effect only if 'animated' prop is set) */ transitionNext? : string /** * Notify the component that the background is a dark color */ dark? : boolean /** * Height of Carousel in CSS units, including unit name */ height? : string /** * Applies a default padding to each slide, according to the usage of 'arrows' and 'navigation' props */ padding? : boolean /** * Color name for QCarousel button controls (arrows, navigation) from the Quasar Color Palette */ controlColor? : string /** * Color name for text color of QCarousel button controls (arrows, navigation) from the Quasar Color Palette */ controlTextColor? : string /** * Type of button to use for controls (arrows, navigation) */ controlType? : 'regular' | 'flat' | 'outline' | 'push' | 'unelevated' /** * Jump to next slide at fixed time intervals (in milliseconds); 'false' disables autoplay, 'true' enables it for 5000ms intervals */ autoplay? : number | boolean /** * Show navigation arrow buttons */ arrows? : boolean /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ prevIcon? : string /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ nextIcon? : string /** * Show navigation dots */ navigation? : boolean /** * Side to stick navigation to */ navigationPosition? : 'top' | 'right' | 'bottom' | 'left' /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ navigationIcon? : string /** * Icon name following Quasar convention for the active (current slide) navigation icon; Make sure you have the icon library installed unless you are using 'img:' prefix */ navigationActiveIcon? : string /** * Show thumbnails */ thumbnails? : boolean /** * Toggle the view to be fullscreen or not fullscreen */ toggleFullscreen (): void /** * Enter the fullscreen view */ setFullscreen (): void /** * Leave the fullscreen view */ exitFullscreen (): void /** * Go to next panel */ next (): void /** * Go to previous panel */ previous (): void /** * Go to specific panel * @param panelName Panel's name, which may be a String or Number; Number does not refers to panel index, but to its name, which may be an Integer */ goTo (panelName : string | number): void } export interface QCarouselControl extends ComponentPublicInstance { /** * Side/corner to stick to */ position? : 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left' | 'top' | 'right' | 'bottom' | 'left' /** * An array of two numbers to offset the component horizontally and vertically (in pixels) */ offset? : any[] } export interface QCarouselSlide extends ComponentPublicInstance { /** * Slide name */ name : any /** * Put component in disabled mode */ disable? : boolean /** * URL pointing to a slide background image (use statics folder) */ imgSrc? : string } export interface QChatMessage extends ComponentPublicInstance { /** * Render as a sent message (so from current user) */ sent? : boolean /** * Renders a label header/section only */ label? : string /** * Color name (from the Quasar Color Palette) for chat bubble background */ bgColor? : string /** * Color name (from the Quasar Color Palette) for chat bubble text */ textColor? : string /** * Author's name */ name? : string /** * URL to the avatar image of the author */ avatar? : string /** * Array of strings that are the message body. Strings are not sanitized (see details in docs) */ text? : any[] /** * Creation timestamp */ stamp? : string /** * 1-12 out of 12 (same as col-*) */ size? : string /** * Render the label as HTML; This can lead to XSS attacks so make sure that you sanitize the message first */ labelHtml? : boolean /** * Render the name as HTML; This can lead to XSS attacks so make sure that you sanitize the message first */ nameHtml? : boolean /** * Render the text as HTML; This can lead to XSS attacks so make sure that you sanitize the message first */ textHtml? : boolean /** * Render the stamp as HTML; This can lead to XSS attacks so make sure that you sanitize the message first */ stampHtml? : boolean } export interface QCheckbox extends ComponentPublicInstance { /** * Used to specify the name of the control; Useful if dealing with forms submitted directly to a URL */ name? : string /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * Model of the component; Either use this property (along with a listener for 'update:model-value' event) OR use v-model directive */ modelValue : any | any[] /** * Works when model ('value') is Array. It tells the component which value should add/remove when ticked/unticked */ val? : any /** * What model value should be considered as checked/ticked/on? */ trueValue? : any /** * What model value should be considered as unchecked/unticked/off? */ falseValue? : any /** * What model value should be considered as 'indeterminate'? */ indeterminateValue? : any /** * Determines toggle order of the two states ('t' stands for state of true, 'f' for state of false); If 'toggle-indeterminate' is true, then the order is: indet -> first state -> second state -> indet (and repeat), otherwise: indet -> first state -> second state -> first state -> second state -> ... */ toggleOrder? : 'tf' | 'ft' /** * When user clicks/taps on the component, should we toggle through the indeterminate state too? */ toggleIndeterminate? : boolean /** * Label to display along the component (or use the default slot instead of this prop) */ label? : string /** * Label (if any specified) should be displayed on the left side of the component */ leftLabel? : boolean /** * Color name for component from the Quasar Color Palette */ color? : string /** * Should the color (if specified any) be kept when the component is unticked/ off? */ keepColor? : boolean /** * Notify the component that the background is a dark color */ dark? : boolean /** * Dense mode; occupies less space */ dense? : boolean /** * Put component in disabled mode */ disable? : boolean /** * Tabindex HTML attribute value */ tabindex? : number | string /** * Toggle the state (of the model) */ toggle (): void } export interface QChip extends ComponentPublicInstance { /** * Dense mode; occupies less space */ dense? : boolean /** * QChip size name or a CSS unit including unit name */ size? : string /** * Notify the component that the background is a dark color */ dark? : boolean /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ icon? : string /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ iconRight? : string /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ iconRemove? : string /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ iconSelected? : string /** * Chip's content as string; overrides default slot if specified */ label? : string | number /** * Color name for component from the Quasar Color Palette */ color? : string /** * Overrides text color (if needed); Color name from the Quasar Color Palette */ textColor? : string /** * Model of the component determining if QChip should be rendered or not */ modelValue? : boolean /** * Model for QChip if it's selected or not */ selected? : boolean /** * Sets a low value for border-radius instead of the default one, making it close to a square */ square? : boolean /** * Display using the 'outline' design */ outline? : boolean /** * Is QChip clickable? If it's the case, then it will add hover effects and emit 'click' events */ clickable? : boolean /** * If set, then it displays a 'remove' icon that when clicked the QChip emits 'remove' event */ removable? : boolean /** * Configure material ripple (disable it by setting it to 'false' or supply a config object) */ ripple? : boolean | LooseDictionary /** * Tabindex HTML attribute value */ tabindex? : number | string /** * Put component in disabled mode */ disable? : boolean } export interface QCircularProgress extends ComponentPublicInstance { /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * Current progress (must be between min/max) */ value? : number /** * Minimum value defining 'no progress' (must be lower than 'max') */ min? : number /** * Maximum value defining 100% progress made (must be higher than 'min') */ max? : number /** * Color name for the arc progress from the Quasar Color Palette */ color? : string /** * Color name for the center part of the component from the Quasar Color Palette */ centerColor? : string /** * Color name for the track of the component from the Quasar Color Palette */ trackColor? : string /** * Size of text in CSS units, including unit name. Suggestion: use 'em' units to sync with component size */ fontSize? : string /** * Thickness of progress arc as a ratio (0.0 < x < 1.0) of component size */ thickness? : number /** * Angle to rotate progress arc by */ angle? : number /** * Put component into 'indeterminate' state; Ignores 'value' prop */ indeterminate? : boolean /** * Enables the default slot and uses it (if available), otherwise it displays the 'value' prop as text; Make sure the text has enough space to be displayed inside the component */ showValue? : boolean /** * Reverses the direction of progress; Only for determined state */ reverse? : boolean /** * No animation when model changes */ instantFeedback? : boolean } export interface QColor extends ComponentPublicInstance { /** * Used to specify the name of the control; Useful if dealing with forms submitted directly to a URL */ name? : string /** * Model of the component; Either use this property (along with a listener for 'update:model-value' event) OR use v-model directive */ modelValue : string /** * The default value to show when the model doesn't have one */ defaultValue? : string /** * The default view of the picker */ defaultView? : 'spectrum' | 'tune' | 'palette' /** * Forces a certain model format upon the model */ formatModel? : 'auto' | 'hex' | 'rgb' | 'hexa' | 'rgba' /** * Use a custom palette of colors for the palette tab */ palette? : any[] /** * Removes border-radius so borders are squared */ square? : boolean /** * Applies a 'flat' design (no default shadow) */ flat? : boolean /** * Applies a default border to the component */ bordered? : boolean /** * Do not render header */ noHeader? : boolean /** * Do not render footer; Useful when you want a specific view ('default-view' prop) and don't want the user to be able to switch it */ noFooter? : boolean /** * Put component in disabled mode */ disable? : boolean /** * Put component in readonly mode */ readonly? : boolean /** * Notify the component that the background is a dark color */ dark? : boolean } export interface QDate extends ComponentPublicInstance { /** * Used to specify the name of the control; Useful if dealing with forms submitted directly to a URL */ name? : string /** * Display the component in landscape mode */ landscape? : boolean /** * Mask (formatting string) used for parsing and formatting value */ mask? : string /** * Locale formatting options */ locale? : { /** * List of full day names (DDDD), starting with Sunday */ days? : any[] /** * List of short day names (DDD), starting with Sunday */ daysShort? : any[] /** * List of full month names (MMMM), starting with January */ months? : any[] /** * List of short month names (MMM), starting with January */ monthsShort? : any[] } /** * Specify calendar type */ calendar? : 'gregorian' | 'persian' /** * Color name for component from the Quasar Color Palette */ color? : string /** * Overrides text color (if needed); Color name from the Quasar Color Palette */ textColor? : string /** * Notify the component that the background is a dark color */ dark? : boolean /** * Removes border-radius so borders are squared */ square? : boolean /** * Applies a 'flat' design (no default shadow) */ flat? : boolean /** * Applies a default border to the component */ bordered? : boolean /** * Put component in readonly mode */ readonly? : boolean /** * Put component in disabled mode */ disable? : boolean /** * Date(s) of the component; Must be Array if using 'multiple' prop; Either use this property (along with a listener for 'update:model-value' event) OR use v-model directive */ modelValue : string | any[] | LooseDictionary /** * When specified, it overrides the default header title; Makes sense when not in 'minimal' mode */ title? : string /** * When specified, it overrides the default header subtitle; Makes sense when not in 'minimal' mode */ subtitle? : string /** * The default year and month to display (in YYYY/MM format) when model is unfilled (undefined or null); Please ensure it is within the navigation min/max year-month (if using them) */ defaultYearMonth? : string /** * The view which will be displayed by default */ defaultView? : 'Calendar' | 'Months' | 'Years' /** * Show the years selector in months view */ yearsInMonthView? : boolean /** * A list of events to highlight on the calendar; If using a function, it receives the date as a String and must return a Boolean (matches or not); If using a function then for best performance, reference it from your scope and do not define it inline */ events? : any[] | Function /** * Color name (from the Quasar Color Palette); If using a function, it receives the date as a String and must return a String (color for the received date); If using a function then for best performance, reference it from your scope and do not define it inline */ eventColor? : string | Function /** * Optionally configure the days that are selectable; If using a function, it receives the date as a String and must return a Boolean (is date acceptable or not); If using a function then for best performance, reference it from your scope and do not define it inline; Incompatible with 'range' prop */ options? : any[] | Function /** * Lock user from navigating below a specific year+month (in YYYY/MM format); This prop is not used to correct the model; You might want to also use 'default-year-month' prop */ navigationMinYearMonth? : string /** * Lock user from navigating above a specific year+month (in YYYY/MM format); This prop is not used to correct the model; You might want to also use 'default-year-month' prop */ navigationMaxYearMonth? : string /** * Remove ability to unselect a date; It does not apply to selecting a range over already selected dates */ noUnset? : boolean /** * Sets the day of the week that is considered the first day (0 - Sunday, 1 - Monday, ...); This day will show in the left-most column of the calendar */ firstDayOfWeek? : string | number /** * Display a button that selects the current day */ todayBtn? : boolean /** * Don’t display the header */ minimal? : boolean /** * Allow multiple selection; Model must be Array */ multiple? : boolean /** * Allow range selection; Partial compatibility with 'options' prop: selected ranges might also include 'unselectable' days */ range? : boolean /** * Emit model when user browses month and year too; ONLY for single selection (non-multiple, non-range) */ emitImmediately? : boolean /** * Change model to today */ setToday (): void /** * Change current view * @param view QDate view name */ setView (view : 'Calendar' | 'Months' | 'Years'): void /** * Increment or decrement calendar view's month or year * @param type What to increment/decrement * @param descending Decrement? */ offsetCalendar (type : 'month' | 'year', descending? : boolean): void /** * Change current year and month of the Calendar view; It gets corrected if using navigation-min/max-year-month and sets the current view to Calendar * @param year The year * @param month The month */ setCalendarTo (year? : number, month? : number): void /** * Configure the current editing range * @param from Definition of date from where the range begins * @param to Definition of date to where the range ends */ setEditingRange (from? : { /** * The year */ year? : number /** * The month */ month? : number /** * The day of month */ day? : number }, to? : { /** * The year */ year? : number /** * The month */ month? : number /** * The day of month */ day? : number }): void } export interface QDialog extends ComponentPublicInstance { /** * Model of the component defining shown/hidden state; Either use this property (along with a listener for 'update:model-value' event) OR use v-model directive */ modelValue? : boolean /** * User cannot dismiss Dialog if clicking outside of it or hitting ESC key; Also, an app route change won't dismiss it */ persistent? : boolean /** * User cannot dismiss Dialog by hitting ESC key; No need to set it if 'persistent' prop is also set */ noEscDismiss? : boolean /** * User cannot dismiss Dialog by clicking outside of it; No need to set it if 'persistent' prop is also set */ noBackdropDismiss? : boolean /** * Changing route app won't dismiss Dialog; No need to set it if 'persistent' prop is also set */ noRouteDismiss? : boolean /** * Any click/tap inside of the dialog will close it */ autoClose? : boolean /** * Put Dialog into seamless mode; Does not use a backdrop so user is able to interact with the rest of the page too */ seamless? : boolean /** * Put Dialog into maximized mode */ maximized? : boolean /** * Dialog will try to render with same width as the window */ fullWidth? : boolean /** * Dialog will try to render with same height as the window */ fullHeight? : boolean /** * Stick dialog to one of the sides (top, right, bottom or left) */ position? : 'standard' | 'top' | 'right' | 'bottom' | 'left' /** * One of Quasar's embedded transitions */ transitionShow? : string /** * One of Quasar's embedded transitions */ transitionHide? : string /** * Forces content to have squared borders */ square? : boolean /** * (Accessibility) When Dialog gets hidden, do not refocus on the DOM element that previously had focus */ noRefocus? : boolean /** * (Accessibility) When Dialog gets shown, do not switch focus on it */ noFocus? : boolean /** * Triggers component to show * @param evt JS event object */ show (evt? : LooseDictionary): void /** * Triggers component to hide * @param evt JS event object */ hide (evt? : LooseDictionary): void /** * Triggers component to toggle between show/hide * @param evt JS event object */ toggle (evt? : LooseDictionary): void /** * Focus dialog; if you have content with autofocus attribute, it will directly focus it */ focus (): void /** * Shakes dialog */ shake (): void } export interface QDrawer extends ComponentPublicInstance { /** * Model of the component defining shown/hidden state; Either use this property (along with a listener for 'update:model-value' event) OR use v-model directive */ modelValue? : boolean /** * Side to attach to */ side? : 'left' | 'right' /** * Puts drawer into overlay mode (does not occupy space on screen, narrowing the page) */ overlay? : boolean /** * Width of drawer (in pixels) */ width? : number /** * Puts drawer into mini mode */ mini? : boolean /** * Width of drawer (in pixels) when in mini mode */ miniWidth? : number /** * Notify the component that the background is a dark color */ dark? : boolean /** * Mini mode will expand as an overlay */ miniToOverlay? : boolean /** * Breakpoint (in pixels) of layout width up to which mobile mode is used */ breakpoint? : number /** * Overrides the default dynamic mode into which the drawer is put on */ behavior? : 'default' | 'desktop' | 'mobile' /** * Applies a default border to the component */ bordered? : boolean /** * Adds a default shadow to the header */ elevated? : boolean /** * Prevents drawer from auto-closing when app's route changes */ persistent? : boolean /** * Forces drawer to be shown on screen on initial render if the layout width is above breakpoint, regardless of v-model; This is the default behavior when SSR is taken over by client on initial render */ showIfAbove? : boolean /** * Disables the default behavior where drawer can be swiped into view; Useful for iOS platforms where it might interfere with Safari's 'swipe to go to previous/next page' feature */ noSwipeOpen? : boolean /** * Disables the default behavior where drawer can be swiped out of view (applies to drawer content only); Useful for iOS platforms where it might interfere with Safari's 'swipe to go to previous/next page' feature */ noSwipeClose? : boolean /** * Disables the default behavior where drawer backdrop can be swiped */ noSwipeBackdrop? : boolean /** * Triggers component to show * @param evt JS event object */ show (evt? : LooseDictionary): void /** * Triggers component to hide * @param evt JS event object */ hide (evt? : LooseDictionary): void /** * Triggers component to toggle between show/hide * @param evt JS event object */ toggle (evt? : LooseDictionary): void } export interface QEditor extends ComponentPublicInstance { /** * Fullscreen mode */ fullscreen? : boolean /** * Changing route app won't exit fullscreen */ noRouteFullscreenExit? : boolean /** * Model of the component; Either use this property (along with a listener for 'update:modelValue' event) OR use v-model directive */ modelValue : string /** * Put component in readonly mode */ readonly? : boolean /** * Removes border-radius so borders are squared */ square? : boolean /** * Applies a 'flat' design (no borders) */ flat? : boolean /** * Dense mode; toolbar buttons are shown on one-line only */ dense? : boolean /** * Notify the component that the background is a dark color */ dark? : boolean /** * Put component in disabled mode */ disable? : boolean /** * CSS unit for the minimum height of the editable area */ minHeight? : string /** * CSS unit for maximum height of the input area */ maxHeight? : string /** * CSS value to set the height of the editable area */ height? : string /** * Definition of commands and their buttons to be included in the 'toolbar' prop */ definitions? : { /** * Label of the button */ label? : string /** * Text to be displayed as a tooltip on hover */ tip? : string /** * HTML formatted text to be displayed within a tooltip on hover */ htmlTip? : string /** * Icon of the button */ icon? : string /** * Keycode of a key to be used together with the <ctrl> key for use as a shortcut to trigger this element */ key? : number /** * Either this or "cmd" is required. Function for when button gets clicked/tapped. */ handler? : Function /** * Either this or "handler" is required. This must be a valid execCommand method according to the designMode API. */ cmd? : string /** * Only set a param if using a "cmd". This is commonly text or HTML to inject, but is highly dependent upon the specific cmd being called. */ param? : string /** * Is button disabled? If specifying a function, return a Boolean value. */ disable? : boolean | Function /** * Pass the value "no-state" if the button should not have an "active" state */ type? : 'no-state' /** * Lock the button label, so it doesn't change based on the child option selected. */ fixedLabel? : boolean /** * Lock the button icon, so it doesn't change based on the child option selected. */ fixedIcon? : boolean /** * Highlight the toolbar button, when a child option has been selected. */ highlight? : boolean } /** * Object with definitions of fonts */ fonts? : LooseDictionary /** * An array of arrays of Objects/Strings that you use to define the construction of the elements and commands available in the toolbar */ toolbar? : any[] /** * Font color (from the Quasar Palette) of buttons and text in the toolbar */ toolbarColor? : string /** * Text color (from the Quasar Palette) of toolbar commands */ toolbarTextColor? : string /** * Choose the active color (from the Quasar Palette) of toolbar commands button */ toolbarToggleColor? : string /** * Toolbar background color (from Quasar Palette) */ toolbarBg? : string /** * Toolbar buttons are rendered "outlined" */ toolbarOutline? : boolean /** * Toolbar buttons are rendered as a "push-button" type */ toolbarPush? : boolean /** * Toolbar buttons are rendered "rounded" */ toolbarRounded? : boolean /** * Paragraph tag to be used */ paragraphTag? : 'div' | 'p' /** * Object with CSS properties and values for styling the container of QEditor */ contentStyle? : LooseDictionary /** * CSS classes for the input area */ contentClass? : LooseDictionary | any[] | string /** * Text to display as placeholder */ placeholder? : string /** * Toggle the view to be fullscreen or not fullscreen */ toggleFullscreen (): void /** * Enter the fullscreen view */ setFullscreen (): void /** * Leave the fullscreen view */ exitFullscreen (): void /** * Run contentEditable command at caret position and range * @param cmd Must be a valid execCommand method according to the designMode API * @param param The argument to pass to the command * @param update Refresh the toolbar */ runCmd (cmd : string, param? : string, update? : boolean): void /** * Hide the link editor if visible and force the instance to re-render */ refreshToolbar (): void /** * Focus on the contentEditable at saved cursor position */ focus (): void /** * Retrieve the content of the Editor * @returns Provides the pure HTML within the editable area */ getContentEl (): Element } export interface QExpansionItem extends ComponentPublicInstance { /** * Equivalent to Vue Router <router-link> 'to' property */ to? : string | LooseDictionary /** * Equivalent to Vue Router <router-link> 'exact' property */ exact? : boolean /** * Equivalent to Vue Router <router-link> 'replace' property */ replace? : boolean /** * Equivalent to Vue Router <router-link> 'active-class' property */ activeClass? : string /** * Equivalent to Vue Router <router-link> 'active-class' property */ exactActiveClass? : string /** * Put component in disabled mode */ disable? : boolean /** * Model of the component defining 'open' state; Either use this property (along with a listener for 'update:modelValue' event) OR use v-model directive */ modelValue? : boolean /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ icon? : string /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ expandIcon? : string /** * Expand icon name (following Quasar convention) for when QExpansionItem is expanded; When used, it also disables the rotation animation of the expand icon; Make sure you have the icon library installed unless you are using 'img:' prefix */ expandedIcon? : string /** * Apply custom class(es) to the expand icon item section */ expandIconClass? : any[] | string | LooseDictionary /** * Header label (unless using 'header' slot) */ label? : string /** * Apply ellipsis when there's not enough space to render on the specified number of lines; If more than one line specified, then it will only work on webkit browsers because it uses the '-webkit-line-clamp' CSS property! */ labelLines? : number | string /** * Header sub-label (unless using 'header' slot) */ caption? : string /** * Apply ellipsis when there's not enough space to render on the specified number of lines; If more than one line specified, then it will only work on webkit browsers because it uses the '-webkit-line-clamp' CSS property! */ captionLines? : number | string /** * Notify the component that the background is a dark color */ dark? : boolean /** * Dense mode; occupies less space */ dense? : boolean /** * Animation duration (in milliseconds) */ duration? : number /** * Apply an inset to header (unless using 'header' slot); Useful when header avatar/left side is missing but you want to align content with other items that do have a left side, or when you're building a menu */ headerInsetLevel? : number /** * Apply an inset to content (changes content padding) */ contentInsetLevel? : number /** * Apply a top and bottom separator when expansion item is opened */ expandSeparator? : boolean /** * Puts expansion item into open state on initial render; Overridden by v-model if used */ defaultOpened? : boolean /** * Applies the expansion events to the expand icon only and not to the whole header */ expandIconToggle? : boolean /** * Switch expand icon side (from default 'right' to 'left') */ switchToggleSide? : boolean /** * Use dense mode for expand icon */ denseToggle? : boolean /** * Register expansion item into a group (unique name that must be applied to all expansion items in that group) for coordinated open/close state within the group a.k.a. 'accordion mode' */ group? : string /** * Put expansion list into 'popup' mode */ popup? : boolean /** * Apply custom style to the header */ headerStyle? : any[] | string | LooseDictionary /** * Apply custom class(es) to the header */ headerClass? : any[] | string | LooseDictionary /** * Triggers component to show * @param evt JS event object */ show (evt? : LooseDictionary): void /** * Triggers component to hide * @param evt JS event object */ hide (evt? : LooseDictionary): void /** * Triggers component to toggle between show/hide * @param evt JS event object */ toggle (evt? : LooseDictionary): void } export interface QFab extends ComponentPublicInstance { /** * Define the button HTML DOM type */ type? : 'a' | 'submit' | 'button' | 'reset' /** * Use 'outline' design for Fab button */ outline? : boolean /** * Use 'push' design for Fab button */ push? : boolean /** * Use 'flat' design for Fab button */ flat? : boolean /** * Remove shadow */ unelevated? : boolean /** * Apply custom padding (vertical [horizontal]); Size in CSS units, including unit name or standard size name (none|xs|sm|md|lg|xl); Also removes the min width and height when set */ padding? : string /** * Color name for component from the Quasar Color Palette */ color? : string /** * Overrides text color (if needed); Color name from the Quasar Color Palette */ textColor? : string /** * Apply the glossy effect over the button */ glossy? : boolean /** * Display label besides the FABs, as external content */ externalLabel? : boolean /** * The label that will be shown when Fab is extended */ label? : string | number /** * Position of the label around the icon */ labelPosition? : 'top' | 'right' | 'bottom' | 'left' /** * Hide the label; Useful for animation purposes where you toggle the visibility of the label */ hideLabel? : boolean /** * Class definitions to be attributed to the label container */ labelClass? : any[] | string | LooseDictionary /** * Style definitions to be attributed to the label container */ labelStyle? : any[] | string | LooseDictionary /** * Apply a rectangle aspect to the FAB */ square? : boolean /** * Put component in disabled mode */ disable? : boolean /** * Tabindex HTML attribute value */ tabindex? : number | string /** * Controls state of fab actions (showing/hidden); Works best with v-model directive, otherwise use along listening to 'update:modelValue' event */ modelValue? : boolean /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ icon? : string /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ activeIcon? : string /** * Hide the icon (don't use any) */ hideIcon? : boolean /** * Direction to expand Fab Actions to */ direction? : 'up' | 'right' | 'down' | 'left' /** * The side of the Fab where Fab Actions will expand (only when direction is 'up' or 'down') */ verticalActionsAlign? : 'left' | 'center' | 'right' /** * By default, Fab Actions are hidden when user navigates to another route and this prop disables this behavior */ persistent? : boolean /** * Expands fab actions list * @param evt JS event object */ show (evt? : LooseDictionary): void /** * Collapses fab actions list * @param evt JS event object */ hide (evt? : LooseDictionary): void /** * Triggers component to toggle between show/hide * @param evt JS event object */ toggle (evt? : LooseDictionary): void } export interface QFabAction extends ComponentPublicInstance { /** * Define the button HTML DOM type */ type? : 'a' | 'submit' | 'button' | 'reset' /** * Use 'outline' design for Fab button */ outline? : boolean /** * Use 'push' design for Fab button */ push? : boolean /** * Use 'flat' design for Fab button */ flat? : boolean /** * Remove shadow */ unelevated? : boolean /** * Apply custom padding (vertical [horizontal]); Size in CSS units, including unit name or standard size name (none|xs|sm|md|lg|xl); Also removes the min width and height when set */ padding? : string /** * Color name for component from the Quasar Color Palette */ color? : string /** * Overrides text color (if needed); Color name from the Quasar Color Palette */ textColor? : string /** * Apply the glossy effect over the button */ glossy? : boolean /** * Display label besides the FABs, as external content */ externalLabel? : boolean /** * The label that will be shown when Fab is extended */ label? : string | number /** * Position of the label around the icon */ labelPosition? : 'top' | 'right' | 'bottom' | 'left' /** * Hide the label; Useful for animation purposes where you toggle the visibility of the label */ hideLabel? : boolean /** * Class definitions to be attributed to the label container */ labelClass? : any[] | string | LooseDictionary /** * Style definitions to be attributed to the label container */ labelStyle? : any[] | string | LooseDictionary /** * Apply a rectangle aspect to the FAB */ square? : boolean /** * Put component in disabled mode */ disable? : boolean /** * Tabindex HTML attribute value */ tabindex? : number | string /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ icon? : string /** * How to align the Fab Action relative to Fab expand side; By default it uses the align specified in QFab */ anchor? : 'start' | 'center' | 'end' /** * Equivalent to Vue Router <router-link> 'to' property */ to? : string | LooseDictionary /** * Equivalent to Vue Router <router-link> 'replace' property */ replace? : boolean /** * Emulate click on QFabAction * @param evt JS event object */ click (evt? : LooseDictionary): void } export interface QField extends ComponentPublicInstance { /** * Model of the component; Either use this property (along with a listener for 'update:model-value' event) OR use v-model directive */ modelValue? : any /** * Does field have validation errors? */ error? : boolean /** * Validation error message (gets displayed only if 'error' is set to 'true') */ errorMessage? : string /** * Hide error icon when there is an error */ noErrorIcon? : boolean /** * Array of Functions/Strings; If String, then it must be a name of one of the embedded validation rules */ rules? : any[] /** * By default a change in the rules does not trigger a new validation until the model changes; If set to true then a change in the rules will trigger a validation; Has a performance penalty, so use it only when you really need it */ reactiveRules? : boolean /** * If set to boolean true then it checks validation status against the 'rules' only after field loses focus for first time; If set to 'ondemand' then it will trigger only when component's validate() method is manually called or when the wrapper QForm submits itself */ lazyRules? : boolean | 'ondemand' /** * A text label that will “float” up above the input field, once the field gets focus */ label? : string /** * Label will be always shown above the field regardless of field content (if any) */ stackLabel? : boolean /** * Helper (hint) text which gets placed below your wrapped form component */ hint? : string /** * Hide the helper (hint) text when field doesn't have focus */ hideHint? : boolean /** * Prefix */ prefix? : string /** * Suffix */ suffix? : string /** * Color name for the label from the Quasar Color Palette; Overrides the 'color' prop; The difference from 'color' prop is that the label will always have this color, even when field is not focused */ labelColor? : string /** * Color name for component from the Quasar Color Palette */ color? : string /** * Color name for component from the Quasar Color Palette */ bgColor? : string /** * Notify the component that the background is a dark color */ dark? : boolean /** * Signals the user a process is in progress by displaying a spinner; Spinner can be customized by using the 'loading' slot. */ loading? : boolean /** * Appends clearable icon when a value (not undefined or null) is set; When clicked, model becomes null */ clearable? : boolean /** * Custom icon to use for the clear button when using along with 'clearable' prop */ clearIcon? : string /** * Use 'filled' design for the field */ filled? : boolean /** * Use 'outlined' design for the field */ outlined? : boolean /** * Use 'borderless' design for the field */ borderless? : boolean /** * Use 'standout' design for the field; Specifies classes to be applied when focused (overriding default ones) */ standout? : boolean | string /** * Enables label slot; You need to set it to force use of the 'label' slot if the 'label' prop is not set */ labelSlot? : boolean /** * Enables bottom slots ('error', 'hint', 'counter') */ bottomSlots? : boolean /** * Do not reserve space for hint/error/counter anymore when these are not used; As a result, it also disables the animation for those; It also allows the hint/error area to stretch vertically based on its content */ hideBottomSpace? : boolean /** * Show an automatic counter on bottom right */ counter? : boolean /** * Applies a small standard border-radius for a squared shape of the component */ rounded? : boolean /** * Remove border-radius so borders are squared; Overrides 'rounded' prop */ square? : boolean /** * Dense mode; occupies less space */ dense? : boolean /** * Match inner content alignment to that of QItem */ itemAligned? : boolean /** * Put component in disabled mode */ disable? : boolean /** * Put component in readonly mode */ readonly? : boolean /** * Focus field on initial component render */ autofocus? : boolean /** * Used to specify the 'id' of the control and also the 'for' attribute of the label that wraps it; If no 'name' prop is specified, then it is used for this attribute as well */ for? : string /** * Used to specify the name of the control; Useful if dealing with forms; If not specified, it takes the value of 'for' prop, if it exists */ name? : string /** * Specify a max length of model */ maxlength? : string | number /** * Reset validation status */ resetValidation (): void /** * Trigger a validation * @param value Optional value to validate against * @returns True/false if no async rules, otherwise a Promise with the outcome (true -> validation was a success, false -> invalid models detected) */ validate (value? : any): boolean | Promise<boolean> /** * Focus field */ focus (): void /** * Blur field (lose focus) */ blur (): void } export interface QFile extends ComponentPublicInstance { /** * Used to specify the name of the control; Useful if dealing with forms; If not specified, it takes the value of 'for' prop, if it exists */ name? : string /** * Allow multiple file uploads */ multiple? : boolean /** * Comma separated list of unique file type specifiers. Maps to 'accept' attribute of native input type=file element */ accept? : string /** * Optionally, specify that a new file should be captured, and which device should be used to capture that new media of a type defined by the 'accept' prop. Maps to 'capture' attribute of native input type=file element */ capture? : 'user' | 'environment' /** * Maximum size of individual file in bytes */ maxFileSize? : number | string /** * Maximum size of all files combined in bytes */ maxTotalSize? : number | string /** * Maximum number of files to contain */ maxFiles? : number | string /** * Custom filter for added files; Only files that pass this filter will be added to the queue and uploaded; For best performance, reference it from your scope and do not define it inline */ filter? : Function /** * Model of the component; Must be FileList or Array if using 'multiple' prop; Either use this property (along with a listener for 'update:modelValue' event) OR use v-model directive */ modelValue : File | FileList | any[] /** * Does field have validation errors? */ error? : boolean /** * Validation error message (gets displayed only if 'error' is set to 'true') */ errorMessage? : string /** * Hide error icon when there is an error */ noErrorIcon? : boolean /** * Array of Functions/Strings; If String, then it must be a name of one of the embedded validation rules */ rules? : any[] /** * By default a change in the rules does not trigger a new validation until the model changes; If set to true then a change in the rules will trigger a validation; Has a performance penalty, so use it only when you really need it */ reactiveRules? : boolean /** * If set to boolean true then it checks validation status against the 'rules' only after field loses focus for first time; If set to 'ondemand' then it will trigger only when component's validate() method is manually called or when the wrapper QForm submits itself */ lazyRules? : boolean | 'ondemand' /** * A text label that will “float” up above the input field, once the field gets focus */ label? : string /** * Label will be always shown above the field regardless of field content (if any) */ stackLabel? : boolean /** * Helper (hint) text which gets placed below your wrapped form component */ hint? : string /** * Hide the helper (hint) text when field doesn't have focus */ hideHint? : boolean /** * Prefix */ prefix? : string /** * Suffix */ suffix? : string /** * Color name for the label from the Quasar Color Palette; Overrides the 'color' prop; The difference from 'color' prop is that the label will always have this color, even when field is not focused */ labelColor? : string /** * Color name for component from the Quasar Color Palette */ color? : string /** * Color name for component from the Quasar Color Palette */ bgColor? : string /** * Notify the component that the background is a dark color */ dark? : boolean /** * Signals the user a process is in progress by displaying a spinner; Spinner can be customized by using the 'loading' slot. */ loading? : boolean /** * Appends clearable icon when a value (not undefined or null) is set; When clicked, model becomes null */ clearable? : boolean /** * Custom icon to use for the clear button when using along with 'clearable' prop */ clearIcon? : string /** * Use 'filled' design for the field */ filled? : boolean /** * Use 'outlined' design for the field */ outlined? : boolean /** * Use 'borderless' design for the field */ borderless? : boolean /** * Use 'standout' design for the field; Specifies classes to be applied when focused (overriding default ones) */ standout? : boolean | string /** * Enables label slot; You need to set it to force use of the 'label' slot if the 'label' prop is not set */ labelSlot? : boolean /** * Enables bottom slots ('error', 'hint', 'counter') */ bottomSlots? : boolean /** * Do not reserve space for hint/error/counter anymore when these are not used; As a result, it also disables the animation for those; It also allows the hint/error area to stretch vertically based on its content */ hideBottomSpace? : boolean /** * Show an automatic counter on bottom right */ counter? : boolean /** * Applies a small standard border-radius for a squared shape of the component */ rounded? : boolean /** * Remove border-radius so borders are squared; Overrides 'rounded' prop */ square? : boolean /** * Dense mode; occupies less space */ dense? : boolean /** * Match inner content alignment to that of QItem */ itemAligned? : boolean /** * Put component in disabled mode */ disable? : boolean /** * Put component in readonly mode */ readonly? : boolean /** * Focus field on initial component render */ autofocus? : boolean /** * Used to specify the 'id' of the control and also the 'for' attribute of the label that wraps it; If no 'name' prop is specified, then it is used for this attribute as well */ for? : string /** * Append file(s) to current model rather than replacing them; Has effect only when using 'multiple' mode */ append? : boolean /** * Override default selection string, if not using 'file' or 'selected' scoped slots and if not using 'use-chips' prop */ displayValue? : number | string /** * Use QChip to show picked files */ useChips? : boolean /** * Label for the counter; The 'counter' prop is necessary to enable this one */ counterLabel? : Function /** * Tabindex HTML attribute value */ tabindex? : number | string /** * Class definitions to be attributed to the underlying selection container */ inputClass? : any[] | string | LooseDictionary /** * Style definitions to be attributed to the underlying selection container */ inputStyle? : any[] | string | LooseDictionary /** * Trigger file pick; Must be called as a direct consequence of user interaction (eg. in a click handler), due to browsers security policy * @param evt JS event object */ pickFiles (evt? : LooseDictionary): void /** * Add files programmatically * @param files Array of files (instances of File) */ addFiles (files : FileList | any[]): void /** * Reset validation status */ resetValidation (): void /** * Trigger a validation * @param value Optional value to validate against * @returns True/false if no async rules, otherwise a Promise with the outcome (true -> validation was a success, false -> invalid models detected) */ validate (value? : any): boolean | Promise<boolean> /** * Focus component */ focus (): void /** * Blur component (lose focus) */ blur (): void /** * Remove file located at specific index in the model * @param index Index at which to remove selection */ removeAtIndex (index : number): void /** * Remove specified file from the model * @param file File to remove (instance of File) */ removeFile (file : File): void } export interface QFooter extends ComponentPublicInstance { /** * Model of the component defining if it is shown or hidden to the user; Either use this property (along with a listener for 'update:modelValue' event) OR use v-model directive */ modelValue? : boolean /** * Enable 'reveal' mode; Takes into account user scroll to temporarily show/hide footer */ reveal? : boolean /** * Applies a default border to the component */ bordered? : boolean /** * Adds a default shadow to the footer */ elevated? : boolean /** * When using SSR, you can optionally hint of the height (in pixels) of the QFooter */ heightHint? : number | string } export interface QForm extends ComponentPublicInstance { /** * Focus first focusable element on initial component render */ autofocus? : boolean /** * Do not try to focus on first component that has a validation error when submitting form */ noErrorFocus? : boolean /** * Do not try to focus on first component when resetting form */ noResetFocus? : boolean /** * Validate all fields in form (by default it stops after finding the first invalid field with synchronous validation) */ greedy? : boolean /** * Focus on first focusable element/component in the form */ focus (): void /** * Triggers a validation on all applicable inner Quasar components * @param shouldFocus Tell if it should focus or not on component with error on submitting form; Overrides 'no-focus-error' prop if specified * @returns Promise is always fulfilled and receives the outcome (true -> validation was a success, false -> invalid models detected) */ validate (shouldFocus? : boolean): Promise<boolean> /** * Resets the validation on all applicable inner Quasar components */ resetValidation (): void /** * Manually trigger form validation and submit * @param evt JS event object */ submit (evt? : LooseDictionary): void /** * Manually trigger form reset * @param evt JS event object */ reset (evt? : LooseDictionary): void /** * Get array of children vue components that support validation * @returns Vue components that support Quasar validation API */ getValidationComponents (): any[] } export interface QFormChildMixin extends ComponentPublicInstance { /** * Needs to be overwritten when getting extended/mixed in * @returns Promise is always fulfilled and receives the outcome (true -> validation was a success, false -> invalid models detected) */ validate (): boolean | Promise<boolean> /** * Needs to be overwritten when getting extended/mixed in */ resetValidation (): void } export interface QHeader extends ComponentPublicInstance { /** * Model of the component defining if it is shown or hidden to the user; Either use this property (along with a listener for 'update:modelValue' event) OR use v-model directive */ modelValue? : boolean /** * Enable 'reveal' mode; Takes into account user scroll to temporarily show/hide header */ reveal? : boolean /** * Amount of scroll (in pixels) that should trigger a 'reveal' state change */ revealOffset? : number /** * Applies a default border to the component */ bordered? : boolean /** * Adds a default shadow to the header */ elevated? : boolean /** * When using SSR, you can optionally hint of the height (in pixels) of the QHeader */ heightHint? : number | string } export interface QIcon extends ComponentPublicInstance { /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * HTML tag to render, unless no icon is supplied or it's an svg icon */ tag? : string /** * Name of the icon, following Quasar convention */ name? : string /** * Color name for component from the Quasar Color Palette */ color? : string /** * Useful if icon is on the left side of something: applies a standard margin on the right side of Icon */ left? : boolean /** * Useful if icon is on the right side of something: applies a standard margin on the left side of Icon */ right? : boolean } export interface QImg extends ComponentPublicInstance { /** * Force the component to maintain an aspect ratio */ ratio? : string | number | string | number /** * Path to image */ src? : string /** * Same syntax as <img> srcset attribute */ srcset? : string /** * Same syntax as <img> sizes attribute */ sizes? : string /** * While waiting for your image to load, you can use a placeholder image */ placeholderSrc? : string /** * Forces image width; Must also include the unit (px or %) */ width? : string /** * Forces image height; Must also include the unit (px or %) */ height? : string /** * Lazy or immediate load; Same syntax as <img> loading attribute */ loading? : 'lazy' | 'eager' /** * Same syntax as <img> crossorigin attribute */ crossorigin? : 'anonymous' | 'use-credentials' /** * How the image will fit into the container; Equivalent of the object-fit prop; Can be coordinated with 'position' prop */ fit? : 'cover' | 'fill' | 'contain' | 'none' | 'scale-down' /** * The alignment of the image into the container; Equivalent of the object-position CSS prop */ position? : string /** * Specifies an alternate text for the image, if the image cannot be displayed */ alt? : string /** * Class definitions to be attributed to the container of image; Does not apply to the caption */ imgClass? : any[] | string | LooseDictionary /** * Apply CSS to the container of the image; Does not apply to the caption */ imgStyle? : LooseDictionary /** * Color name for default Spinner (unless using a 'loading' slot) */ spinnerColor? : string /** * Size in CSS units, including unit name, for default Spinner (unless using a 'loading' slot) */ spinnerSize? : string /** * Do not display the default spinner while waiting for the image to be loaded; It is overriden by the 'loading' slot when one is present */ noSpinner? : boolean /** * Disables the native context menu for the image */ noNativeMenu? : boolean /** * Disable default transition when switching between old and new image */ noTransition? : boolean } export interface QInfiniteScroll extends ComponentPublicInstance { /** * Offset (pixels) to bottom of Infinite Scroll container from which the component should start loading more content in advance */ offset? : number /** * Debounce amount (in milliseconds) */ debounce? : string | number /** * Initialize the pagination index (used for the @load event) */ initialIndex? : number /** * CSS selector or DOM element to be used as a custom scroll container instead of the auto detected one */ scrollTarget? : Element | string /** * Put component in disabled mode */ disable? : boolean /** * Scroll area should behave like a messenger - starting scrolled to bottom and loading when reaching the top */ reverse? : boolean /** * Checks scroll position and loads more content if necessary */ poll (): void /** * Tells Infinite Scroll to load more content, regardless of the scroll position */ trigger (): void /** * Resets calling index to 0 */ reset (): void /** * Stops working, regardless of scroll position */ stop (): void /** * Starts working. Checks scroll position upon call and if trigger is hit, it loads more content */ resume (): void /** * Overwrite the current pagination index */ setIndex (): void /** * Updates the scroll target; Useful when the parent elements change so that the scrolling target also changes */ updateScrollTarget (): void } export interface QInnerLoading extends ComponentPublicInstance { /** * One of Quasar's embedded transitions */ transitionShow? : string /** * One of Quasar's embedded transitions */ transitionHide? : string /** * Transition duration (in milliseconds, without unit) */ transitionDuration? : string | number /** * Size in CSS units, including unit name, or standard size name (xs|sm|md|lg|xl), for the inner Spinner (unless using the default slot) */ size? : string /** * State - loading or not */ showing? : boolean /** * Color name for component from the Quasar Color Palette for the inner Spinner (unless using the default slot) */ color? : string /** * Notify the component that the background is a dark color */ dark? : boolean } export interface QInput extends ComponentPublicInstance { /** * Used to specify the name of the control; Useful if dealing with forms; If not specified, it takes the value of 'for' prop, if it exists */ name? : string /** * Custom mask or one of the predefined mask names */ mask? : string /** * Fills string with specified characters (or underscore if value is not string) to fill mask's length */ fillMask? : boolean | string /** * Fills string from the right side of the mask */ reverseFillMask? : boolean /** * Model will be unmasked (won't contain tokens/separation characters) */ unmaskedValue? : boolean /** * Model of the component; Either use this property (along with a listener for 'update:modelValue' event) OR use v-model directive */ modelValue : string | number /** * Does field have validation errors? */ error? : boolean /** * Validation error message (gets displayed only if 'error' is set to 'true') */ errorMessage? : string /** * Hide error icon when there is an error */ noErrorIcon? : boolean /** * Array of Functions/Strings; If String, then it must be a name of one of the embedded validation rules */ rules? : any[] /** * By default a change in the rules does not trigger a new validation until the model changes; If set to true then a change in the rules will trigger a validation; Has a performance penalty, so use it only when you really need it */ reactiveRules? : boolean /** * If set to boolean true then it checks validation status against the 'rules' only after field loses focus for first time; If set to 'ondemand' then it will trigger only when component's validate() method is manually called or when the wrapper QForm submits itself */ lazyRules? : boolean | 'ondemand' /** * A text label that will “float” up above the input field, once the field gets focus */ label? : string /** * Label will be always shown above the field regardless of field content (if any) */ stackLabel? : boolean /** * Helper (hint) text which gets placed below your wrapped form component */ hint? : string /** * Hide the helper (hint) text when field doesn't have focus */ hideHint? : boolean /** * Prefix */ prefix? : string /** * Suffix */ suffix? : string /** * Color name for the label from the Quasar Color Palette; Overrides the 'color' prop; The difference from 'color' prop is that the label will always have this color, even when field is not focused */ labelColor? : string /** * Color name for component from the Quasar Color Palette */ color? : string /** * Color name for component from the Quasar Color Palette */ bgColor? : string /** * Notify the component that the background is a dark color */ dark? : boolean /** * Signals the user a process is in progress by displaying a spinner; Spinner can be customized by using the 'loading' slot. */ loading? : boolean /** * Appends clearable icon when a value (not undefined or null) is set; When clicked, model becomes null */ clearable? : boolean /** * Custom icon to use for the clear button when using along with 'clearable' prop */ clearIcon? : string /** * Use 'filled' design for the field */ filled? : boolean /** * Use 'outlined' design for the field */ outlined? : boolean /** * Use 'borderless' design for the field */ borderless? : boolean /** * Use 'standout' design for the field; Specifies classes to be applied when focused (overriding default ones) */ standout? : boolean | string /** * Enables label slot; You need to set it to force use of the 'label' slot if the 'label' prop is not set */ labelSlot? : boolean /** * Enables bottom slots ('error', 'hint', 'counter') */ bottomSlots? : boolean /** * Do not reserve space for hint/error/counter anymore when these are not used; As a result, it also disables the animation for those; It also allows the hint/error area to stretch vertically based on its content */ hideBottomSpace? : boolean /** * Show an automatic counter on bottom right */ counter? : boolean /** * Applies a small standard border-radius for a squared shape of the component */ rounded? : boolean /** * Remove border-radius so borders are squared; Overrides 'rounded' prop */ square? : boolean /** * Dense mode; occupies less space */ dense? : boolean /** * Match inner content alignment to that of QItem */ itemAligned? : boolean /** * Put component in disabled mode */ disable? : boolean /** * Put component in readonly mode */ readonly? : boolean /** * Focus field on initial component render */ autofocus? : boolean /** * Used to specify the 'id' of the control and also the 'for' attribute of the label that wraps it; If no 'name' prop is specified, then it is used for this attribute as well */ for? : string /** * Text to be displayed as shadow at the end of the text in the control; Does NOT applies to type=file */ shadowText? : string /** * Input type */ type? : 'text' | 'password' | 'textarea' | 'email' | 'search' | 'tel' | 'file' | 'number' | 'url' | 'time' | 'date' /** * Debounce amount (in milliseconds) when updating model */ debounce? : string | number /** * Specify a max length of model */ maxlength? : string | number /** * Make field autogrow along with its content (uses a textarea) */ autogrow? : boolean /** * Class definitions to be attributed to the underlying input tag */ inputClass? : any[] | string | LooseDictionary /** * Style definitions to be attributed to the underlying input tag */ inputStyle? : any[] | string | LooseDictionary /** * Reset validation status */ resetValidation (): void /** * Trigger a validation * @param value Optional value to validate against * @returns True/false if no async rules, otherwise a Promise with the outcome (true -> validation was a success, false -> invalid models detected) */ validate (value? : any): boolean | Promise<boolean> /** * Focus underlying input tag */ focus (): void /** * Lose focus on underlying input tag */ blur (): void /** * Select input text */ select (): void /** * Get the native input/textarea DOM Element * @returns The underlying native input/textarea DOM Element */ getNativeElement (): LooseDictionary } export interface QIntersection extends ComponentPublicInstance { /** * HTML tag to use */ tag? : string /** * Get triggered only once */ once? : boolean /** * Pre-render content on server side if using SSR (use it to pre-render above the fold content) */ ssrPrerender? : boolean /** * [Intersection API root prop] Lets you define an alternative to the viewport as your root (through its DOM element); It is important to keep in mind that root needs to be an ancestor of the observed element */ root? : Element /** * [Intersection API rootMargin prop] Allows you to specify the margins for the root, effectively allowing you to either grow or shrink the area used for intersections */ margin? : string /** * [Intersection API threshold prop] Threshold(s) at which to trigger, specified as a ratio, or list of ratios, of (visible area / total area) of the observed element */ threshold? : any[] | number /** * One of Quasar's embedded transitions */ transition? : string /** * Disable visibility observable (content will remain as it was, visible or hidden) */ disable? : boolean } export interface QItem extends ComponentPublicInstance { /** * Equivalent to Vue Router <router-link> 'to' property */ to? : string | LooseDictionary /** * Equivalent to Vue Router <router-link> 'exact' property */ exact? : boolean /** * Equivalent to Vue Router <router-link> 'replace' property */ replace? : boolean /** * Equivalent to Vue Router <router-link> 'active-class' property */ activeClass? : string /** * Equivalent to Vue Router <router-link> 'active-class' property */ exactActiveClass? : string /** * Put component in disabled mode */ disable? : boolean /** * Put item into 'active' state */ active? : boolean /** * Notify the component that the background is a dark color */ dark? : boolean /** * Is QItem clickable? If it's the case, then it will add hover effects and emit 'click' events */ clickable? : boolean /** * Dense mode; occupies less space */ dense? : boolean /** * Apply an inset; Useful when avatar/left side is missing but you want to align content with other items that do have a left side, or when you're building a menu */ insetLevel? : number /** * Tabindex HTML attribute value */ tabindex? : number | string /** * HTML tag to render; Suggestion: use 'label' when encapsulating a QCheckbox/QRadio/QToggle so that when user clicks/taps on the whole item it will trigger a model change for the mentioned components */ tag? : string /** * Put item into a manual focus state; Enables 'focused' prop which will determine if item is focused or not, rather than relying on native hover/focus states */ manualFocus? : boolean /** * Determines focus state, ONLY if 'manual-focus' is enabled / set to true */ focused? : boolean } export interface QItemLabel extends ComponentPublicInstance { /** * Renders an overline label */ overline? : boolean /** * Renders a caption label */ caption? : boolean /** * Renders a header label */ header? : boolean /** * Apply ellipsis when there's not enough space to render on the specified number of lines; */ lines? : number | string } export interface QItemSection extends ComponentPublicInstance { /** * Render an avatar item side (does not needs 'side' prop to be set) */ avatar? : boolean /** * Render a thumbnail item side (does not needs 'side' prop to be set) */ thumbnail? : boolean /** * Renders as a side of the item */ side? : boolean /** * Align content to top (useful for multi-line items) */ top? : boolean /** * Do not wrap text (useful for item's main content) */ noWrap? : boolean } export interface QList extends ComponentPublicInstance { /** * Applies a default border to the component */ bordered? : boolean /** * Dense mode; occupies less space */ dense? : boolean /** * Applies a separator between contained items */ separator? : boolean /** * Notify the component that the background is a dark color */ dark? : boolean /** * Applies a material design-like padding on top and bottom */ padding? : boolean } export interface QKnob extends ComponentPublicInstance { /** * Used to specify the name of the control; Useful if dealing with forms submitted directly to a URL */ name? : string /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * Any number to indicate the given value of the knob. Either use this property (along with a listener for 'update:modelValue' event) OR use the v-model directive */ modelValue : number /** * The minimum value that the model (the knob value) should start at */ min? : number /** * The maximum value that the model (the knob value) should go to */ max? : number /** * A number representing steps in the value of the model, while adjusting the knob */ step? : number /** * No animation when model changes */ instantFeedback? : boolean /** * Color name for component from the Quasar Color Palette */ color? : string /** * Color name for the center part of the component from the Quasar Color Palette */ centerColor? : string /** * Color name for the track of the component from the Quasar Color Palette */ trackColor? : string /** * Size of text in CSS units, including unit name. Suggestion: use 'em' units to sync with component size */ fontSize? : string /** * Thickness of progress arc as a ratio (0.0 < x < 1.0) of component size */ thickness? : number /** * Angle to rotate progress arc by */ angle? : number /** * Enables the default slot and uses it (if available), otherwise it displays the 'value' prop as text; Make sure the text has enough space to be displayed inside the component */ showValue? : boolean /** * Tabindex HTML attribute value */ tabindex? : number | string /** * Put component in disabled mode */ disable? : boolean /** * Put component in readonly mode */ readonly? : boolean } export interface QLayout extends ComponentPublicInstance { /** * Defines how your layout components (header/footer/drawer) should be placed on screen; See docs examples */ view? : string /** * Containerize the layout which means it changes the default behavior of expanding to the whole window; Useful (but not limited to) for when using on a QDialog */ container? : boolean } export interface QLinearProgress extends ComponentPublicInstance { /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * Progress value (0.0 < x < 1.0) */ value? : number /** * Optional buffer value (0.0 < x < 1.0) */ buffer? : number /** * Color name for component from the Quasar Color Palette */ color? : string /** * Color name for component's track from the Quasar Color Palette */ trackColor? : string /** * Notify the component that the background is a dark color */ dark? : boolean /** * Reverse direction of progress */ reverse? : boolean /** * Draw stripes; For determinate state only (for performance reasons) */ stripe? : boolean /** * Put component into indeterminate mode */ indeterminate? : boolean /** * Put component into query mode */ query? : boolean /** * Applies a small standard border-radius for a squared shape of the component */ rounded? : boolean /** * No transition when model changes */ instantFeedback? : boolean } export interface QMarkupTable extends ComponentPublicInstance { /** * Dense mode; occupies less space */ dense? : boolean /** * Notify the component that the background is a dark color */ dark? : boolean /** * Applies a 'flat' design (no default shadow) */ flat? : boolean /** * Applies a default border to the component */ bordered? : boolean /** * Removes border-radius so borders are squared */ square? : boolean /** * Use a separator/border between rows, columns or all cells */ separator? : 'horizontal' | 'vertical' | 'cell' | 'none' /** * Wrap text within table cells */ wrapCells? : boolean } export interface QMenu extends ComponentPublicInstance { /** * One of Quasar's embedded transitions */ transitionShow? : string /** * One of Quasar's embedded transitions */ transitionHide? : string /** * Transition duration (in milliseconds, without unit) */ transitionDuration? : string | number /** * Configure a target element to trigger component toggle; 'true' means it enables the parent DOM element, 'false' means it disables attaching events to any DOM elements; By using a String (CSS selector) or a DOM element it attaches the events to the specified DOM element (if it exists) */ target? : boolean | string | Element /** * Skips attaching events to the target DOM element (that trigger the element to get shown) */ noParentEvent? : boolean /** * Allows the component to behave like a context menu, which opens with a right mouse click (or long tap on mobile) */ contextMenu? : boolean /** * Model of the component defining shown/hidden state; Either use this property (along with a listener for 'update:model-value' event) OR use v-model directive */ modelValue? : boolean /** * Notify the component that the background is a dark color */ dark? : boolean /** * Allows the menu to match at least the full width of its target */ fit? : boolean /** * Allows the menu to cover its target. When used, the 'self' and 'fit' props are no longer effective */ cover? : boolean /** * Two values setting the starting position or anchor point of the menu relative to its target */ anchor? : 'top left' | 'top middle' | 'top right' | 'top start' | 'top end' | 'center left' | 'center middle' | 'center right' | 'center start' | 'center end' | 'bottom left' | 'bottom middle' | 'bottom right' | 'bottom start' | 'bottom end' /** * Two values setting the menu's own position relative to its target */ self? : 'top left' | 'top middle' | 'top right' | 'top start' | 'top end' | 'center left' | 'center middle' | 'center right' | 'center start' | 'center end' | 'bottom left' | 'bottom middle' | 'bottom right' | 'bottom start' | 'bottom end' /** * An array of two numbers to offset the menu horizontally and vertically in pixels */ offset? : any[] /** * CSS selector or DOM element to be used as a custom scroll container instead of the auto detected one */ scrollTarget? : Element | string /** * Allows for the target position to be set by the mouse position, when the target of the menu is either clicked or touched */ touchPosition? : boolean /** * Allows the menu to not be dismissed by a click/tap outside of the menu or by hitting the ESC key */ persistent? : boolean /** * Changing route app won't dismiss the popup; No need to set it if 'persistent' prop is also set */ noRouteDismiss? : boolean /** * Allows any click/tap in the menu to close it; Useful instead of attaching events to each menu item that should close the menu on click/tap */ autoClose? : boolean /** * Separate from parent menu, marking it as a separate closing point for v-close-popup (without this, chained menus close all together) */ separateClosePopup? : boolean /** * Forces content to have squared borders */ square? : boolean /** * (Accessibility) When Menu gets hidden, do not refocus on the DOM element that previously had focus */ noRefocus? : boolean /** * (Accessibility) When Menu gets shown, do not switch focus on it */ noFocus? : boolean /** * The maximum height of the menu; Size in CSS units, including unit name */ maxHeight? : string /** * The maximum width of the menu; Size in CSS units, including unit name */ maxWidth? : string /** * Triggers component to show * @param evt JS event object */ show (evt? : LooseDictionary): void /** * Triggers component to hide * @param evt JS event object */ hide (evt? : LooseDictionary): void /** * Triggers component to toggle between show/hide * @param evt JS event object */ toggle (evt? : LooseDictionary): void /** * There are some custom scenarios for which Quasar cannot automatically reposition the menu without significant performance drawbacks so the optimal solution is for you to call this method when you need it */ updatePosition (): void /** * Focus menu; if you have content with autofocus attribute, it will directly focus it */ focus (): void } export interface QNoSsr extends ComponentPublicInstance { /** * HTML tag to use */ tag? : string /** * Text to display on server-side render (unless using 'placeholder' slot) */ placeholder? : string } export interface QOptionGroup extends ComponentPublicInstance { /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * Model of the component; Either use this property (along with a listener for 'update:model-value' event) OR use v-model directive */ modelValue : any /** * Array of objects with value and label props. The binary components will be created according to this array; Props from QToggle, QCheckbox or QRadio can also be added as key/value pairs to control the components singularly */ options? : any[] /** * Used to specify the name of the controls; Useful if dealing with forms submitted directly to a URL */ name? : string /** * The type of input component to be used */ type? : 'radio' | 'checkbox' | 'toggle' /** * Color name for component from the Quasar Color Palette */ color? : string /** * Should the color (if specified any) be kept when input components are unticked? */ keepColor? : boolean /** * Notify the component that the background is a dark color */ dark? : boolean /** * Dense mode; occupies less space */ dense? : boolean /** * Label (if any specified) should be displayed on the left side of the input components */ leftLabel? : boolean /** * Show input components as inline-block rather than each having their own row */ inline? : boolean /** * Put component in disabled mode */ disable? : boolean } export interface QPageScroller extends ComponentPublicInstance { /** * Page side/corner to stick to */ position? : 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left' | 'top' | 'right' | 'bottom' | 'left' /** * An array of two numbers to offset the component horizontally and vertically in pixels */ offset? : any[] /** * By default the component shrinks to content's size; By using this prop you make the component fully expand horizontally or vertically, based on 'position' prop */ expand? : boolean /** * Scroll offset (in pixels) from which point the component is shown on page; Measured from the top of the page (or from the bottom if in 'reverse' mode) */ scrollOffset? : number /** * Work in reverse (shows when scrolling to the top of the page and scrolls to bottom when triggered) */ reverse? : boolean /** * Duration (in milliseconds) of the scrolling until it reaches its target */ duration? : number } export interface QPageSticky extends ComponentPublicInstance { /** * Page side/corner to stick to */ position? : 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left' | 'top' | 'right' | 'bottom' | 'left' /** * An array of two numbers to offset the component horizontally and vertically in pixels */ offset? : any[] /** * By default the component shrinks to content's size; By using this prop you make the component fully expand horizontally or vertically, based on 'position' prop */ expand? : boolean } export interface QPage extends ComponentPublicInstance { /** * Applies a default responsive page padding */ padding? : boolean /** * Override default CSS style applied to the component (sets minHeight); Function(offset: Number) => CSS props/value: Object; For best performance, reference it from your scope and do not define it inline */ styleFn? : Function } export interface QPageContainer extends ComponentPublicInstance { } export interface QPagination extends ComponentPublicInstance { /** * Current page (must be between min/max) */ modelValue : number /** * Minimum page (must be lower than 'max') */ min? : number /** * Number of last page (must be higher than 'min') */ max : number /** * Color name for component from the Quasar Color Palette */ color? : string /** * Overrides text color (if needed); Color name from the Quasar Color Palette */ textColor? : string /** * Color name for component from the Quasar Color Palette */ activeColor? : string /** * Overrides text color (if needed); Color name from the Quasar Color Palette */ activeTextColor? : string /** * Notify the component that the background is a dark color (useful when you are using it along with the 'input' prop) */ dark? : boolean /** * Style definitions to be attributed to the input (if using one) */ inputStyle? : any[] | string | LooseDictionary /** * Class definitions to be attributed to the input (if using one) */ inputClass? : any[] | string | LooseDictionary /** * Button size in CSS units, including unit name */ size? : string /** * Put component in disabled mode */ disable? : boolean /** * Use an input instead of buttons */ input? : boolean /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ iconPrev? : string /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ iconNext? : string /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ iconFirst? : string /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ iconLast? : string /** * Generate link for page buttons; For best performance, reference it from your scope and do not define it inline */ toFn? : Function /** * Show boundary button links */ boundaryLinks? : boolean /** * Always show first and last page buttons (if not using 'input') */ boundaryNumbers? : boolean /** * Show direction buttons */ directionLinks? : boolean /** * Show ellipses (...) when pages are available */ ellipses? : boolean /** * Maximum number of page links to display at a time; 0 means Infinite */ maxPages? : number /** * Configure buttons material ripple (disable it by setting it to 'false' or supply a config object); Does not applies to boundary and ellipsis buttons */ ripple? : boolean | LooseDictionary /** * Makes a circle shaped button for all buttons */ round? : boolean /** * Applies a more prominent border-radius for a squared shape button for all buttons */ rounded? : boolean /** * Use 'flat' design for current page button */ flat? : boolean /** * Use 'outline' design for current page button */ outline? : boolean /** * Remove shadow for current page button */ unelevated? : boolean /** * Use 'push' design for current page button */ push? : boolean /** * Applies a glossy effect for all buttons */ glossy? : boolean /** * Dense mode; occupies less space */ dense? : boolean /** * Apply custom padding (vertical [horizontal]); Size in CSS units, including unit name or standard size name (none|xs|sm|md|lg|xl); Also removes the min width and height when set */ padding? : string /** * Go directly to the specified page * @param pageNumber Page number to go to */ set (pageNumber? : number): void /** * Increment/Decrement current page by offset * @param offset Offset page, can be negative or positive */ setByOffset (offset? : number): void } export interface QParallax extends ComponentPublicInstance { /** * Path to image (unless a 'media' slot is used) */ src? : string /** * Height of component (in pixels) */ height? : number /** * Speed of parallax effect (0.0 < x < 1.0) */ speed? : number /** * CSS selector or DOM element to be used as a custom scroll container instead of the auto detected one */ scrollTarget? : Element | string } export interface QPopupEdit extends ComponentPublicInstance { /** * Model of the component; Either use this property (along with a listener for 'update:model-value' event) OR use v-model directive */ modelValue : any /** * Optional title (unless 'title' slot is used) */ title? : string /** * Show Set and Cancel buttons */ buttons? : boolean /** * Override Set button label */ labelSet? : string /** * Override Cancel button label */ labelCancel? : string /** * Automatically save the model (if changed) when user clicks/taps outside of the popup; It does not apply to ESC key */ autoSave? : boolean /** * Color name for component from the Quasar Color Palette */ color? : string /** * Validates model then triggers 'save' and closes Popup; Returns a Boolean ('true' means valid, 'false' means abort); Syntax: validate(value); For best performance, reference it from your scope and do not define it inline */ validate? : Function /** * Put component in disabled mode */ disable? : boolean /** * Allows the menu to match at least the full width of its target */ fit? : boolean /** * Allows the menu to cover its target. When used, the 'self' and 'fit' props are no longer effective */ cover? : boolean /** * Two values setting the starting position or anchor point of the menu relative to its target */ anchor? : 'top left' | 'top middle' | 'top right' | 'top start' | 'top end' | 'center left' | 'center middle' | 'center right' | 'center start' | 'center end' | 'bottom left' | 'bottom middle' | 'bottom right' | 'bottom start' | 'bottom end' /** * Two values setting the menu's own position relative to its target */ self? : 'top left' | 'top middle' | 'top right' | 'top start' | 'top end' | 'center left' | 'center middle' | 'center right' | 'center start' | 'center end' | 'bottom left' | 'bottom middle' | 'bottom right' | 'bottom start' | 'bottom end' /** * An array of two numbers to offset the menu horizontally and vertically in pixels */ offset? : any[] /** * Allows for the target position to be set by the mouse position, when the target of the menu is either clicked or touched */ touchPosition? : boolean /** * Avoid menu closing by hitting ESC key or by clicking/tapping outside of the Popup */ persistent? : boolean /** * Separate from parent menu, marking it as a separate closing point for v-close-popup (without this, chained menus close all together) */ separateClosePopup? : boolean /** * Forces menu to have squared borders */ square? : boolean /** * The maximum height of the menu; Size in CSS units, including unit name */ maxHeight? : string /** * The maximum width of the menu; Size in CSS units, including unit name */ maxWidth? : string /** * Trigger a model update; Validates model (and emits 'save' event if it's the case) then closes Popup */ set (): void /** * Triggers a model reset to its initial value ('cancel' event is emitted) then closes Popup */ cancel (): void /** * Triggers component to show * @param evt JS event object */ show (evt? : LooseDictionary): void /** * Triggers component to hide * @param evt JS event object */ hide (evt? : LooseDictionary): void /** * There are some custom scenarios for which Quasar cannot automatically reposition the component without significant performance drawbacks so the optimal solution is for you to call this method when you need it */ updatePosition (): void } export interface QPopupProxy extends ComponentPublicInstance { /** * Configure a target element to trigger component toggle; 'true' means it enables the parent DOM element, 'false' means it disables attaching events to any DOM elements; By using a String (CSS selector) or a DOM element it attaches the events to the specified DOM element (if it exists) */ target? : boolean | string | Element /** * Skips attaching events to the target DOM element (that trigger the element to get shown) */ noParentEvent? : boolean /** * Allows the component to behave like a context menu, which opens with a right mouse click (or long tap on mobile) */ contextMenu? : boolean /** * Defines the state of the component (shown/hidden); Either use this property (along with a listener for 'update:modelValue' event) OR use v-model directive */ modelValue? : boolean /** * Breakpoint (in pixels) of window width/height (whichever is smaller) from where a Menu will get to be used instead of a Dialog */ breakpoint? : number | string /** * Triggers component to show * @param evt JS event object */ show (evt? : LooseDictionary): void /** * Triggers component to hide * @param evt JS event object */ hide (evt? : LooseDictionary): void /** * Triggers component to toggle between show/hide * @param evt JS event object */ toggle (evt? : LooseDictionary): void } export interface QPullToRefresh extends ComponentPublicInstance { /** * Color name for the icon from the Quasar Color Palette */ color? : string /** * Color name for background of the icon container from the Quasar Color Palette */ bgColor? : string /** * Icon to display when refreshing the content */ icon? : string /** * Don't listen for mouse events */ noMouse? : boolean /** * Put component in disabled mode */ disable? : boolean /** * CSS selector or DOM element to be used as a custom scroll container instead of the auto detected one */ scrollTarget? : Element | string /** * Triggers a refresh */ trigger (): void /** * Updates the scroll target; Useful when the parent elements change so that the scrolling target also changes */ updateScrollTarget (): void } export interface QRadio extends ComponentPublicInstance { /** * Used to specify the name of the control; Useful if dealing with forms submitted directly to a URL */ name? : string /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * Model of the component; Either use this property (along with a listener for 'update:model-value' event) OR use v-model directive */ modelValue : number | string /** * The actual value of the option with which model value is changed */ val : number | string /** * Label to display along the radio control (or use the default slot instead of this prop) */ label? : string /** * Label (if any specified) should be displayed on the left side of the checkbox */ leftLabel? : boolean /** * Color name for component from the Quasar Color Palette */ color? : string /** * Should the color (if specified any) be kept when checkbox is unticked? */ keepColor? : boolean /** * Notify the component that the background is a dark color */ dark? : boolean /** * Dense mode; occupies less space */ dense? : boolean /** * Put component in disabled mode */ disable? : boolean /** * Tabindex HTML attribute value */ tabindex? : number | string /** * Sets the Radio's v-model to equal the val */ set (): void } export interface QRange extends ComponentPublicInstance { /** * Used to specify the name of the control; Useful if dealing with forms submitted directly to a URL */ name? : string /** * Model of the component of type { min, max } (both values must be between global min/max); Either use this property (along with a listener for 'update:modelValue' event) OR use v-model directive */ modelValue : { /** * Model value for left thumb */ min? : number /** * Model value for right thumb */ max? : number } /** * Minimum value of the model */ min? : number /** * Maximum value of the model */ max? : number /** * Specify step amount between valid values (> 0.0); When step equals to 0 it defines infinite granularity */ step? : number /** * Work in reverse (changes direction) */ reverse? : boolean /** * Display in vertical direction */ vertical? : boolean /** * User can drag range instead of just the two thumbs */ dragRange? : boolean /** * User can drag only the range instead and NOT the two thumbs */ dragOnlyRange? : boolean /** * Color name for component from the Quasar Color Palette */ color? : string /** * Popup labels (for left and right thumbs) when user clicks/taps on the slider thumb and moves it */ label? : boolean /** * Color name for labels background from the Quasar Color Palette; Applies to both labels, unless specific label color props are used */ labelColor? : string /** * Color name for labels text from the Quasar Color Palette; Applies to both labels, unless specific label text color props are used */ labelTextColor? : string /** * Color name for left label background from the Quasar Color Palette */ leftLabelColor? : string /** * Color name for left label text from the Quasar Color Palette */ leftLabelTextColor? : string /** * Color name for right label background from the Quasar Color Palette */ rightLabelColor? : string /** * Color name for right label text from the Quasar Color Palette */ rightLabelTextColor? : string /** * Override default label for min value */ leftLabelValue? : string | number /** * Override default label for max value */ rightLabelValue? : string | number /** * Always display the labels */ labelAlways? : boolean /** * Display markers on the track, one for each possible value for the model */ markers? : boolean /** * Snap thumbs on valid values, rather than sliding freely; Suggestion: use with 'step' prop */ snap? : boolean /** * Set custom thumbs svg path */ thumbPath? : string /** * Notify the component that the background is a dark color */ dark? : boolean /** * Dense mode; occupies less space */ dense? : boolean /** * Put component in disabled mode */ disable? : boolean /** * Put component in readonly mode */ readonly? : boolean /** * Tabindex HTML attribute value */ tabindex? : number | string } export interface QRating extends ComponentPublicInstance { /** * Used to specify the name of the control; Useful if dealing with forms submitted directly to a URL */ name? : string /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * Model of the component; Either use this property (along with a listener for 'update:model-value' event) OR use v-model directive */ modelValue : number /** * Number of icons to display */ max? : number | string /** * Icon name following Quasar convention; make sure you have the icon library installed unless you are using 'img:' prefix; If an array is provided each rating value will use the corresponding icon in the array (0 based) */ icon? : string | any[] /** * Icon name following Quasar convention to be used when selected (optional); make sure you have the icon library installed unless you are using 'img:' prefix; If an array is provided each rating value will use the corresponding icon in the array (0 based) */ iconSelected? : string | any[] /** * Icon name following Quasar convention to be used when selected (optional); make sure you have the icon library installed unless you are using 'img:' prefix; If an array is provided each rating value will use the corresponding icon in the array (0 based) */ iconHalf? : string | any[] /** * Color name for component from the Quasar Color Palette; v1.5.0+: If an array is provided each rating value will use the corresponding color in the array (0 based) */ color? : string | any[] /** * Color name from the Quasar Palette for selected icons */ colorSelected? : string | any[] /** * Color name from the Quasar Palette for half selected icons */ colorHalf? : string | any[] /** * Does not lower opacity for unselected icons */ noDimming? : boolean /** * When used, disables default behavior of clicking/tapping on icon which represents current model value to reset model to 0 */ noReset? : boolean /** * Put component in readonly mode */ readonly? : boolean /** * Put component in disabled mode */ disable? : boolean } export interface QResizeObserver extends ComponentPublicInstance { /** * Debounce amount (in milliseconds) */ debounce? : string | number /** * Emit a 'resize' event * @param immediately Skip over the debounce amount */ trigger (immediately? : boolean): void } export interface QResponsive extends ComponentPublicInstance { /** * Aspect ratio for the content; If value is a String, then avoid using a computational statement (like '16/9') and instead specify the String value of the result directly (eg. '1.7777') */ ratio? : string | number } export interface QScrollArea extends ComponentPublicInstance { /** * Notify the component that the background is a dark color */ dark? : boolean /** * Object with CSS properties and values for custom styling the scrollbars (both vertical and horizontal) */ barStyle? : any[] | string | LooseDictionary /** * Object with CSS properties and values for custom styling the vertical scrollbar; Is applied on top of 'bar-style' prop */ verticalBarStyle? : any[] | string | LooseDictionary /** * Object with CSS properties and values for custom styling the horizontal scrollbar; Is applied on top of 'bar-style' prop */ horizontalBarStyle? : any[] | string | LooseDictionary /** * Object with CSS properties and values for custom styling the thumb of scrollbars (both vertical and horizontal) */ thumbStyle? : LooseDictionary /** * Object with CSS properties and values for custom styling the thumb of the vertical scrollbar; Is applied on top of 'thumb-style' prop */ verticalThumbStyle? : LooseDictionary /** * Object with CSS properties and values for custom styling the thumb of the horizontal scrollbar; Is applied on top of 'thumb-style' prop */ horizontalThumbStyle? : LooseDictionary /** * Object with CSS properties and values for styling the container of QScrollArea */ contentStyle? : any[] | string | LooseDictionary /** * Object with CSS properties and values for styling the container of QScrollArea when scroll area becomes active (is mouse hovered) */ contentActiveStyle? : any[] | string | LooseDictionary /** * Manually control the visibility of the scrollbar; Overrides default mouse over/leave behavior */ visible? : boolean /** * When content changes, the scrollbar appears; this delay defines the amount of time (in milliseconds) before scrollbars disappear again (if component is not hovered) */ delay? : number | string /** * Tabindex HTML attribute value */ tabindex? : number | string /** * Get the scrolling DOM element target * @returns DOM element upon which scrolling takes place */ getScrollTarget (): LooseDictionary /** * Get the current scroll information * @returns Scroll information */ getScroll (): { /** * Vertical scroll position (in px) */ verticalPosition? : number /** * Vertical scroll percentage (0.0 <= x <= 1.0) */ verticalPercentage? : number /** * Vertical scroll size (in px) */ verticalSize? : number /** * Height of the container (in px) */ verticalContainerSize? : number /** * Horizontal scroll position (in px) */ horizontalPosition? : number /** * Horizontal scroll percentage (0.0 <= x <= 1.0) */ horizontalPercentage? : number /** * Horizontal scroll size (in px) */ horizontalSize? : number /** * Width of the container (in px) */ horizontalContainerSize? : number } /** * Get current scroll position * @returns undefined */ getScrollPosition (): { /** * Scroll offset from top (vertical) */ top? : number /** * Scroll offset from left (horizontal) */ left? : number } /** * Get current scroll position in percentage (0.0 <= x <= 1.0) * @returns undefined */ getScrollPercentage (): { /** * Scroll percentage (0.0 <= x <= 1.0) offset from top (vertical) */ top? : number /** * Scroll percentage (0.0 <= x <= 1.0) offset from left (horizontal) */ left? : number } /** * Set scroll position to an offset; If a duration (in milliseconds) is specified then the scroll is animated * @param axis Scroll axis * @param offset Scroll position offset from top (in pixels) * @param duration Duration (in milliseconds) enabling animated scroll */ setScrollPosition (axis : 'vertical' | 'horizontal', offset : number, duration? : number): void /** * Set scroll position to a percentage (0.0 <= x <= 1.0) of the total scrolling size; If a duration (in milliseconds) is specified then the scroll is animated * @param axis Scroll axis * @param offset Scroll percentage (0.0 <= x <= 1.0) of the total scrolling size * @param duration Duration (in milliseconds) enabling animated scroll */ setScrollPercentage (axis : 'vertical' | 'horizontal', offset : number, duration? : number): void } export interface QScrollObserver extends ComponentPublicInstance { /** * Debounce amount (in milliseconds) */ debounce? : string | number /** * Axis on which to detect changes */ axis? : 'both' | 'vertical' | 'horizontal' /** * CSS selector or DOM element to be used as a custom scroll container instead of the auto detected one */ scrollTarget? : Element | string /** * Emit a 'scroll' event * @param immediately Skip over the debounce amount */ trigger (immediately? : boolean): void /** * Get current scroll details under the form of an Object: { position, direction, directionChanged, inflectionPoint } */ getPosition (): void } export interface QSelect extends ComponentPublicInstance { /** * Used to specify the name of the control; Useful if dealing with forms; If not specified, it takes the value of 'for' prop, if it exists */ name? : string /** * Make virtual list work in horizontal mode */ virtualScrollHorizontal? : boolean /** * Minimum number of items to render in the virtual list */ virtualScrollSliceSize? : number | string /** * Ratio of number of items in visible zone to render before it */ virtualScrollSliceRatioBefore? : number | string /** * Ratio of number of items in visible zone to render after it */ virtualScrollSliceRatioAfter? : number | string /** * Default size in pixels (height if vertical, width if horizontal) of an item; This value is used for rendering the initial list; Try to use a value close to the minimum size of an item */ virtualScrollItemSize? : number | string /** * Size in pixels (height if vertical, width if horizontal) of the sticky part (if using one) at the start of the list; A correct value will improve scroll precision */ virtualScrollStickySizeStart? : number | string /** * Size in pixels (height if vertical, width if horizontal) of the sticky part (if using one) at the end of the list; A correct value will improve scroll precision */ virtualScrollStickySizeEnd? : number | string /** * The number of columns in the table (you need this if you use table-layout: fixed) */ tableColspan? : number | string /** * Model of the component; Must be Array if using 'multiple' prop; Either use this property (along with a listener for 'update:modelValue' event) OR use v-model directive */ modelValue : number | string | any[] /** * Does field have validation errors? */ error? : boolean /** * Validation error message (gets displayed only if 'error' is set to 'true') */ errorMessage? : string /** * Hide error icon when there is an error */ noErrorIcon? : boolean /** * Array of Functions/Strings; If String, then it must be a name of one of the embedded validation rules */ rules? : any[] /** * By default a change in the rules does not trigger a new validation until the model changes; If set to true then a change in the rules will trigger a validation; Has a performance penalty, so use it only when you really need it */ reactiveRules? : boolean /** * If set to boolean true then it checks validation status against the 'rules' only after field loses focus for first time; If set to 'ondemand' then it will trigger only when component's validate() method is manually called or when the wrapper QForm submits itself */ lazyRules? : boolean | 'ondemand' /** * A text label that will “float” up above the input field, once the field gets focus */ label? : string /** * Label will be always shown above the field regardless of field content (if any) */ stackLabel? : boolean /** * Helper (hint) text which gets placed below your wrapped form component */ hint? : string /** * Hide the helper (hint) text when field doesn't have focus */ hideHint? : boolean /** * Prefix */ prefix? : string /** * Suffix */ suffix? : string /** * Color name for the label from the Quasar Color Palette; Overrides the 'color' prop; The difference from 'color' prop is that the label will always have this color, even when field is not focused */ labelColor? : string /** * Color name for component from the Quasar Color Palette */ color? : string /** * Color name for component from the Quasar Color Palette */ bgColor? : string /** * Notify the component that the background is a dark color */ dark? : boolean /** * Signals the user a process is in progress by displaying a spinner; Spinner can be customized by using the 'loading' slot. */ loading? : boolean /** * Appends clearable icon when a value (not undefined or null) is set; When clicked, model becomes null */ clearable? : boolean /** * Custom icon to use for the clear button when using along with 'clearable' prop */ clearIcon? : string /** * Use 'filled' design for the field */ filled? : boolean /** * Use 'outlined' design for the field */ outlined? : boolean /** * Use 'borderless' design for the field */ borderless? : boolean /** * Use 'standout' design for the field; Specifies classes to be applied when focused (overriding default ones) */ standout? : boolean | string /** * Enables label slot; You need to set it to force use of the 'label' slot if the 'label' prop is not set */ labelSlot? : boolean /** * Enables bottom slots ('error', 'hint', 'counter') */ bottomSlots? : boolean /** * Do not reserve space for hint/error/counter anymore when these are not used; As a result, it also disables the animation for those; It also allows the hint/error area to stretch vertically based on its content */ hideBottomSpace? : boolean /** * Show an automatic counter on bottom right */ counter? : boolean /** * Applies a small standard border-radius for a squared shape of the component */ rounded? : boolean /** * Remove border-radius so borders are squared; Overrides 'rounded' prop */ square? : boolean /** * Dense mode; occupies less space */ dense? : boolean /** * Match inner content alignment to that of QItem */ itemAligned? : boolean /** * Put component in disabled mode */ disable? : boolean /** * Put component in readonly mode */ readonly? : boolean /** * Focus field on initial component render */ autofocus? : boolean /** * Used to specify the 'id' of the control and also the 'for' attribute of the label that wraps it; If no 'name' prop is specified, then it is used for this attribute as well */ for? : string /** * Allow multiple selection; Model must be Array */ multiple? : boolean /** * Override default selection string, if not using 'selected' slot/scoped slot and if not using 'use-chips' prop */ displayValue? : number | string /** * Force render the selected option(s) as HTML; This can lead to XSS attacks so make sure that you sanitize the content; Does NOT apply when using 'selected' or 'selected-item' slots! */ displayValueHtml? : boolean /** * Available options that the user can select from. For best performance freeze the list of options. */ options? : any[] /** * Property of option which holds the 'value'; If using a function then for best performance, reference it from your scope and do not define it inline */ optionValue? : Function | string /** * Property of option which holds the 'label'; If using a function then for best performance, reference it from your scope and do not define it inline */ optionLabel? : Function | string /** * Property of option which tells it's disabled; The value of the property must be a Boolean; If using a function then for best performance, reference it from your scope and do not define it inline */ optionDisable? : Function | string /** * Hides selection; Use the underlying input tag to hold the label (instead of showing it to the right of the input) of the selected option; Only works for non 'multiple' Selects */ hideSelected? : boolean /** * Hides dropdown icon */ hideDropdownIcon? : boolean /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ dropdownIcon? : string /** * Allow a maximum number of selections that the user can do */ maxValues? : number | string /** * Dense mode for options list; occupies less space */ optionsDense? : boolean /** * Options menu will be colored with a dark color */ optionsDark? : boolean /** * CSS class name for options that are active/selected; Set it to an empty string to stop applying the default (which is text-* where * is the 'color' prop value) */ optionsSelectedClass? : string /** * Force render the options as HTML; This can lead to XSS attacks so make sure that you sanitize the content; Does NOT apply when using 'option' slot! */ optionsHtml? : boolean /** * Expanded menu will cover the component (will not work along with 'use-input' prop for obvious reasons) */ optionsCover? : boolean /** * Allow the options list to be narrower than the field (only in menu mode) */ menuShrink? : boolean /** * Two values setting the starting position or anchor point of the options list relative to the field (only in menu mode) */ menuAnchor? : 'top left' | 'top middle' | 'top right' | 'top start' | 'top end' | 'center left' | 'center middle' | 'center right' | 'center start' | 'center end' | 'bottom left' | 'bottom middle' | 'bottom right' | 'bottom start' | 'bottom end' /** * Two values setting the options list's own position relative to its target (only in menu mode) */ menuSelf? : 'top left' | 'top middle' | 'top right' | 'top start' | 'top end' | 'center left' | 'center middle' | 'center right' | 'center start' | 'center end' | 'bottom left' | 'bottom middle' | 'bottom right' | 'bottom start' | 'bottom end' /** * An array of two numbers to offset the options list horizontally and vertically in pixels (only in menu mode) */ menuOffset? : any[] /** * Class definitions to be attributed to the popup content */ popupContentClass? : string /** * Style definitions to be attributed to the popup content */ popupContentStyle? : any[] | string | LooseDictionary /** * Use an input tag where users can type */ useInput? : boolean /** * Use QChip to show what is currently selected */ useChips? : boolean /** * Fills the input with current value; Useful along with 'hide-selected'; Does NOT works along with 'multiple' selection */ fillInput? : boolean /** * Enables creation of new values and defines behavior when a new value is added: 'add' means it adds the value (even if possible duplicate), 'add-unique' adds only unique values, and 'toggle' adds or removes the value (based on if it exists or not already); When using this prop then listening for @new-value becomes optional (only to override the behavior defined by 'new-value-mode') */ newValueMode? : 'add' | 'add-unique' | 'toggle' /** * Try to map labels of model from 'options' Array; has a small performance penalty; If you are using emit-value you will probably need to use map-options to display the label text in the select field rather than the value; Refer to the 'Affecting model' section above */ mapOptions? : boolean /** * Update model with the value of the selected option instead of the whole option */ emitValue? : boolean /** * Debounce the input model update with an amount of milliseconds */ inputDebounce? : number | string /** * Class definitions to be attributed to the underlying input tag */ inputClass? : any[] | string | LooseDictionary /** * Style definitions to be attributed to the underlying input tag */ inputStyle? : any[] | string | LooseDictionary /** * Tabindex HTML attribute value */ tabindex? : number | string /** * Autocomplete attribute for field */ autocomplete? : string /** * Transition when showing the menu/dialog; One of Quasar's embedded transitions */ transitionShow? : string /** * Transition when hiding the menu/dialog; One of Quasar's embedded transitions */ transitionHide? : string /** * Transition duration when hiding the menu/dialog (in milliseconds, without unit) */ transitionDuration? : string | number /** * Overrides the default dynamic mode of showing as menu on desktop and dialog on mobiles */ behavior? : 'default' | 'menu' | 'dialog' /** * Scroll the virtual scroll list to the item with the specified index (0 based) * @param index The index of the list item (0 based) * @param edge The edge to align to if the item is not visible already (by default it aligns to end if scrolling towards the end and to start otherwise); If the '-force' version is used then it always aligns */ scrollTo (index : string | number, edge? : 'start' | 'center' | 'end' | 'start-force' | 'center-force' | 'end-force'): void /** * Resets the virtual scroll computations; Needed for custom edge-cases */ reset (): void /** * Refreshes the virtual scroll list; Use it after appending items * @param index The index of the list item to scroll to after refresh (0 based); If it's not specified the scroll position is not changed; Use a negative value to keep scroll position */ refresh (index? : string | number): void /** * Reset validation status */ resetValidation (): void /** * Trigger a validation * @param value Optional value to validate against * @returns True/false if no async rules, otherwise a Promise with the outcome (true -> validation was a success, false -> invalid models detected) */ validate (value? : any): boolean | Promise<boolean> /** * Focus component */ focus (): void /** * Blur component (lose focus) */ blur (): void /** * Focus and open popup */ showPopup (): void /** * Hide popup */ hidePopup (): void /** * Remove selected option located at specific index * @param index Index at which to remove selection */ removeAtIndex (index : number): void /** * Adds option to model * @param opt Option to add to model * @param unique Option must be unique */ add (opt : any, unique? : boolean): void /** * Add/remove option from model * @param opt Option to add to model * @param keepOpen Don't close the menu and do not clear the filter */ toggleOption (opt : any, keepOpen? : boolean): void /** * Sets option from menu as 'focused' * @param index Index of option from menu */ setOptionIndex (index : number): void /** * Move selected option from menu by index offset * @param offset Number of options to move up or down * @param skipInputValue Don't set input-value on navigation */ moveOptionSelection (offset? : number, skipInputValue? : boolean): void /** * Filter options * @param value String to filter with */ filter (value : string): void /** * Recomputes menu position */ updateMenuPosition (): void /** * If 'use-input' is specified, this updates the value that it holds * @param value String to set the input value to * @param noFilter Set to true if you don't want the filter (if any) to be also triggered */ updateInputValue (value? : string, noFilter? : boolean): void /** * Tells if an option is selected * @param opt Option entry * @returns Option is selected or not */ isOptionSelected (opt : any): boolean /** * Get the model value that would be emitted by QSelect when selecting a said option; Also takes into consideration if 'emit-value' is set * @param opt Option entry * @returns Emitting model value of said option */ getEmittingOptionValue (opt : any): any /** * Get the model value of an option; Takes into consideration 'option-value' (if used), but does not looks for 'emit-value', like getEmittingOptionValue() does * @param opt Option entry * @returns Model value of said option */ getOptionValue (opt : any): any /** * Get the label of an option; Takes into consideration the 'option-label' prop (if used) * @param opt Option entry * @returns Label of said option */ getOptionLabel (opt : any): any /** * Tells if an option is disabled; Takes into consideration 'option-disable' prop (if used) * @param opt Option entry * @returns Option is disabled or not */ isOptionDisabled (opt : any): boolean } export interface QSeparator extends ComponentPublicInstance { /** * Notify the component that the background is a dark color */ dark? : boolean /** * If set to true, the corresponding direction margins will be set to 8px; It can also be set to a size in CSS units, including unit name, or one of the xs|sm|md|lg|xl predefined sizes */ spaced? : boolean | string /** * if set to true, the left and right margins will be set to 16px. If set to item, the left and right margins will be set to 72px. If set to item-thumbnail, the left margin is set to 116px and right margin is set to 0px */ inset? : boolean | string /** * If set to true, the separator will be vertical. */ vertical? : boolean /** * Size in CSS units, including unit name */ size? : string /** * Color name for component from the Quasar Color Palette */ color? : string } export interface QSkeleton extends ComponentPublicInstance { /** * Notify the component that the background is a dark color */ dark? : boolean /** * Type of skeleton placeholder */ type? : 'text' | 'rect' | 'circle' | 'QBtn' | 'QBadge' | 'QChip' | 'QToolbar' | 'QCheckbox' | 'QRadio' | 'QToggle' | 'QSlider' | 'QRange' | 'QInput' | 'QAvatar' /** * The animation effect of the skeleton placeholder */ animation? : 'wave' | 'pulse' | 'pulse-x' | 'pulse-y' | 'fade' | 'blink' | 'none' /** * Removes border-radius so borders are squared */ square? : boolean /** * Applies a default border to the component */ bordered? : boolean /** * Size in CSS units, including unit name; Overrides 'height' and 'width' props and applies the value to both height and width */ size? : string /** * Width in CSS units, including unit name; Apply custom width; Use this prop or through CSS; Overridden by 'size' prop if used */ width? : string /** * Height in CSS units, including unit name; Apply custom height; Use this prop or through CSS; Overridden by 'size' prop if used */ height? : string /** * HTML tag to use */ tag? : string } export interface QSlideItem extends ComponentPublicInstance { /** * Color name for left-side background from the Quasar Color Palette */ leftColor? : string /** * Color name for right-side background from the Quasar Color Palette */ rightColor? : string /** * Color name for top-side background from the Quasar Color Palette */ topColor? : string /** * Color name for bottom-side background from the Quasar Color Palette */ bottomColor? : string /** * Notify the component that the background is a dark color */ dark? : boolean /** * Reset to initial state (not swiped to any side) */ reset (): void } export interface QSlideTransition extends ComponentPublicInstance { /** * If set to true, the transition will be applied on the initial render. */ appear? : boolean /** * Duration (in milliseconds) enabling animated scroll. */ duration? : number } export interface QSlider extends ComponentPublicInstance { /** * Used to specify the name of the control; Useful if dealing with forms submitted directly to a URL */ name? : string /** * Model of the component (must be between min/max); Either use this property (along with a listener for 'update:modelValue' event) OR use v-model directive */ modelValue : number /** * Minimum value of the model */ min? : number /** * Maximum value of the model */ max? : number /** * Specify step amount between valid values (> 0.0); When step equals to 0 it defines infinite granularity */ step? : number /** * Work in reverse (changes direction) */ reverse? : boolean /** * Display in vertical direction */ vertical? : boolean /** * Color name for component from the Quasar Color Palette */ color? : string /** * Popup a label when user clicks/taps on the slider thumb and moves it */ label? : boolean /** * Color name for component from the Quasar Color Palette */ labelColor? : string /** * Color name for component from the Quasar Color Palette */ labelTextColor? : string /** * Override default label value */ labelValue? : string | number /** * Always display the label */ labelAlways? : boolean /** * Display markers on the track, one for each possible value for the model */ markers? : boolean /** * Snap on valid values, rather than sliding freely; Suggestion: use with 'step' prop */ snap? : boolean /** * Set custom thumb svg path */ thumbPath? : string /** * Notify the component that the background is a dark color */ dark? : boolean /** * Dense mode; occupies less space */ dense? : boolean /** * Put component in disabled mode */ disable? : boolean /** * Put component in readonly mode */ readonly? : boolean /** * Tabindex HTML attribute value */ tabindex? : number | string } export interface QSpace extends ComponentPublicInstance { } export interface QSpinner extends ComponentPublicInstance { /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * Color name for component from the Quasar Color Palette */ color? : string /** * Override value to use for stroke-width */ thickness? : number } export interface QSpinnerAudio extends ComponentPublicInstance { /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * Color name for component from the Quasar Color Palette */ color? : string } export interface QSpinnerBall extends ComponentPublicInstance { /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * Color name for component from the Quasar Color Palette */ color? : string } export interface QSpinnerBars extends ComponentPublicInstance { /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * Color name for component from the Quasar Color Palette */ color? : string } export interface QSpinnerBox extends ComponentPublicInstance { /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * Color name for component from the Quasar Color Palette */ color? : string } export interface QSpinnerClock extends ComponentPublicInstance { /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * Color name for component from the Quasar Color Palette */ color? : string } export interface QSpinnerComment extends ComponentPublicInstance { /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * Color name for component from the Quasar Color Palette */ color? : string } export interface QSpinnerCube extends ComponentPublicInstance { /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * Color name for component from the Quasar Color Palette */ color? : string } export interface QSpinnerDots extends ComponentPublicInstance { /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * Color name for component from the Quasar Color Palette */ color? : string } export interface QSpinnerFacebook extends ComponentPublicInstance { /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * Color name for component from the Quasar Color Palette */ color? : string } export interface QSpinnerGears extends ComponentPublicInstance { /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * Color name for component from the Quasar Color Palette */ color? : string } export interface QSpinnerGrid extends ComponentPublicInstance { /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * Color name for component from the Quasar Color Palette */ color? : string } export interface QSpinnerHearts extends ComponentPublicInstance { /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * Color name for component from the Quasar Color Palette */ color? : string } export interface QSpinnerHourglass extends ComponentPublicInstance { /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * Color name for component from the Quasar Color Palette */ color? : string } export interface QSpinnerInfinity extends ComponentPublicInstance { /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * Color name for component from the Quasar Color Palette */ color? : string } export interface QSpinnerIos extends ComponentPublicInstance { /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * Color name for component from the Quasar Color Palette */ color? : string } export interface QSpinnerOrbit extends ComponentPublicInstance { /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * Color name for component from the Quasar Color Palette */ color? : string } export interface QSpinnerOval extends ComponentPublicInstance { /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * Color name for component from the Quasar Color Palette */ color? : string } export interface QSpinnerPie extends ComponentPublicInstance { /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * Color name for component from the Quasar Color Palette */ color? : string } export interface QSpinnerPuff extends ComponentPublicInstance { /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * Color name for component from the Quasar Color Palette */ color? : string } export interface QSpinnerRadio extends ComponentPublicInstance { /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * Color name for component from the Quasar Color Palette */ color? : string } export interface QSpinnerRings extends ComponentPublicInstance { /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * Color name for component from the Quasar Color Palette */ color? : string } export interface QSpinnerTail extends ComponentPublicInstance { /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * Color name for component from the Quasar Color Palette */ color? : string } export interface QSplitter extends ComponentPublicInstance { /** * Model of the component defining the size of first panel (or second if using reverse) in the unit specified (for '%' it's the split ratio percent - 0.0 < x < 100.0; for 'px' it's the size in px); Either use this property (along with a listener for 'update:modelValue' event) OR use v-model directive */ modelValue : number /** * Apply the model size to the second panel (by default it applies to the first) */ reverse? : boolean /** * CSS unit for the model */ unit? : '%' | 'px' /** * Emit model while user is panning on the separator */ emitImmediately? : boolean /** * Allows the splitter to split its two panels horizontally, instead of vertically */ horizontal? : boolean /** * An array of two values representing the minimum and maximum split size of the two panels; When 'px' unit is set then you can use Infinity as the second value to make it unbound on the other side */ limits? : any[] /** * Put component in disabled mode */ disable? : boolean /** * Class definitions to be attributed to the 'before' panel */ beforeClass? : any[] | string | LooseDictionary /** * Class definitions to be attributed to the 'after' panel */ afterClass? : any[] | string | LooseDictionary /** * Class definitions to be attributed to the splitter separator */ separatorClass? : any[] | string | LooseDictionary /** * Style definitions to be attributed to the splitter separator */ separatorStyle? : any[] | string | LooseDictionary /** * Applies a default lighter color on the separator; To be used when background is darker; Avoid using when you are overriding through separator-class or separator-style props */ dark? : boolean } export interface QStep extends ComponentPublicInstance { /** * Panel name */ name : any /** * Put component in disabled mode */ disable? : boolean /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ icon? : string /** * Color name for component from the Quasar Color Palette */ color? : string /** * Step title */ title : string /** * Step’s additional information that appears beneath the title */ caption? : string /** * Step's prefix (max 2 characters) which replaces the icon if step does not has error, is being edited or is marked as done */ prefix? : string | number /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ doneIcon? : string /** * Color name for component from the Quasar Color Palette */ doneColor? : string /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ activeIcon? : string /** * Color name for component from the Quasar Color Palette */ activeColor? : string /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ errorIcon? : string /** * Color name for component from the Quasar Color Palette */ errorColor? : string /** * Allow navigation through the header */ headerNav? : boolean /** * Mark the step as 'done' */ done? : boolean /** * Mark the step as having an error */ error? : boolean } export interface QStepper extends ComponentPublicInstance { /** * Model of the component defining the current panel's name; If a Number is used, it does not define the panel's index, but rather the panel's name which can also be an Integer; Either use this property (along with a listener for 'update:model-value' event) OR use the v-model directive. */ modelValue? : any /** * Equivalent to using Vue's native <keep-alive> component on the content */ keepAlive? : boolean /** * Equivalent to using Vue's native include prop for <keep-alive>; Values must be valid Vue component names */ keepAliveInclude? : string | any[] | RegExp /** * Equivalent to using Vue's native exclude prop for <keep-alive>; Values must be valid Vue component names */ keepAliveExclude? : string | any[] | RegExp /** * Equivalent to using Vue's native max prop for <keep-alive> */ keepAliveMax? : number /** * Enable transitions between panel (also see 'transition-prev' and 'transition-next' props) */ animated? : boolean /** * Makes component appear as infinite (when reaching last panel, next one will become the first one) */ infinite? : boolean /** * Enable swipe events (may interfere with content's touch/mouse events) */ swipeable? : boolean /** * Put Stepper in vertical mode (instead of horizontal by default) */ vertical? : boolean /** * One of Quasar's embedded transitions (has effect only if 'animated' prop is set) */ transitionPrev? : string /** * One of Quasar's embedded transitions (has effect only if 'animated' prop is set) */ transitionNext? : string /** * Notify the component that the background is a dark color */ dark? : boolean /** * Applies a 'flat' design (no default shadow) */ flat? : boolean /** * Applies a default border to the component */ bordered? : boolean /** * Use alternative labels - stacks the icon on top of the label (applies only to horizontal stepper) */ alternativeLabels? : boolean /** * Allow navigation through the header */ headerNav? : boolean /** * Hide header labels on narrow windows */ contracted? : boolean /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ inactiveIcon? : string /** * Color name for component from the Quasar Color Palette */ inactiveColor? : string /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ doneIcon? : string /** * Color name for component from the Quasar Color Palette */ doneColor? : string /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ activeIcon? : string /** * Color name for component from the Quasar Color Palette */ activeColor? : string /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ errorIcon? : string /** * Color name for component from the Quasar Color Palette */ errorColor? : string /** * Class definitions to be attributed to the header */ headerClass? : string /** * Go to next panel */ next (): void /** * Go to previous panel */ previous (): void /** * Go to specific panel * @param panelName Panel's name, which may be a String or Number; Number does not refers to panel index, but to its name, which may be an Integer */ goTo (panelName : string | number): void } export interface QStepperNavigation extends ComponentPublicInstance { } export interface QTabPanel extends ComponentPublicInstance { /** * Panel name */ name : any /** * Put component in disabled mode */ disable? : boolean /** * Notify the component that the background is a dark color */ dark? : boolean } export interface QTabPanels extends ComponentPublicInstance { /** * Model of the component defining the current panel's name; If a Number is used, it does not define the panel's index, but rather the panel's name which can also be an Integer; Either use this property (along with a listener for 'update:model-value' event) OR use the v-model directive. */ modelValue? : any /** * Equivalent to using Vue's native <keep-alive> component on the content */ keepAlive? : boolean /** * Equivalent to using Vue's native include prop for <keep-alive>; Values must be valid Vue component names */ keepAliveInclude? : string | any[] | RegExp /** * Equivalent to using Vue's native exclude prop for <keep-alive>; Values must be valid Vue component names */ keepAliveExclude? : string | any[] | RegExp /** * Equivalent to using Vue's native max prop for <keep-alive> */ keepAliveMax? : number /** * Enable transitions between panel (also see 'transition-prev' and 'transition-next' props) */ animated? : boolean /** * Makes component appear as infinite (when reaching last panel, next one will become the first one) */ infinite? : boolean /** * Enable swipe events (may interfere with content's touch/mouse events) */ swipeable? : boolean /** * Default transitions and swipe actions will be on the vertical axis */ vertical? : boolean /** * One of Quasar's embedded transitions (has effect only if 'animated' prop is set) */ transitionPrev? : string /** * One of Quasar's embedded transitions (has effect only if 'animated' prop is set) */ transitionNext? : string /** * Go to next panel */ next (): void /** * Go to previous panel */ previous (): void /** * Go to specific panel * @param panelName Panel's name, which may be a String or Number; Number does not refers to panel index, but to its name, which may be an Integer */ goTo (panelName : string | number): void } export interface QTable extends ComponentPublicInstance { /** * Fullscreen mode */ fullscreen? : boolean /** * Changing route app won't exit fullscreen */ noRouteFullscreenExit? : boolean /** * Rows of data to display */ rows? : any[] /** * Property of each row that defines the unique key of each row (the result must be a primitive, not Object, Array, etc); The value of property must be string or a function taking a row and returning the desired (nested) key in the row; If supplying a function then for best performance, reference it from your scope and do not define it inline */ rowKey? : string | Function /** * Display data using QVirtualScroll (for non-grid mode only) */ virtualScroll? : boolean /** * Minimum number of rows to render in the virtual list */ virtualScrollSliceSize? : number | string /** * Ratio of number of rows in visible zone to render before it */ virtualScrollSliceRatioBefore? : number | string /** * Ratio of number of rows in visible zone to render after it */ virtualScrollSliceRatioAfter? : number | string /** * Default size in pixels of a row; This value is used for rendering the initial table; Try to use a value close to the minimum size of a row */ virtualScrollItemSize? : number | string /** * Size in pixels of the sticky header (if using one); A correct value will improve scroll precision */ virtualScrollStickySizeStart? : number | string /** * Size in pixels of the sticky footer part (if using one); A correct value will improve scroll precision */ virtualScrollStickySizeEnd? : number | string /** * The number of columns in the table (you need this if you use table-layout: fixed) */ tableColspan? : number | string /** * Color name for component from the Quasar Color Palette */ color? : string /** * Icon name following Quasar convention for stepping to first page; Make sure you have the icon library installed unless you are using 'img:' prefix */ iconFirstPage? : string /** * Icon name following Quasar convention for stepping to previous page; Make sure you have the icon library installed unless you are using 'img:' prefix */ iconPrevPage? : string /** * Icon name following Quasar convention for stepping to next page; Make sure you have the icon library installed unless you are using 'img:' prefix */ iconNextPage? : string /** * Icon name following Quasar convention for stepping to last page; Make sure you have the icon library installed unless you are using 'img:' prefix */ iconLastPage? : string /** * Display data as a grid instead of the default table */ grid? : boolean /** * Display header for grid-mode also */ gridHeader? : boolean /** * Dense mode; Connect with $q.screen for responsive behavior */ dense? : boolean /** * The column definitions (Array of Objects) */ columns? : { /** * Unique id, identifies column, (used by pagination.sortBy, 'body-cell-[name]' slot, ...) */ name : string /** * Label for header */ label : string /** * Row Object property to determine value for this column or function which maps to the required property */ field : string | Function /** * If we use visible-columns, this col will always be visible */ required? : boolean /** * Horizontal alignment of cells in this column */ align? : string /** * Tell QTable you want this column sortable */ sortable? : boolean /** * Compare function if you have some custom data or want a specific way to compare two rows */ sort? : Function /** * Set column sort order: 'ad' (ascending-descending) or 'da' (descending-ascending); Overrides the 'column-sort-order' prop */ sortOrder? : 'ad' | 'da' /** * Function you can apply to format your data */ format? : Function /** * Style to apply on normal cells of the column */ style? : string | Function /** * Classes to add on normal cells of the column */ classes? : string | Function /** * Style to apply on header cells of the column */ headerStyle? : string /** * Classes to add on header cells of the column */ headerClasses? : string }[] /** * Array of Strings defining column names ('name' property of each column from 'columns' prop definitions); Columns marked as 'required' are not affected by this property */ visibleColumns? : any[] /** * Put Table into 'loading' state; Notify the user something is happening behind the covers */ loading? : boolean /** * Table title */ title? : string /** * Hide table header layer */ hideHeader? : boolean /** * Hide table bottom layer regardless of what it has to display */ hideBottom? : boolean /** * Hide the selected rows banner (if any) */ hideSelectedBanner? : boolean /** * Hide the default no data bottom layer */ hideNoData? : boolean /** * Hide the pagination controls at the bottom */ hidePagination? : boolean /** * Notify the component that the background is a dark color */ dark? : boolean /** * Applies a 'flat' design (no default shadow) */ flat? : boolean /** * Applies a default border to the component */ bordered? : boolean /** * Removes border-radius so borders are squared */ square? : boolean /** * Use a separator/border between rows, columns or all cells */ separator? : 'horizontal' | 'vertical' | 'cell' | 'none' /** * Wrap text within table cells */ wrapCells? : boolean /** * Skip the third state (unsorted) when user toggles column sort direction */ binaryStateSort? : boolean /** * Set column sort order: 'ad' (ascending-descending) or 'da' (descending-ascending); It gets applied to all columns unless a column has its own sortOrder specified in the 'columns' definition prop */ columnSortOrder? : 'ad' | 'da' /** * Override default text to display when no data is available */ noDataLabel? : string /** * Override default text to display when user filters the table and no matched results are found */ noResultsLabel? : string /** * Override default text to display when table is in loading state (see 'loading' prop) */ loadingLabel? : string /** * Text to display when user selected at least one row; For best performance, reference it from your scope and do not define it inline */ selectedRowsLabel? : Function /** * Text to override default rows per page label at bottom of table */ rowsPerPageLabel? : string /** * Text to override default pagination label at bottom of table (unless 'pagination' scoped slot is used); For best performance, reference it from your scope and do not define it inline */ paginationLabel? : Function /** * CSS style to apply to native HTML <table> element's wrapper (which is a DIV) */ tableStyle? : string | any[] | LooseDictionary /** * CSS classes to apply to native HTML <table> element's wrapper (which is a DIV) */ tableClass? : string | any[] | LooseDictionary /** * CSS style to apply to header of native HTML <table> (which is a TR) */ tableHeaderStyle? : string | any[] | LooseDictionary /** * CSS classes to apply to header of native HTML <table> (which is a TR) */ tableHeaderClass? : string | any[] | LooseDictionary /** * CSS style to apply to the cards container (when in grid mode) */ cardContainerStyle? : string | any[] | LooseDictionary /** * CSS classes to apply to the cards container (when in grid mode) */ cardContainerClass? : string | any[] | LooseDictionary /** * CSS style to apply to the card (when in grid mode) or container card (when not in grid mode) */ cardStyle? : string | any[] | LooseDictionary /** * CSS classes to apply to the card (when in grid mode) or container card (when not in grid mode) */ cardClass? : string | any[] | LooseDictionary /** * CSS classes to apply to the title (if using 'title' prop) */ titleClass? : string | any[] | LooseDictionary /** * String/Object to filter table with; When using an Object it requires 'filter-method' to also be specified since it will be a custom filtering */ filter? : string | LooseDictionary /** * The actual filtering mechanism; For best performance, reference it from your scope and do not define it inline */ filterMethod? : Function /** * Pagination object; You can also use the 'v-model:pagination' for synching; When not synching it simply initializes the pagination on first render */ pagination? : { /** * Column name (from column definition) */ sortBy? : string /** * Is sorting in descending order? */ descending? : boolean /** * Page number (1-based) */ page? : number /** * How many rows per page? 0 means Infinite */ rowsPerPage? : number /** * For server-side fetching only. How many total database rows are there to be added to the table. If set, causes the QTable to emit @request when data is required. */ rowsNumber? : number } /** * Options for user to pick (Numbers); Number 0 means 'Show all rows in one page' */ rowsPerPageOptions? : any[] /** * Selection type */ selection? : 'single' | 'multiple' | 'none' /** * Keeps the user selection array */ selected? : any[] /** * Keeps the array with expanded rows keys */ expanded? : any[] /** * The actual sort mechanism. Function (rows, sortBy, descending) => sorted rows; For best performance, reference it from your scope and do not define it inline */ sortMethod? : Function /** * Toggles fullscreen mode */ toggleFullscreen (): void /** * Enter the fullscreen view */ setFullscreen (): void /** * Leave the fullscreen view */ exitFullscreen (): void /** * Trigger a server request (emits 'request' event) * @param props Request details */ requestServerInteraction (props? : { /** * Optional pagination object */ pagination? : { /** * Column name (from column definition) */ sortBy? : string /** * Is sorting in descending order? */ descending? : boolean /** * Page number (1-based) */ page? : number /** * How many rows per page? 0 means Infinite */ rowsPerPage? : number } /** * Filtering method (the 'filter-method' prop) */ filter? : Function }): void /** * Unless using an external pagination Object (through 'v-model:pagination' prop), you can use this method and force the internal pagination to change * @param pagination Pagination object * @param forceServerRequest Also force a server request */ setPagination (pagination : { /** * Column name (from column definition) */ sortBy? : string /** * Is sorting in descending order? */ descending? : boolean /** * Page number (1-based) */ page? : number /** * How many rows per page? 0 means Infinite */ rowsPerPage? : number }, forceServerRequest? : boolean): void /** * Navigates to first page */ firstPage (): void /** * Navigates to previous page, if available */ prevPage (): void /** * Navigates to next page, if available */ nextPage (): void /** * Navigates to last page */ lastPage (): void /** * Determine if a row has been selected by user * @param key Row key value * @returns Is row selected or not? */ isRowSelected (key : any): boolean /** * Clears user selection (emits 'update:selected' with empty array) */ clearSelection (): void /** * Determine if a row is expanded or not * @param key Row key value * @returns Is row expanded or not? */ isRowExpanded (key : any): boolean /** * Sets the expanded rows keys array; Especially useful if not using an external 'expanded' state otherwise just emits 'update:expanded' with the value * @param expanded Array containing keys of the expanded rows */ setExpanded (expanded : any[]): void /** * Trigger a table sort * @param col Column name or column definition object */ sort (col : string | LooseDictionary): void /** * Resets the virtual scroll (if using it) computations; Needed for custom edge-cases */ resetVirtualScroll (): void /** * Scroll the table to the row with the specified index in page (0 based) * @param index The index of the row in page (0 based) * @param edge Only for virtual scroll - the edge to align to if the row is not visible already (by default it aligns to end if scrolling towards the end and to start otherwise); If the '-force' version is used then it always aligns */ scrollTo (index : string | number, edge? : 'start' | 'center' | 'end' | 'start-force' | 'center-force' | 'end-force'): void } export interface QTd extends ComponentPublicInstance { /** * QTable's column scoped slot property */ props? : LooseDictionary /** * Tries to shrink column width size; Useful for columns with a checkbox/radio/toggle */ autoWidth? : boolean /** * Disable hover effect */ noHover? : boolean } export interface QTh extends ComponentPublicInstance { /** * QTable's header column scoped slot property */ props? : LooseDictionary /** * Tries to shrink header column width size; Useful for columns with a checkbox/radio/toggle */ autoWidth? : boolean } export interface QTr extends ComponentPublicInstance { /** * QTable's row scoped slot property */ props? : LooseDictionary /** * Disable hover effect */ noHover? : boolean } export interface QRouteTab extends ComponentPublicInstance { /** * Equivalent to Vue Router <router-link> 'to' property */ to : string | LooseDictionary /** * Equivalent to Vue Router <router-link> 'exact' property */ exact? : boolean /** * Equivalent to Vue Router <router-link> 'replace' property */ replace? : boolean /** * Equivalent to Vue Router <router-link> 'active-class' property */ activeClass? : string /** * Equivalent to Vue Router <router-link> 'active-class' property */ exactActiveClass? : string /** * Put component in disabled mode */ disable? : boolean /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ icon? : string /** * A number or string to label the tab */ label? : number | string /** * Adds an alert symbol to the tab, notifying the user there are some updates; If its value is not a Boolean, then you can specify a color */ alert? : boolean | string /** * Adds a floating icon to the tab, notifying the user there are some updates; It's displayed only if 'alert' is set; Can use the color specified by 'alert' prop */ alertIcon? : string /** * Panel name */ name? : number | string /** * Turns off capitalizing all letters within the tab (which is the default) */ noCaps? : boolean /** * Class definitions to be attributed to the content wrapper */ contentClass? : string /** * Configure material ripple (disable it by setting it to 'false' or supply a config object) */ ripple? : boolean | LooseDictionary /** * Tabindex HTML attribute value */ tabindex? : number | string } export interface QTab extends ComponentPublicInstance { /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ icon? : string /** * A number or string to label the tab */ label? : number | string /** * Adds an alert symbol to the tab, notifying the user there are some updates; If its value is not a Boolean, then you can specify a color */ alert? : boolean | string /** * Adds a floating icon to the tab, notifying the user there are some updates; It's displayed only if 'alert' is set; Can use the color specified by 'alert' prop */ alertIcon? : string /** * Panel name */ name? : number | string /** * Turns off capitalizing all letters within the tab (which is the default) */ noCaps? : boolean /** * Class definitions to be attributed to the content wrapper */ contentClass? : string /** * Configure material ripple (disable it by setting it to 'false' or supply a config object) */ ripple? : boolean | LooseDictionary /** * Tabindex HTML attribute value */ tabindex? : number | string /** * Put component in disabled mode */ disable? : boolean } export interface QTabs extends ComponentPublicInstance { /** * Model of the component defining current panel name; Either use this property (along with a listener for 'update:modelValue' event) OR use v-model directive */ modelValue? : number | string /** * Use vertical design (tabs one on top of each other rather than one next to the other horizontally) */ vertical? : boolean /** * Reserve space for arrows to place them on each side of the tabs (the arrows fade when inactive) */ outsideArrows? : boolean /** * Force display of arrows (if needed) on mobile */ mobileArrows? : boolean /** * Horizontal alignment the tabs within the tabs container */ align? : 'left' | 'center' | 'right' | 'justify' /** * Breakpoint (in pixels) of tabs container width at which the tabs automatically turn to a justify alignment */ breakpoint? : number | string /** * The color to be attributed to the text of the active tab */ activeColor? : string /** * The color to be attributed to the background of the active tab */ activeBgColor? : string /** * The color to be attributed to the indicator (the underline) of the active tab */ indicatorColor? : string /** * Class definitions to be attributed to the content wrapper */ contentClass? : string /** * The name of an icon to replace the default arrow used to scroll through the tabs to the left, when the tabs extend past the width of the tabs container */ leftIcon? : string /** * The name of an icon to replace the default arrow used to scroll through the tabs to the right, when the tabs extend past the width of the tabs container */ rightIcon? : string /** * When used on flexbox parent, tabs will stretch to parent's height */ stretch? : boolean /** * By default, QTabs is set to grow to the available space; However, you can reverse that with this prop; Useful (and required) when placing the component in a QToolbar */ shrink? : boolean /** * Switches the indicator position (on left of tab for vertical mode or above the tab for default horizontal mode) */ switchIndicator? : boolean /** * Allows the indicator to be the same width as the tab's content (text or icon), instead of the whole width of the tab */ narrowIndicator? : boolean /** * Allows the text to be inline with the icon, should one be used */ inlineLabel? : boolean /** * Turns off capitalizing all letters within the tab (which is the default) */ noCaps? : boolean /** * Dense mode; occupies less space */ dense? : boolean } export interface QTime extends ComponentPublicInstance { /** * Used to specify the name of the control; Useful if dealing with forms submitted directly to a URL */ name? : string /** * Display the component in landscape mode */ landscape? : boolean /** * Mask (formatting string) used for parsing and formatting value */ mask? : string /** * Locale formatting options */ locale? : { /** * List of full day names (DDDD), starting with Sunday */ days? : any[] /** * List of short day names (DDD), starting with Sunday */ daysShort? : any[] /** * List of full month names (MMMM), starting with January */ months? : any[] /** * List of short month names (MMM), starting with January */ monthsShort? : any[] } /** * Specify calendar type */ calendar? : 'gregorian' | 'persian' /** * Color name for component from the Quasar Color Palette */ color? : string /** * Overrides text color (if needed); Color name from the Quasar Color Palette */ textColor? : string /** * Notify the component that the background is a dark color */ dark? : boolean /** * Removes border-radius so borders are squared */ square? : boolean /** * Applies a 'flat' design (no default shadow) */ flat? : boolean /** * Applies a default border to the component */ bordered? : boolean /** * Put component in readonly mode */ readonly? : boolean /** * Put component in disabled mode */ disable? : boolean /** * Time of the component; Either use this property (along with a listener for 'update:modelValue' event) OR use v-model directive */ modelValue : string /** * Forces 24 hour time display instead of AM/PM system */ format24h? : boolean /** * The default date to use (in YYYY/MM/DD format) when model is unfilled (undefined or null) */ defaultDate? : string /** * Optionally configure what time is the user allowed to set; Overridden by 'hour-options', 'minute-options' and 'second-options' if those are set; For best performance, reference it from your scope and do not define it inline */ options? : Function /** * Optionally configure what hours is the user allowed to set; Overrides 'options' prop if that is also set */ hourOptions? : any[] /** * Optionally configure what minutes is the user allowed to set; Overrides 'options' prop if that is also set */ minuteOptions? : any[] /** * Optionally configure what seconds is the user allowed to set; Overrides 'options' prop if that is also set */ secondOptions? : any[] /** * Allow the time to be set with seconds */ withSeconds? : boolean /** * Display a button that selects the current time */ nowBtn? : boolean /** * Change model to current moment */ setNow (): void } export interface QTimeline extends ComponentPublicInstance { /** * Color name for component from the Quasar Color Palette */ color? : string /** * Side to place the timeline entries in dense and comfortable layout; For loose layout it gets overridden by QTimelineEntry side prop */ side? : 'left' | 'right' /** * Layout of the timeline. Dense keeps content and labels on one side. Comfortable keeps content on one side and labels on the opposite side. Loose puts content on both sides. */ layout? : 'dense' | 'comfortable' | 'loose' /** * Notify the component that the background is a dark color */ dark? : boolean } export interface QTimelineEntry extends ComponentPublicInstance { /** * Defines a heading timeline item */ heading? : boolean /** * Tag to use, if of type 'heading' only */ tag? : string /** * Side to place the timeline entry; Works only if QTimeline layout is loose. */ side? : 'left' | 'right' /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ icon? : string /** * URL to the avatar image; Icon takes precedence if used, so it replaces avatar */ avatar? : string /** * Color name for component from the Quasar Color Palette */ color? : string /** * Title of timeline entry; Is overridden if using 'title' slot */ title? : string /** * Subtitle of timeline entry; Is overridden if using 'subtitle' slot */ subtitle? : string /** * Body content of timeline entry; Use this prop or the default slot */ body? : string } export interface QToggle extends ComponentPublicInstance { /** * Used to specify the name of the control; Useful if dealing with forms submitted directly to a URL */ name? : string /** * Size in CSS units, including unit name or standard size name (xs|sm|md|lg|xl) */ size? : string /** * Model of the component; Either use this property (along with a listener for 'update:model-value' event) OR use v-model directive */ modelValue : any | any[] /** * Works when model ('value') is Array. It tells the component which value should add/remove when ticked/unticked */ val? : any /** * What model value should be considered as checked/ticked/on? */ trueValue? : any /** * What model value should be considered as unchecked/unticked/off? */ falseValue? : any /** * What model value should be considered as 'indeterminate'? */ indeterminateValue? : any /** * Determines toggle order of the two states ('t' stands for state of true, 'f' for state of false); If 'toggle-indeterminate' is true, then the order is: indet -> first state -> second state -> indet (and repeat), otherwise: indet -> first state -> second state -> first state -> second state -> ... */ toggleOrder? : 'tf' | 'ft' /** * When user clicks/taps on the component, should we toggle through the indeterminate state too? */ toggleIndeterminate? : boolean /** * Label to display along the component (or use the default slot instead of this prop) */ label? : string /** * Label (if any specified) should be displayed on the left side of the component */ leftLabel? : boolean /** * Color name for component from the Quasar Color Palette */ color? : string /** * Should the color (if specified any) be kept when the component is unticked/ off? */ keepColor? : boolean /** * Notify the component that the background is a dark color */ dark? : boolean /** * Dense mode; occupies less space */ dense? : boolean /** * Put component in disabled mode */ disable? : boolean /** * Tabindex HTML attribute value */ tabindex? : number | string /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ icon? : string /** * The icon to be used when the toggle is on */ checkedIcon? : string /** * The icon to be used when the toggle is off */ uncheckedIcon? : string /** * The icon to be used when the model is indeterminate */ indeterminateIcon? : string /** * Override default icon color (for truthy state only); Color name for component from the Quasar Color Palette */ iconColor? : string /** * Toggle the state (of the model) */ toggle (): void } export interface QToolbar extends ComponentPublicInstance { /** * Apply an inset to content (useful for subsequent toolbars) */ inset? : boolean } export interface QToolbarTitle extends ComponentPublicInstance { /** * By default, QToolbarTitle is set to grow to the available space. However, you can reverse that with this prop */ shrink? : boolean } export interface QTooltip extends ComponentPublicInstance { /** * One of Quasar's embedded transitions */ transitionShow? : string /** * One of Quasar's embedded transitions */ transitionHide? : string /** * Transition duration (in milliseconds, without unit) */ transitionDuration? : string | number /** * Model of the component defining shown/hidden state; Either use this property (along with a listener for 'update:model-value' event) OR use v-model directive */ modelValue? : boolean /** * The maximum height of the Tooltip; Size in CSS units, including unit name */ maxHeight? : string /** * The maximum width of the Tooltip; Size in CSS units, including unit name */ maxWidth? : string /** * Two values setting the starting position or anchor point of the Tooltip relative to its target */ anchor? : 'top left' | 'top middle' | 'top right' | 'top start' | 'top end' | 'center left' | 'center middle' | 'center right' | 'center start' | 'center end' | 'bottom left' | 'bottom middle' | 'bottom right' | 'bottom start' | 'bottom end' /** * Two values setting the Tooltip's own position relative to its target */ self? : 'top left' | 'top middle' | 'top right' | 'top start' | 'top end' | 'center left' | 'center middle' | 'center right' | 'center start' | 'center end' | 'bottom left' | 'bottom middle' | 'bottom right' | 'bottom start' | 'bottom end' /** * An array of two numbers to offset the Tooltip horizontally and vertically in pixels */ offset? : any[] /** * CSS selector or DOM element to be used as a custom scroll container instead of the auto detected one */ scrollTarget? : Element | string /** * Configure a target element to trigger Tooltip toggle; 'true' means it enables the parent DOM element, 'false' means it disables attaching events to any DOM elements; By using a String (CSS selector) it attaches the events to the specified DOM element (if it exists) */ target? : boolean | string /** * Skips attaching events to the target DOM element (that trigger the element to get shown) */ noParentEvent? : boolean /** * Configure Tooltip to appear with delay */ delay? : number /** * Configure Tooltip to disappear with delay */ hideDelay? : number /** * Triggers component to show * @param evt JS event object */ show (evt? : LooseDictionary): void /** * Triggers component to hide * @param evt JS event object */ hide (evt? : LooseDictionary): void /** * Triggers component to toggle between show/hide * @param evt JS event object */ toggle (evt? : LooseDictionary): void /** * There are some custom scenarios for which Quasar cannot automatically reposition the tooltip without significant performance drawbacks so the optimal solution is for you to call this method when you need it */ updatePosition (): void } export interface QTree extends ComponentPublicInstance { /** * The array of nodes that designates the tree structure */ nodes : any[] /** * The property name of each node object that holds a unique node id */ nodeKey : string /** * The property name of each node object that holds the label of the node */ labelKey? : string /** * The property name of each node object that holds the list of children of the node */ childrenKey? : string /** * Do not display the connector lines between nodes */ noConnectors? : boolean /** * Color name for component from the Quasar Color Palette */ color? : string /** * Color name for controls (like checkboxes) from the Quasar Color Palette */ controlColor? : string /** * Overrides text color (if needed); Color name from the Quasar Color Palette */ textColor? : string /** * Color name for selected nodes (from the Quasar Color Palette) */ selectedColor? : string /** * Notify the component that the background is a dark color */ dark? : boolean /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ icon? : string /** * The type of strategy to use for the selection of the nodes */ tickStrategy? : 'none' | 'strict' | 'leaf' | 'leaf-filtered' /** * Keys of nodes that are ticked */ ticked? : any[] /** * Keys of nodes that are expanded */ expanded? : any[] /** * Key of node currently selected */ selected? : any /** * Allow the tree to have all its branches expanded, when first rendered */ defaultExpandAll? : boolean /** * Allows the tree to be set in accordion mode */ accordion? : boolean /** * The text value to be used for filtering nodes */ filter? : string /** * The function to use to filter the tree nodes; For best performance, reference it from your scope and do not define it inline */ filterMethod? : Function /** * Toggle animation duration (in milliseconds) */ duration? : number /** * Override default such label for when no nodes are available */ noNodesLabel? : string /** * Override default such label for when no nodes are available due to filtering */ noResultsLabel? : string /** * Get the node with the given key * @param key The key of a node * @returns Requested node */ getNodeByKey (key : any): LooseDictionary /** * Get array of nodes that are ticked * @returns Ticked node objects */ getTickedNodes (): any[] /** * Get array of nodes that are expanded * @returns Expanded node objects */ getExpandedNodes (): any[] /** * Determine if a node is expanded * @param key The key of a node * @returns Is specified node expanded? */ isExpanded (key : any): boolean /** * Use to expand all branches of the tree */ expandAll (): void /** * Use to collapse all branches of the tree */ collapseAll (): void /** * Expands the tree at the point of the node with the key given * @param key The key of a node * @param state Set to 'true' to expand the branch of the tree, otherwise 'false' collapses it */ setExpanded (key : any, state : boolean): void /** * Method to check if a node's checkbox is selected or not * @param key The key of a node * @returns Is specified node ticked? */ isTicked (key : any): boolean /** * Method to set a node's checkbox programmatically * @param keys The keys of nodes to tick/untick * @param state Set to 'true' to tick the checkbox of nodes, otherwise 'false' unticks them */ setTicked (keys : any[], state : boolean): void } export interface QUploader extends ComponentPublicInstance { /** * Function which should return an Object or a Promise resolving with an Object; For best performance, reference it from your scope and do not define it inline */ factory? : Function /** * URL or path to the server which handles the upload. Takes String or factory function, which returns String. Function is called right before upload; If using a function then for best performance, reference it from your scope and do not define it inline */ url? : string | Function /** * HTTP method to use for upload; Takes String or factory function which returns a String; Function is called right before upload; If using a function then for best performance, reference it from your scope and do not define it inline */ method? : 'POST' | 'PUT' | Function /** * Field name for each file upload; This goes into the following header: 'Content-Disposition: form-data; name="__HERE__"; filename="somefile.png"; If using a function then for best performance, reference it from your scope and do not define it inline */ fieldName? : string | Function /** * Array or a factory function which returns an array; Array consists of objects with header definitions; Function is called right before upload; If using a function then for best performance, reference it from your scope and do not define it inline */ headers? : { /** * Header name */ name : string /** * Header value */ value : string }[] | Function /** * Array or a factory function which returns an array; Array consists of objects with additional fields definitions (used by Form to be uploaded); Function is called right before upload; If using a function then for best performance, reference it from your scope and do not define it inline */ formFields? : { /** * Field name */ name : string /** * Field value */ value : string }[] | Function /** * Sets withCredentials to true on the XHR that manages the upload; Takes boolean or factory function for Boolean; Function is called right before upload; If using a function then for best performance, reference it from your scope and do not define it inline */ withCredentials? : boolean | Function /** * Send raw files without wrapping into a Form(); Takes boolean or factory function for Boolean; Function is called right before upload; If using a function then for best performance, reference it from your scope and do not define it inline */ sendRaw? : boolean | Function /** * Upload files in batch (in one XHR request); Takes boolean or factory function for Boolean; Function is called right before upload; If using a function then for best performance, reference it from your scope and do not define it inline */ batch? : boolean | Function /** * Allow multiple file uploads */ multiple? : boolean /** * Comma separated list of unique file type specifiers. Maps to 'accept' attribute of native input type=file element */ accept? : string /** * Optionally, specify that a new file should be captured, and which device should be used to capture that new media of a type defined by the 'accept' prop. Maps to 'capture' attribute of native input type=file element */ capture? : 'user' | 'environment' /** * Maximum size of individual file in bytes */ maxFileSize? : number | string /** * Maximum size of all files combined in bytes */ maxTotalSize? : number | string /** * Maximum number of files to contain */ maxFiles? : number | string /** * Custom filter for added files; Only files that pass this filter will be added to the queue and uploaded; For best performance, reference it from your scope and do not define it inline */ filter? : Function /** * Label for the uploader */ label? : string /** * Color name for component from the Quasar Color Palette */ color? : string /** * Overrides text color (if needed); Color name from the Quasar Color Palette */ textColor? : string /** * Notify the component that the background is a dark color */ dark? : boolean /** * Removes border-radius so borders are squared */ square? : boolean /** * Applies a 'flat' design (no default shadow) */ flat? : boolean /** * Applies a default border to the component */ bordered? : boolean /** * Don't display thumbnails for image files */ noThumbnails? : boolean /** * Upload files immediately when added */ autoUpload? : boolean /** * Don't show the upload button */ hideUploadBtn? : boolean /** * Put component in disabled mode */ disable? : boolean /** * Put component in readonly mode */ readonly? : boolean /** * Trigger file pick; Must be called as a direct consequence of user interaction (eg. in a click handler), due to browsers security policy * @param evt JS event object */ pickFiles (evt? : LooseDictionary): void /** * Add files programmatically * @param files Array of files (instances of File) */ addFiles (files : FileList | any[]): void /** * Start uploading (same as clicking the upload button) */ upload (): void /** * Abort upload of all files (same as clicking the abort button) */ abort (): void /** * Resets uploader to default; Empties queue, aborts current uploads */ reset (): void /** * Removes already uploaded files from the list */ removeUploadedFiles (): void /** * Remove files that are waiting for upload to start (same as clicking the left clear button) */ removeQueuedFiles (): void /** * Remove specified file from the queue * @param file File to remove (instance of File) */ removeFile (file : LooseDictionary): void } export interface QUploaderAddTrigger extends ComponentPublicInstance { } export interface QVideo extends ComponentPublicInstance { /** * Aspect ratio for the content; If value is a String, then avoid using a computational statement (like '16/9') and instead specify the String value of the result directly (eg. '1.7777') */ ratio? : string | number /** * The source url to display in an iframe */ src : string } export interface QVirtualScroll extends ComponentPublicInstance { /** * Make virtual list work in horizontal mode */ virtualScrollHorizontal? : boolean /** * Minimum number of items to render in the virtual list */ virtualScrollSliceSize? : number | string /** * Ratio of number of items in visible zone to render before it */ virtualScrollSliceRatioBefore? : number | string /** * Ratio of number of items in visible zone to render after it */ virtualScrollSliceRatioAfter? : number | string /** * Default size in pixels (height if vertical, width if horizontal) of an item; This value is used for rendering the initial list; Try to use a value close to the minimum size of an item */ virtualScrollItemSize? : number | string /** * Size in pixels (height if vertical, width if horizontal) of the sticky part (if using one) at the start of the list; A correct value will improve scroll precision */ virtualScrollStickySizeStart? : number | string /** * Size in pixels (height if vertical, width if horizontal) of the sticky part (if using one) at the end of the list; A correct value will improve scroll precision */ virtualScrollStickySizeEnd? : number | string /** * The number of columns in the table (you need this if you use table-layout: fixed) */ tableColspan? : number | string /** * The type of content: list (default) or table */ type? : 'list' | 'table' /** * Available list items that will be passed to the scoped slot; For best performance freeze the list of items; Required if 'itemsFn' is not supplied */ items? : any[] /** * Number of available items in the list; Required and used only if 'itemsFn' is provided */ itemsSize? : number /** * Function to return the scope for the items to be displayed; Should return an array for items starting from 'from' index for size length; For best performance, reference it from your scope and do not define it inline */ itemsFn? : Function /** * CSS selector or DOM element to be used as a custom scroll container instead of the auto detected one */ scrollTarget? : Element | string /** * Scroll the virtual scroll list to the item with the specified index (0 based) * @param index The index of the list item (0 based) * @param edge The edge to align to if the item is not visible already (by default it aligns to end if scrolling towards the end and to start otherwise); If the '-force' version is used then it always aligns */ scrollTo (index : string | number, edge? : 'start' | 'center' | 'end' | 'start-force' | 'center-force' | 'end-force'): void /** * Resets the virtual scroll computations; Needed for custom edge-cases */ reset (): void /** * Refreshes the virtual scroll list; Use it after appending items * @param index The index of the list item to scroll to after refresh (0 based); If it's not specified the scroll position is not changed; Use a negative value to keep scroll position */ refresh (index? : string | number): void } export interface DialogChainObject { /** * Receives a Function param to tell what to do when OK is pressed / option is selected * @param callbackFn Tell what to do * @returns Chained Object */ onOk (callbackFn : Function): DialogChainObject /** * Receives a Function as param to tell what to do when Cancel is pressed / dialog is dismissed * @param callbackFn Tell what to do * @returns Chained Object */ onCancel (callbackFn : Function): DialogChainObject /** * Receives a Function param to tell what to do when the dialog is closed * @param callbackFn Tell what to do * @returns Chained Object */ onDismiss (callbackFn : Function): DialogChainObject /** * Hides the dialog when called * @returns Chained Object */ hide (): DialogChainObject /** * Updates the initial properties (given as create() param) except for 'component' * @param opts Props (except 'component') which will overwrite the initial create() params; If create() was invoked with a custom dialog component then this param should contain the new componentProps * @returns Chained Object */ update (opts? : LooseDictionary): DialogChainObject } import { CookiesGetMethodType } from './api' export interface QDialogOptions { /** * CSS Class name to apply to the Dialog's QCard */ class? : string | any[] | LooseDictionary /** * CSS style to apply to the Dialog's QCard */ style? : string | any[] | LooseDictionary /** * A text for the heading title of the dialog */ title? : string /** * A text with more information about what needs to be input, selected or confirmed. */ message? : string /** * Render title and message as HTML; This can lead to XSS attacks, so make sure that you sanitize the message first */ html? : boolean /** * Position of the Dialog on screen. Standard is centered. */ position? : 'top' | 'right' | 'bottom' | 'left' | 'standard' /** * An object definition of the input field for the prompting question. */ prompt? : { /** * The initial value of the input */ model : string /** * Optional property to determine the input field type */ type? : string /** * Is typed content valid? */ isValid? : Function /** * Attributes to pass to prompt control */ attrs? : LooseDictionary /** * A text label that will “float” up above the input field, once the field gets focus */ label? : string /** * Label will be always shown above the field regardless of field content (if any) */ stackLabel? : boolean /** * Use 'filled' design for the field */ filled? : boolean /** * Use 'outlined' design for the field */ outlined? : boolean /** * Use 'standout' design for the field; Specifies classes to be applied when focused (overriding default ones) */ standout? : boolean | string /** * Applies a small standard border-radius for a squared shape of the component */ rounded? : boolean /** * Remove border-radius so borders are squared; Overrides 'rounded' prop */ square? : boolean /** * Show an automatic counter on bottom right */ counter? : boolean /** * Specify a max length of model */ maxlength? : string | number /** * Prefix */ prefix? : string /** * Suffix */ suffix? : string } /** * An object definition for creating the selection form content */ options? : { /** * The value of the selection (String if it's of type radio or Array otherwise) */ model : string | any[] /** * The type of selection */ type? : 'radio' | 'checkbox' | 'toggle' /** * The list of options to interact with; Equivalent to options prop of the QOptionsGroup component */ items? : any[] /** * Is the model valid? */ isValid? : Function } /** * Display a Quasar spinner (if value is true, then the defaults are used); Useful for conveying the idea that something is happening behind the covers; Tip: use along with persistent, ok: false and update() method */ progress? : boolean | { /** * One of the QSpinners */ spinner? : Component /** * Color name for component from the Quasar Color Palette */ color? : string } /** * Props for an 'OK' button */ ok? : string | { [index: string]: any } | boolean /** * Props for a 'CANCEL' button */ cancel? : string | { [index: string]: any } | boolean /** * What button to focus, unless you also have 'prompt' or 'options' */ focus? : 'ok' | 'cancel' | 'none' /** * Makes buttons be stacked instead of vertically aligned */ stackButtons? : boolean /** * Color name for component from the Quasar Color Palette */ color? : string /** * Apply dark mode */ dark? : boolean /** * User cannot dismiss Dialog if clicking outside of it or hitting ESC key; Also, an app route change won't dismiss it */ persistent? : boolean /** * User cannot dismiss Dialog by hitting ESC key; No need to set it if 'persistent' prop is also set */ noEscDismiss? : boolean /** * User cannot dismiss Dialog by clicking outside of it; No need to set it if 'persistent' prop is also set */ noBackdropDismiss? : boolean /** * Changing route app won't dismiss Dialog; No need to set it if 'persistent' prop is also set */ noRouteDismiss? : boolean /** * Put Dialog into seamless mode; Does not use a backdrop so user is able to interact with the rest of the page too */ seamless? : boolean /** * Put Dialog into maximized mode */ maximized? : boolean /** * Dialog will try to render with same width as the window */ fullWidth? : boolean /** * Dialog will try to render with same height as the window */ fullHeight? : boolean /** * One of Quasar's embedded transitions */ transitionShow? : string /** * One of Quasar's embedded transitions */ transitionHide? : string /** * Use custom dialog component; use along with 'componentProps' prop where possible */ component? : any /** * User defined props which will be forwarded to underlying custom component if 'component' prop is used */ componentProps? : LooseDictionary } import { WebStorageGetItemMethodType } from './api' import { WebStorageGetIndexMethodType } from './api' import { WebStorageGetKeyMethodType } from './api' import { WebStorageGetAllKeysMethodType } from './api' import { QVueGlobals, QSingletonGlobals } from "./globals"; declare module "./globals" { export interface QVueGlobals { addressbarColor: AddressbarColor fullscreen: AppFullscreen /** * Does the app have user focus? Or the app runs in the background / another tab has the user's attention */ appVisible : boolean /** * Creates an ad-hoc Bottom Sheet; Same as calling $q.bottomSheet(...) * @param opts Bottom Sheet options * @returns Chainable Object */ bottomSheet (opts : { /** * CSS Class name to apply to the Dialog's QCard */ class? : string | any[] | LooseDictionary /** * CSS style to apply to the Dialog's QCard */ style? : string | any[] | LooseDictionary /** * Title */ title? : string /** * Message */ message? : string /** * Array of Objects, each Object defining an action */ actions? : { /** * CSS classes for this action */ classes? : string | any[] | LooseDictionary /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ icon? : string /** * Path to an image for this action */ img? : string /** * Display img as avatar (round borders) */ avatar? : boolean /** * Action label */ label? : string | number }[] /** * Display actions as a grid instead of as a list */ grid? : boolean /** * Apply dark mode */ dark? : boolean /** * Put Bottom Sheet into seamless mode; Does not use a backdrop so user is able to interact with the rest of the page too */ seamless? : boolean /** * User cannot dismiss Bottom Sheet if clicking outside of it or hitting ESC key */ persistent? : boolean }): DialogChainObject cookies: Cookies dark: Dark /** * Creates an ad-hoc Dialog; Same as calling $q.dialog(...) * @param opts Dialog options * @returns Chainable Object */ dialog (opts : QDialogOptions): DialogChainObject loading: Loading loadingBar: LoadingBar localStorage: LocalStorage /** * Creates a notification; Same as calling $q.notify(...) * @param opts Notification options * @returns Calling this function with no parameters hides the notification; When called with one Object parameter (the original notification must NOT be grouped), it updates the notification (specified properties are shallow merged with previous ones; note that group and position cannot be changed while updating and so they are ignored) */ notify (opts : { /** * Optional type (that has been previously registered) or one of the out of the box ones ('positive', 'negative', 'warning', 'info', 'ongoing') */ type? : string /** * Color name for component from the Quasar Color Palette */ color? : string /** * Color name for component from the Quasar Color Palette */ textColor? : string /** * The content of your message */ message? : string /** * The content of your optional caption */ caption? : string /** * Render message as HTML; This can lead to XSS attacks, so make sure that you sanitize the message first */ html? : boolean /** * Icon name following Quasar convention; Make sure you have the icon library installed unless you are using 'img:' prefix */ icon? : string /** * URL to an avatar/image; Suggestion: use statics folder */ avatar? : string /** * Useful for notifications that are updated; Displays a Quasar spinner instead of an avatar or icon; If value is Boolean 'true' then the default QSpinner is shown */ spinner? : boolean | Component /** * Window side/corner to stick to */ position? : 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' | 'top' | 'bottom' | 'left' | 'right' | 'center' /** * Override the auto generated group with custom one; Grouped notifications cannot be updated; String or number value inform this is part of a specific group, regardless of its options; When a new notification is triggered with same group name, it replaces the old one and shows a badge with how many times the notification was triggered */ group? : boolean | string | number /** * Color name for the badge from the Quasar Color Palette */ badgeColor? : string /** * Color name for the badge text from the Quasar Color Palette */ badgeTextColor? : string /** * Notification corner to stick badge to; If notification is on the left side then default is top-right otherwise it is top-left */ badgePosition? : 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' /** * Style definitions to be attributed to the badge */ badgeStyle? : any[] | string | LooseDictionary /** * Class definitions to be attributed to the badge */ badgeClass? : any[] | string | LooseDictionary /** * Show progress bar to detail when notification will disappear automatically (unless timeout is 0) */ progress? : boolean /** * Class definitions to be attributed to the progress bar */ progressClass? : any[] | string | LooseDictionary /** * Add CSS class(es) to the notification for easier customization */ classes? : string /** * Key-value for attributes to be set on the notification */ attrs? : LooseDictionary /** * Amount of time to display (in milliseconds) */ timeout? : number /** * Notification actions (buttons); If a 'handler' is specified or not, clicking/tapping on the button will also close the notification; Also check 'closeBtn' convenience prop */ actions? : any[] /** * Function to call when notification gets dismissed */ onDismiss? : Function /** * Convenience way to add a dismiss button with a specific label, without using the 'actions' prop; If set to true, it uses a label accordding to the current Quasar language */ closeBtn? : boolean | string /** * Put notification into multi-line mode; If this prop isn't used and more than one 'action' is specified then notification goes into multi-line mode by default */ multiLine? : boolean /** * Ignore the default configuration (set by setDefaults()) for this instance only */ ignoreDefaults? : boolean } | string): Function platform: Platform screen: Screen sessionStorage: SessionStorage } } declare module '@vue/runtime-core' { interface ComponentCustomProperties { $q: QVueGlobals } } import { GlobalQuasarLanguage, GlobalQuasarIconSet } from './globals' export interface QuasarPluginOptions { lang: GlobalQuasarLanguage, config: any, iconSet: GlobalQuasarIconSet, components: { QAjaxBar?: ComponentOptions QAvatar?: ComponentOptions QBadge?: ComponentOptions QBanner?: ComponentOptions QBar?: ComponentOptions QBreadcrumbs?: ComponentOptions QBreadcrumbsEl?: ComponentOptions QBtnDropdown?: ComponentOptions QBtnGroup?: ComponentOptions QBtnToggle?: ComponentOptions QBtn?: ComponentOptions QCard?: ComponentOptions QCardActions?: ComponentOptions QCardSection?: ComponentOptions QCarousel?: ComponentOptions QCarouselControl?: ComponentOptions QCarouselSlide?: ComponentOptions QChatMessage?: ComponentOptions QCheckbox?: ComponentOptions QChip?: ComponentOptions QCircularProgress?: ComponentOptions QColor?: ComponentOptions QDate?: ComponentOptions QDialog?: ComponentOptions QDrawer?: ComponentOptions QEditor?: ComponentOptions QExpansionItem?: ComponentOptions QFab?: ComponentOptions QFabAction?: ComponentOptions QField?: ComponentOptions QFile?: ComponentOptions QFooter?: ComponentOptions QForm?: ComponentOptions QFormChildMixin?: ComponentOptions QHeader?: ComponentOptions QIcon?: ComponentOptions QImg?: ComponentOptions QInfiniteScroll?: ComponentOptions QInnerLoading?: ComponentOptions QInput?: ComponentOptions QIntersection?: ComponentOptions QItem?: ComponentOptions QItemLabel?: ComponentOptions QItemSection?: ComponentOptions QList?: ComponentOptions QKnob?: ComponentOptions QLayout?: ComponentOptions QLinearProgress?: ComponentOptions QMarkupTable?: ComponentOptions QMenu?: ComponentOptions QNoSsr?: ComponentOptions QOptionGroup?: ComponentOptions QPageScroller?: ComponentOptions QPageSticky?: ComponentOptions QPage?: ComponentOptions QPageContainer?: ComponentOptions QPagination?: ComponentOptions QParallax?: ComponentOptions QPopupEdit?: ComponentOptions QPopupProxy?: ComponentOptions QPullToRefresh?: ComponentOptions QRadio?: ComponentOptions QRange?: ComponentOptions QRating?: ComponentOptions QResizeObserver?: ComponentOptions QResponsive?: ComponentOptions QScrollArea?: ComponentOptions QScrollObserver?: ComponentOptions QSelect?: ComponentOptions QSeparator?: ComponentOptions QSkeleton?: ComponentOptions QSlideItem?: ComponentOptions QSlideTransition?: ComponentOptions QSlider?: ComponentOptions QSpace?: ComponentOptions QSpinner?: ComponentOptions QSpinnerAudio?: ComponentOptions QSpinnerBall?: ComponentOptions QSpinnerBars?: ComponentOptions QSpinnerBox?: ComponentOptions QSpinnerClock?: ComponentOptions QSpinnerComment?: ComponentOptions QSpinnerCube?: ComponentOptions QSpinnerDots?: ComponentOptions QSpinnerFacebook?: ComponentOptions QSpinnerGears?: ComponentOptions QSpinnerGrid?: ComponentOptions QSpinnerHearts?: ComponentOptions QSpinnerHourglass?: ComponentOptions QSpinnerInfinity?: ComponentOptions QSpinnerIos?: ComponentOptions QSpinnerOrbit?: ComponentOptions QSpinnerOval?: ComponentOptions QSpinnerPie?: ComponentOptions QSpinnerPuff?: ComponentOptions QSpinnerRadio?: ComponentOptions QSpinnerRings?: ComponentOptions QSpinnerTail?: ComponentOptions QSplitter?: ComponentOptions QStep?: ComponentOptions QStepper?: ComponentOptions QStepperNavigation?: ComponentOptions QTabPanel?: ComponentOptions QTabPanels?: ComponentOptions QTable?: ComponentOptions QTd?: ComponentOptions QTh?: ComponentOptions QTr?: ComponentOptions QRouteTab?: ComponentOptions QTab?: ComponentOptions QTabs?: ComponentOptions QTime?: ComponentOptions QTimeline?: ComponentOptions QTimelineEntry?: ComponentOptions QToggle?: ComponentOptions QToolbar?: ComponentOptions QToolbarTitle?: ComponentOptions QTooltip?: ComponentOptions QTree?: ComponentOptions QUploader?: ComponentOptions QUploaderAddTrigger?: ComponentOptions QVideo?: ComponentOptions QVirtualScroll?: ComponentOptions }, directives: { ClosePopup?: ClosePopup Intersection?: Intersection Morph?: Morph Mutation?: Mutation Ripple?: Ripple Scroll?: Scroll ScrollFire?: ScrollFire TouchHold?: TouchHold TouchPan?: TouchPan TouchRepeat?: TouchRepeat TouchSwipe?: TouchSwipe }, plugins: { AddressbarColor?: AddressbarColor AppFullscreen?: AppFullscreen AppVisibility?: AppVisibility BottomSheet?: BottomSheet Cookies?: Cookies Dark?: Dark Dialog?: Dialog Loading?: Loading LoadingBar?: LoadingBar LocalStorage?: LocalStorage Meta?: Meta Notify?: Notify Platform?: Platform Screen?: Screen SessionStorage?: SessionStorage } } import './lang' declare module './lang' { export interface QuasarLanguageCodesHolder { 'ar': true 'az-Latn': true 'bg': true 'ca': true 'cs': true 'da': true 'de': true 'el': true 'en-GB': true 'en-US': true 'eo': true 'es': true 'et': true 'fa-IR': true 'fa': true 'fi': true 'fr': true 'gn': true 'he': true 'hr': true 'hu': true 'id': true 'is': true 'it': true 'ja': true 'km': true 'ko-KR': true 'kur-CKB': true 'lu': true 'lv': true 'ml': true 'ms': true 'nb-NO': true 'nl': true 'pl': true 'pt-BR': true 'pt': true 'ro': true 'ru': true 'sk': true 'sl': true 'sr': true 'sv': true 'ta': true 'th': true 'tr': true 'ug': true 'uk': true 'vi': true 'zh-CN': true 'zh-TW': true } } export as namespace quasar export * from './ts-helpers' export * from './utils' export * from './composables' export * from './feature-flag' export * from './globals' export * from './extras' export * from './lang' export * from './api' export const AddressbarColor: AddressbarColor export const AppFullscreen: AppFullscreen export const AppVisibility: AppVisibility export const BottomSheet: BottomSheet export const Cookies: Cookies export const Dark: Dark export const Dialog: Dialog export const Loading: Loading export const LoadingBar: LoadingBar export const LocalStorage: LocalStorage export const Meta: Meta export const Notify: Notify export const Platform: Platform export const Screen: Screen export const SessionStorage: SessionStorage export const ClosePopup: ClosePopup export const Intersection: Intersection export const Morph: Morph export const Mutation: Mutation export const Ripple: Ripple export const Scroll: Scroll export const ScrollFire: ScrollFire export const TouchHold: TouchHold export const TouchPan: TouchPan export const TouchRepeat: TouchRepeat export const TouchSwipe: TouchSwipe export const QAjaxBar: ComponentOptions export const QAvatar: ComponentOptions export const QBadge: ComponentOptions export const QBanner: ComponentOptions export const QBar: ComponentOptions export const QBreadcrumbs: ComponentOptions export const QBreadcrumbsEl: ComponentOptions export const QBtnDropdown: ComponentOptions export const QBtnGroup: ComponentOptions export const QBtnToggle: ComponentOptions export const QBtn: ComponentOptions export const QCard: ComponentOptions export const QCardActions: ComponentOptions export const QCardSection: ComponentOptions export const QCarousel: ComponentOptions export const QCarouselControl: ComponentOptions export const QCarouselSlide: ComponentOptions export const QChatMessage: ComponentOptions export const QCheckbox: ComponentOptions export const QChip: ComponentOptions export const QCircularProgress: ComponentOptions export const QColor: ComponentOptions export const QDate: ComponentOptions export const QDialog: ComponentOptions export const QDrawer: ComponentOptions export const QEditor: ComponentOptions export const QExpansionItem: ComponentOptions export const QFab: ComponentOptions export const QFabAction: ComponentOptions export const QField: ComponentOptions export const QFile: ComponentOptions export const QFooter: ComponentOptions export const QForm: ComponentOptions export const QFormChildMixin: ComponentOptions export const QHeader: ComponentOptions export const QIcon: ComponentOptions export const QImg: ComponentOptions export const QInfiniteScroll: ComponentOptions export const QInnerLoading: ComponentOptions export const QInput: ComponentOptions export const QIntersection: ComponentOptions export const QItem: ComponentOptions export const QItemLabel: ComponentOptions export const QItemSection: ComponentOptions export const QList: ComponentOptions export const QKnob: ComponentOptions export const QLayout: ComponentOptions export const QLinearProgress: ComponentOptions export const QMarkupTable: ComponentOptions export const QMenu: ComponentOptions export const QNoSsr: ComponentOptions export const QOptionGroup: ComponentOptions export const QPageScroller: ComponentOptions export const QPageSticky: ComponentOptions export const QPage: ComponentOptions export const QPageContainer: ComponentOptions export const QPagination: ComponentOptions export const QParallax: ComponentOptions export const QPopupEdit: ComponentOptions export const QPopupProxy: ComponentOptions export const QPullToRefresh: ComponentOptions export const QRadio: ComponentOptions export const QRange: ComponentOptions export const QRating: ComponentOptions export const QResizeObserver: ComponentOptions export const QResponsive: ComponentOptions export const QScrollArea: ComponentOptions export const QScrollObserver: ComponentOptions export const QSelect: ComponentOptions export const QSeparator: ComponentOptions export const QSkeleton: ComponentOptions export const QSlideItem: ComponentOptions export const QSlideTransition: ComponentOptions export const QSlider: ComponentOptions export const QSpace: ComponentOptions export const QSpinner: ComponentOptions export const QSpinnerAudio: ComponentOptions export const QSpinnerBall: ComponentOptions export const QSpinnerBars: ComponentOptions export const QSpinnerBox: ComponentOptions export const QSpinnerClock: ComponentOptions export const QSpinnerComment: ComponentOptions export const QSpinnerCube: ComponentOptions export const QSpinnerDots: ComponentOptions export const QSpinnerFacebook: ComponentOptions export const QSpinnerGears: ComponentOptions export const QSpinnerGrid: ComponentOptions export const QSpinnerHearts: ComponentOptions export const QSpinnerHourglass: ComponentOptions export const QSpinnerInfinity: ComponentOptions export const QSpinnerIos: ComponentOptions export const QSpinnerOrbit: ComponentOptions export const QSpinnerOval: ComponentOptions export const QSpinnerPie: ComponentOptions export const QSpinnerPuff: ComponentOptions export const QSpinnerRadio: ComponentOptions export const QSpinnerRings: ComponentOptions export const QSpinnerTail: ComponentOptions export const QSplitter: ComponentOptions export const QStep: ComponentOptions export const QStepper: ComponentOptions export const QStepperNavigation: ComponentOptions export const QTabPanel: ComponentOptions export const QTabPanels: ComponentOptions export const QTable: ComponentOptions export const QTd: ComponentOptions export const QTh: ComponentOptions export const QTr: ComponentOptions export const QRouteTab: ComponentOptions export const QTab: ComponentOptions export const QTabs: ComponentOptions export const QTime: ComponentOptions export const QTimeline: ComponentOptions export const QTimelineEntry: ComponentOptions export const QToggle: ComponentOptions export const QToolbar: ComponentOptions export const QToolbarTitle: ComponentOptions export const QTooltip: ComponentOptions export const QTree: ComponentOptions export const QUploader: ComponentOptions export const QUploaderAddTrigger: ComponentOptions export const QVideo: ComponentOptions export const QVirtualScroll: ComponentOptions export const Quasar: { install: (app: App, options: Partial<QuasarPluginOptions>) => any } & QSingletonGlobals export default Quasar import './shim-icon-set' import './shim-lang'
the_stack
import TimerBox from '../../../resources/timerbox'; import { JobDetail } from '../../../types/event'; import { ResourceBox } from '../bars'; import { kAbility, patch5xEffectId } from '../constants'; import { PartialFieldMatches } from '../event_emitter'; import { computeBackgroundColorFrom } from '../utils'; import { BaseComponent, ComponentInterface } from './base'; export class SMNComponent extends BaseComponent { aetherflowStackBox: ResourceBox; demiSummoningBox: ResourceBox; energyDrainBox: TimerBox; tranceBox: TimerBox; lucidBox: TimerBox; rubyStacks: HTMLDivElement[]; topazStacks: HTMLDivElement[]; emeraldStacks: HTMLDivElement[]; constructor(o: ComponentInterface) { super(o); // Resource box this.demiSummoningBox = this.bars.addResourceBox({ classList: ['smn-color-demisummon'], }); this.aetherflowStackBox = this.bars.addResourceBox({ classList: ['smn-color-aetherflow'], }); // Proc box this.energyDrainBox = this.bars.addProcBox({ id: 'smn-procs-energydrain', fgColor: 'smn-color-energydrain', }); this.tranceBox = this.bars.addProcBox({ id: 'smn-procs-trance', fgColor: 'smn-color-trance', }); this.lucidBox = this.bars.addProcBox({ id: 'smn-procs-lucid', fgColor: 'smn-color-lucid', }); // Arcanum and Attunement Guage const stacksContainer = document.createElement('div'); stacksContainer.id = 'smn-stacks'; stacksContainer.classList.add('stacks'); this.bars.addJobBarContainer().appendChild(stacksContainer); const rubyStacksContainer = document.createElement('div'); rubyStacksContainer.id = 'smn-stacks-ruby'; stacksContainer.appendChild(rubyStacksContainer); const topazStacksContainer = document.createElement('div'); topazStacksContainer.id = 'smn-stacks-topaz'; stacksContainer.appendChild(topazStacksContainer); const emeraldStacksContainer = document.createElement('div'); emeraldStacksContainer.id = 'smn-stacks-emerald'; stacksContainer.appendChild(emeraldStacksContainer); this.rubyStacks = []; this.topazStacks = []; this.emeraldStacks = []; for (let i = 0; i < 2; i++) { const rubyStack = document.createElement('div'); rubyStacksContainer.appendChild(rubyStack); this.rubyStacks.push(rubyStack); } for (let i = 0; i < 4; i++) { const topazStack = document.createElement('div'); topazStacksContainer.appendChild(topazStack); this.topazStacks.push(topazStack); } for (let i = 0; i < 4; i++) { const emeraldStack = document.createElement('div'); emeraldStacksContainer.appendChild(emeraldStack); this.emeraldStacks.push(emeraldStack); } this.reset(); } private _addActiveOnStacks(elements: HTMLDivElement[], stacks: number) { for (let i = 0; i < elements.length; i++) elements[i]?.classList.toggle('active', i < stacks); } override onJobDetailUpdate(jobDetail: JobDetail['SMN']): void { // assert this is running on a 6.x server if (('bahamutStance' in jobDetail)) return; // Aetherflow Guage const stack = jobDetail.aetherflowStacks; this.aetherflowStackBox.innerText = stack.toString(); // Demi-summoning Guage const time = Math.ceil( Math.max(jobDetail.tranceMilliseconds, jobDetail.attunementMilliseconds ) / 1000); this.demiSummoningBox.innerText = ''; if (time > 0) this.demiSummoningBox.innerText = time.toString(); this.demiSummoningBox.parentNode.classList.toggle('bahamutready', jobDetail.nextSummoned === 'Bahamut'); this.demiSummoningBox.parentNode.classList.toggle('firebirdready', jobDetail.nextSummoned === 'Phoenix'); this.demiSummoningBox.parentNode.classList.toggle('garuda', jobDetail.activePrimal === 'Garuda'); this.demiSummoningBox.parentNode.classList.toggle('titan', jobDetail.activePrimal === 'Titan'); this.demiSummoningBox.parentNode.classList.toggle('ifrit', jobDetail.activePrimal === 'Ifrit'); this.tranceBox.fg = computeBackgroundColorFrom(this.tranceBox, 'smn-color-trance'); if (jobDetail.nextSummoned === 'Phoenix') this.tranceBox.fg = computeBackgroundColorFrom(this.tranceBox, 'smn-color-demisummon.firebirdready'); // Arcanum and Attunement Guage this._addActiveOnStacks(this.rubyStacks, (jobDetail.activePrimal === 'Ifrit') ? jobDetail.attunement : (jobDetail.usableArcanum.includes('Ruby') ? 2 : 0)); this._addActiveOnStacks(this.topazStacks, (jobDetail.activePrimal === 'Titan') ? jobDetail.attunement : (jobDetail.usableArcanum.includes('Topaz') ? 4 : 0)); this._addActiveOnStacks(this.emeraldStacks, (jobDetail.activePrimal === 'Garuda') ? jobDetail.attunement : (jobDetail.usableArcanum.includes('Emerald') ? 4 : 0)); // dynamically change threshold of tranceBox, let user know you should use arcanum quickly this.tranceBox.threshold = this.player.gcdSpell * (jobDetail.usableArcanum.length * 3 + 1); } override onUseAbility(id: string): void { switch (id) { case kAbility.EnergyDrain: case kAbility.EnergySiphon: this.energyDrainBox.duration = 60; break; case kAbility.SummonBahamut: case kAbility.SummonPhoenix: this.tranceBox.duration = this.bars.player.getActionCooldown(60000, 'spell'); break; case kAbility.LucidDreaming: this.lucidBox.duration = 60; break; } } override onStatChange({ gcdSpell }: { gcdSpell: number }): void { this.energyDrainBox.valuescale = gcdSpell; this.energyDrainBox.threshold = gcdSpell + 1; this.tranceBox.valuescale = gcdSpell; this.lucidBox.valuescale = gcdSpell; this.lucidBox.threshold = gcdSpell + 1; } override reset(): void { this.energyDrainBox.duration = 0; this.tranceBox.duration = 0; this.lucidBox.duration = 0; this.tranceBox.fg = computeBackgroundColorFrom(this.tranceBox, 'smn-color-trance'); } } export class SMN5xComponent extends BaseComponent { aetherflowStackBox: ResourceBox; demiSummoningBox: ResourceBox; miasmaBox: TimerBox; bioSmnBox: TimerBox; energyDrainBox: TimerBox; tranceBox: TimerBox; furtherRuin = 0; ruin4Stacks: HTMLElement[] = []; constructor(o: ComponentInterface) { super(o); this.aetherflowStackBox = this.bars.addResourceBox({ classList: ['smn-color-aetherflow'], }); this.demiSummoningBox = this.bars.addResourceBox({ classList: ['smn-color-demisummon'], }); this.miasmaBox = this.bars.addProcBox({ id: 'smn-procs-miasma', fgColor: 'smn-color-miasma', notifyWhenExpired: true, }); this.bioSmnBox = this.bars.addProcBox({ id: 'smn-procs-biosmn', fgColor: 'smn-color-biosmn', notifyWhenExpired: true, }); this.energyDrainBox = this.bars.addProcBox({ id: 'smn-procs-energydrain', fgColor: 'smn-color-energydrain', }); this.tranceBox = this.bars.addProcBox({ id: 'smn-procs-trance', fgColor: 'smn-color-trance', }); // FurtherRuin Stack Gauge const stacksContainer = document.createElement('div'); stacksContainer.id = 'smn-stacks'; this.bars.addJobBarContainer().appendChild(stacksContainer); const ruin4Container = document.createElement('div'); ruin4Container.id = 'smn-stacks-ruin4'; stacksContainer.appendChild(ruin4Container); for (let i = 0; i < 4; ++i) { const d = document.createElement('div'); ruin4Container.appendChild(d); this.ruin4Stacks.push(d); } this.reset(); } refreshFurtherRuin(): void { for (let i = 0; i < 4; ++i) { if (this.furtherRuin > i) this.ruin4Stacks[i]?.classList.add('active'); else this.ruin4Stacks[i]?.classList.remove('active'); } } override onYouGainEffect(id: string, matches: PartialFieldMatches<'GainsEffect'>): void { if (id === patch5xEffectId.FurtherRuin5x) { this.furtherRuin = parseInt(matches.count ?? '0'); this.refreshFurtherRuin(); } } override onYouLoseEffect(id: string): void { if (id === patch5xEffectId.FurtherRuin5x) { this.furtherRuin = 0; this.refreshFurtherRuin(); } } onZoneChange(): void { this.furtherRuin = 0; this.refreshFurtherRuin(); } override onJobDetailUpdate(jobDetail: JobDetail['SMN']): void { // assert this is running on a 5.x server (i.e. CN/KR) if (!('bahamutStance' in jobDetail)) return; const stack = jobDetail.aetherflowStacks; const summoned = jobDetail.bahamutSummoned; const time = Math.ceil(jobDetail.stanceMilliseconds / 1000); // turn red when you have too much stacks before EnergyDrain ready. this.aetherflowStackBox.innerText = stack.toString(); const s = this.energyDrainBox.duration ?? 0 - this.energyDrainBox.elapsed; if ((stack === 2) && (s <= 8)) this.aetherflowStackBox.parentNode.classList.add('too-much-stacks'); else this.aetherflowStackBox.parentNode.classList.remove('too-much-stacks'); // Show time remain when summoning/trancing. // Turn blue when buhamut ready, and turn orange when firebird ready. // Also change tranceBox color. this.demiSummoningBox.innerText = ''; this.demiSummoningBox.parentNode.classList.remove('bahamutready', 'firebirdready'); this.tranceBox.fg = computeBackgroundColorFrom(this.tranceBox, 'smn-color-trance'); if (time > 0) { this.demiSummoningBox.innerText = time.toString(); } else if (jobDetail.dreadwyrmStacks === 2) { this.demiSummoningBox.parentNode.classList.add('bahamutready'); } else if (jobDetail.phoenixReady) { this.demiSummoningBox.parentNode.classList.add('firebirdready'); this.tranceBox.fg = computeBackgroundColorFrom(this.tranceBox, 'smn-color-demisummon.firebirdready'); } // Turn red when only 7s summoning time remain, to alarm that cast the second Enkindle. // Also alarm that don't cast a spell that has cast time, or a WW/SF will be missed. // Turn red when only 2s trancing time remain, to alarm that cast deathflare. if (time <= 7 && summoned === 1) this.demiSummoningBox.parentNode.classList.add('last'); else if (time > 0 && time <= 2 && summoned === 0) this.demiSummoningBox.parentNode.classList.add('last'); else this.demiSummoningBox.parentNode.classList.remove('last'); } override onUseAbility(id: string): void { switch (id) { case kAbility.Miasma: case kAbility.Miasma3: this.miasmaBox.duration = 30; break; case kAbility.BioSmn: case kAbility.BioSmn2: case kAbility.Bio3: this.bioSmnBox.duration = 30; break; case kAbility.Tridisaster: // Tridisaster refresh miasma and bio both, so repeat below. // TODO: remake onXxx like node's EventEmitter this.miasmaBox.duration = 30; this.bioSmnBox.duration = 30; break; case kAbility.EnergyDrain: case kAbility.EnergySiphon: this.energyDrainBox.duration = 30; this.aetherflowStackBox.parentNode.classList.remove('too-much-stacks'); break; case kAbility.DreadwyrmTrance: case kAbility.FirebirdTrance: // Trance cooldown is 55s, // but wait till 60s will be better on matching raidbuffs. // Threshold will be used to tell real cooldown. this.tranceBox.duration = 60; break; } } override onStatChange({ gcdSpell }: { gcdSpell: number }): void { this.miasmaBox.valuescale = gcdSpell; this.miasmaBox.threshold = gcdSpell + 1; this.bioSmnBox.valuescale = gcdSpell; this.bioSmnBox.threshold = gcdSpell + 1; this.energyDrainBox.valuescale = gcdSpell; this.energyDrainBox.threshold = gcdSpell + 1; this.tranceBox.valuescale = gcdSpell; this.tranceBox.threshold = gcdSpell + 7; } override reset(): void { this.furtherRuin = 0; this.refreshFurtherRuin(); this.miasmaBox.duration = 0; this.bioSmnBox.duration = 0; this.energyDrainBox.duration = 0; this.tranceBox.duration = 0; } }
the_stack
import { strict as assert } from "assert"; import { ZonedDateTime, ZoneOffset } from "@js-joda/core"; import { LogSeriesOpts, LogSeriesFragment, LogSample, LogSeriesFetchAndValidateOpts, LogSeriesFragmentStats } from "./logs"; import { MetricSeriesOpts, MetricSeriesFragment, MetricSample, MetricSeriesFetchAndValidateOpts, MetricSeriesFragmentStats } from "./metrics"; import { log } from "./log"; export interface LabelSet { [key: string]: string; } export interface WalltimeCouplingOptions { maxLagSeconds: number; minLagSeconds: number; } export interface FragmentStatsBase { // Use BigInt to stress that this is never fractional -- worry about perf // later. sampleCount: bigint; } export abstract class SampleBase<ValueType, TimeType> { public value: ValueType; public time: TimeType; constructor(value: ValueType, time: TimeType) { this.value = value; this.time = time; } } export abstract class FragmentBase<SampleType, ParentType> { /** The label set defining the time series this fragment is part of. */ public labels: LabelSet; /** The individual samples in this time series fragment */ protected samples: Array<SampleType>; /** Sequential number for locating fragment in the time series. Set by caller. */ public index: number; /** The time series that this fragment is part of (the "parent"). */ public parent: ParentType | undefined; /** * An object representing the samples in this fragment -- is built upon * serialization, i.e. when this.serialized is `true` -- in the * implementation, make sure this is built once and not changed afterwards */ public stats: LogSeriesFragmentStats | MetricSeriesFragmentStats | undefined; /** * For internal book-keeping: is this 'closed' (has been serialized, no more * samples can be added) or can samples still be added? */ protected serialized: boolean; /** * Return number of payload bytes in this fragment. * * For a Prometheus metric sample, that's a double precision float (8 bytes) * for sample value, and an int64 per sample timestamp, i.e. 16 bytes per * sample. * * For a Loki log sample, that's a protobuf timestamp (int64 + int32) per * sample (12 bytes), and the size of the sample value text encoded as UTF-8. */ abstract payloadByteCount(): bigint; constructor( labels: LabelSet, index = 0, parentSeries: ParentType | undefined = undefined ) { this.labels = labels; this.samples = new Array<SampleType>(); this.index = index; this.parent = parentSeries; this.serialized = false; } /** * Return shallow copy so that mutation of the returned array does not have * side effects in here. However, if individual samples were to be mutated * this would take effect here, too.*/ public getSamples(): Array<SampleType> { return [...this.samples]; } /** * Return the current number of samples in this fragment. * Type `bigint` to stress that this is never fractional. */ public sampleCount(): bigint { // This might not be well thought through, but when the `stats` property is // populated then this fragment is "closed" (no more sampled should/can be // added) and the actual data might be gone (consolidate this thinking!). if (this.stats !== undefined) { return this.stats.sampleCount; } return BigInt(this.samples.length); } /** Return stringified and zero-padded index. */ public indexString(length: number): string { const is: string = this.index.toString(); return is.padStart(length, "0"); } public addSample(s: SampleType): void { if (this.serialized) { throw new Error("cannot mutate fragment anymore"); } this.samples.push(s); // I hope the compiler after all removes all overhead when it sees that // `addSampleHook()` is a noop. this.addSampleHook(s); } /** * Use this to indicate that this fragment was serialized (into a binary * msg) out-of-band, i..e not with the `serialize()` method. */ public setSerialized(): void { this.serialized = true; } /** * Can be used in the child to execute custom functionality when adding a * sample. */ protected abstract addSampleHook(s: SampleType): void; } export abstract class TimeseriesBase<FragmentType> { /** The label set (set of key/value pairs) which uniquely defines this time * series*/ protected labels: LabelSet; /** The start time of this synthetic time series (note(jp): does first sample * have this value? might depend on log vs. metrics implementation) */ protected starttime: ZonedDateTime; /** The set of options configuring this time series -- serialized into a * string */ protected optionstring: string; /** The number of fragments consumed from this time series -- for * book-keeping purposes. */ protected nFragmentsConsumed: number; /** For keeing track of how many entries were validated (from the start of the *stream). Used by fetchAndValidate(). */ protected nSamplesValidatedSoFar: bigint; /** * Configure 'walltime coupling' where the synthetic time source is loosely * coupled to the wall time. * * `undefined`: disable this mechanism. can fall back into the past * arbitrarily far, and go into the future arbitrarily far. Not expected to * work for metrics (cortex, blocks storage) -- may work for logs (loki, also * see reject_old_samples option and discussion in * https://github.com/opstrace/opstrace/pull/1140#discussion_r679837228) */ protected walltimeCouplingOptions: WalltimeCouplingOptions | undefined; // Supposed to contain a prometheus counter object, providing an inc() method. protected counterForwardLeap: any | undefined; /** * Fragment time leap, defined as the time difference between the last sample * of a fragment and the last sample of the previous fragment. */ fragmentTimeLeapSeconds: number; // `undefined` means: do not collect validation info; this is so // that we ideally save memory postedFragmentsSinceLastValidate: | Array<LogSeriesFragment | MetricSeriesFragment> | undefined; sample_time_increment_ns: number; n_samples_per_series_fragment: number; uniqueName: string; // To make things absolutely unambiguous allow for the consumer to set the // last fragment consumed via this method. // lastFragmentConsumed: FragmentType | undefined; lastFragmentConsumed: LogSeriesFragment | MetricSeriesFragment | undefined; constructor(opts: LogSeriesOpts | MetricSeriesOpts) { this.nFragmentsConsumed = 0; this.starttime = opts.starttime; this.uniqueName = opts.uniqueName; this.optionstring = `${JSON.stringify(opts)}`; this.labels = this.buildLabelSetFromOpts(opts); this.n_samples_per_series_fragment = opts.n_samples_per_series_fragment; this.sample_time_increment_ns = opts.sample_time_increment_ns; this.nSamplesValidatedSoFar = BigInt(0); this.walltimeCouplingOptions = opts.wtopts; this.postedFragmentsSinceLastValidate = undefined; if (!Number.isInteger(opts.sample_time_increment_ns)) { throw new Error("sample_time_increment_ns must be an integer value"); } // Calculate fragment time leap (think: by how much the internal time is // forward-leaped by the next call to generateNextFragment()). // // Important distinction: // - fragment time width, defined as the time difference between the first // and last sample in the fragment, and equal to // (n_samples_per_series_fragment - 1) * delta_t // - fragment time leap, defined as the time difference between the last // sample of a fragment and the last sample of the previous fragment, // equal to (n_samples_per_series_fragment) * delta_t this.fragmentTimeLeapSeconds = this.n_samples_per_series_fragment * (this.sample_time_increment_ns / 10 ** 6); this.validateWtOpts(opts.wtopts); if (opts.counterForwardLeap !== undefined) { this.counterForwardLeap = opts.counterForwardLeap; if (opts.counterForwardLeap.inc === undefined) { throw new Error( "the counterForwardLeap obj needs to have an `inc()` method" ); } } } protected abstract buildLabelSetFromOpts( opts: LogSeriesOpts | MetricSeriesOpts ): LabelSet; abstract currentTimeRFC3339Nano(): string; abstract promQueryString(): string; protected abstract nextSample(): LogSample | MetricSample; protected abstract generateNextFragment(): FragmentType; // | LogSeriesFragment // | MetricSeriesFragment; /** * Return floating point number representing the timestamp of the last sample * in "seconds since epoch". It is OK to potentially have less absolute * precision as compared to the internal time-keeping variables (can't fit * nanosecond resolution for a wide date range into double precision float, * which is why for log series the prometheus ecosystem tracks seconds and * the fractional part in nanoseconds in two separate variables). */ protected abstract lastSampleSecondsSinceEpoch(): number; /** * Leap forward by N seconds. * * Must only be called after just having completed a fragment (right?). */ protected abstract leapForward(n: bigint): void; // abstract fetchAndValidate( // opts: MetricSeriesFetchAndValidateOpts | LogSeriesFetchAndValidateOpts // ): Promise<number>; protected abstract fetchAndValidateFragment( fragment: LogSeriesFragment | MetricSeriesFragment, opts: MetricSeriesFetchAndValidateOpts | LogSeriesFetchAndValidateOpts ): Promise<number>; public toString(): string { // does this use the name of the extension class, instead of the name // of the base class? that's the goal here, let's see. // Optionsstring might be a little too long. //return `${this.constructor.name}(opts=${this.optionstring})`; return `${this.constructor.name}(${this.promQueryString()})`; } protected validateWtOpts(o: WalltimeCouplingOptions | undefined): void { if (o === undefined) { return; } // I was unable to do this with a for loop based on a static set of // strings or using `for (const key in obj)` -- always a type error. // Huh. assert(Number.isInteger(o["minLagSeconds"])); assert(Number.isInteger(o["maxLagSeconds"])); // The walltime coupling mechanism wants to make sure that all samples in a // fragment have timestamps from the 'green zone', a time interval that is // "allowed", by definition. The lower and upper bound of that interval are // defined by wall time and the max/minLagSeconds. When the time width of a // fragment is larger than this interval then the walltime coupling // mechanism would oscillate between leaping forward and throttling, and // never send data. That's effectively a deadlock :). I got here by using // static min/maxLagSeconds settings. Next up: calculate maxLagSeconds // dynamically based on the fragment time width / fragmentTimeLeapSeconds // (difference does not matter much when using leeway). if (o.maxLagSeconds <= this.fragmentTimeLeapSeconds) { throw new Error("maxLagSeconds <= fragmentTimeLeapSeconds"); } // if (mtls >= o["minLagSeconds"]) { // throw new Error( // "a single series fragment may cover " + // (mtls / 60.0).toFixed(2) + // "minute(s) worth of data. That may put us too far into the " + // "future. Reduce sample count per fragment or reduce " + // "time between samples." // ); // } } /** * When the time of the last sample in the last generated fragment has fallen * behind too far compared to the current wall time, this method can be used * to make the first sample of the next fragment to be generated be closer to * the current wall time again. * * If this method ever needs to be called externally, it should be called * between two calls to `generateAndGetNextFragment()`. For now it is a * private method and is called at the beginning of the implementation of * `generateNextFragment()`. * * ## Background * * With the Cortex Blocks Storage engine, we cannot push samples that go into * the future (compared to wall time in the ingest system), and we also * cannot push samples that are older than 1 hour compared to the wall time * in the ingest system. In both cases, Cortex rejects these samples. * * Context: https://github.com/opstrace/opstrace-corp/issues/147 and * https://github.com/cortexproject/cortex/issues/2366. * * The challenge: for deep read validation we need to _know_ the timestamps * for individual metric samples that were written into the remote storage * system. Keeping them all in memory is not an option towards validation, * i.e. they need to follow a predictable pattern. That is, they can't be * consumed from a clock source of this machine, but they need to be * generated synthetically, following said pattern. The simple pattern being * used here: adjacent timestamps in the synthetically generated samples have * a fixed time distance between them (`this.metrics_time_increment_ms`). * * Now, during execution, this synthetic generation of timestamps, is either * faster or slower than the evolution of the actual time. This depends on * many factors, but certainly on the user-given choice of * `this.metrics_time_increment_ms`. * * This method here provides a correction for one of both cases: when the * synthetic clock source evolves _slower_ than wall time, i.e. when it * slowly falls behind. When it has fallen behind by a specific amount, it * leaps the synthetic time source forward by a particular correction amount. * * Also note: this strategy makes use of the fact that fragments are * validated _individually_ based on their first and last sample's * timestamps, i.e. the leap forward is done _between_ fragments, and not * _within_ an individual fragment. */ protected bringCloserToWalltimeIfFallenBehind(): number { // invariant: this must not be called when `this.walltimeCouplingOptions` // is undefined. assert(this.walltimeCouplingOptions); const lastSampleSecondsSinceEpoch = this.lastSampleSecondsSinceEpoch(); const nowSecondsSinceEpoch = ZonedDateTime.now( ZoneOffset.UTC ).toEpochSecond(); // How much is the timestamp of the last generated sample lagging behind // "now"? This is a positive number, and the larger it is the larger is the // gap. Define this as "lag" (unit: seconds) -- TODO: rename vars // accordingly const shiftIntoPastSeconds = nowSecondsSinceEpoch - lastSampleSecondsSinceEpoch; // Can theoretically also be negative, meaning // `lastSampleSecondsSinceEpoch` is in the future compared to wall time. // This state is not allowed. In remaining parts of the program the // `shiftIntoPastSeconds >= 0` is treated as an invariant (a guarantee // being relied upon). if (shiftIntoPastSeconds < 0) { // The last sample of the last fragment generated is in the future // compared to current wall time. We should never get here, this is the // whole point. This can happen as of a bug in looker or as of wall time // changing unexpectedly around us. Either should be fatal (lead up to a // crash). throw new Error( `${this}: shiftIntoPastSeconds < 0: ${shiftIntoPastSeconds.toFixed( 4 )} -- lastSampleSecondsSinceEpoch: ${lastSampleSecondsSinceEpoch.toFixed( 4 )} -- nowSecondsSinceEpoch: ${nowSecondsSinceEpoch.toFixed(4)}` ); } // If we've fallen behind by more than // `walltimeCouplingOptions.maxLagSeconds` then leap forward to _almost_ // the the right end of the interval [now-wcp.maxLagSeconds, // now-wcp.minLagSeconds]. TODO: maybe expose these parameters to users via // CLI -- maybe also set the defaults 'rather tight', i.e. leap forward by // just a little bit when fallen behind just a little bit. if (shiftIntoPastSeconds > this.walltimeCouplingOptions.maxLagSeconds) { // Do Math.floor() to make this be an integer value const secondsToLeapForward = BigInt( Math.floor( shiftIntoPastSeconds - this.walltimeCouplingOptions.minLagSeconds - 5 ) ); const lfm = Number(secondsToLeapForward) / 60; log.debug(`${this}: leap forward by ${lfm.toFixed(2)} minutes`); // rely on the implementation here to actually leap by the amount that // we just logged, and that we're going to use to build the return // value below this.leapForward(secondsToLeapForward); // Increment Prometheus metric counter if that was provided. if (this.counterForwardLeap !== undefined) { this.counterForwardLeap.inc(); } // Return the _updated_ shift-into-past. return shiftIntoPastSeconds - lfm * 60; } // The current lag is within expected bounds. if (this.nFragmentsConsumed > 0 && this.nFragmentsConsumed % 10000 === 0) { // Log current lag (sometimes -- but this is not a great, useful // solution) const m = shiftIntoPastSeconds / 60.0; // too noisy for large stream count. log.debug("%s: lag behind walltime: %s minutes", this, m.toFixed(1)); } // return 0 or positive number: this is the current lag in seconds compared // to walltime, specifically _behind_ walltime. return shiftIntoPastSeconds; } public generateNextFragmentOrSkip(): [number, FragmentType | undefined] { if (this.walltimeCouplingOptions === undefined) { // walltime coupling disabled, return meaningless -1 to comply with // interface return [-1, this.generateNextFragment()]; } // TODO: this might get expensive, maybe use a monotonic time source // to make sure that we call this only once per minute or so. const shiftIntoPastSeconds = this.bringCloserToWalltimeIfFallenBehind(); // A pragmatic criterion allowing for artificial throttling. Only generate // the next fragment if after fragment generation the internal time source // is still in the past compared to current walltime, with a _guaranteed_ // leeway of `minLagSeconds` as given by the `walltimeCouplingOptions`. // This mechanism prevents this time series to get dangerously close to // 'now'; which implies that it also does not go into the future. This is // useful when the remote system that receives samples from this source // (which has its own perspective on wall time) must not receive samples // from the future. if ( shiftIntoPastSeconds - this.fragmentTimeLeapSeconds > this.walltimeCouplingOptions.minLagSeconds ) { // When generating a new fragment then the current shift into the past // (the 'lag') is not the value we just got, but we've advanced by a // known amount: the fragmentTimeLeapSeconds -- add that. return [ shiftIntoPastSeconds + this.fragmentTimeLeapSeconds, this.generateNextFragment() ]; } // Behind wall time, but too close to wall time. Do not generate a new // fragment. return [shiftIntoPastSeconds, undefined]; } // Most of FetchAndValidateOpts is ignored, just here to make this func // signature match DummyStream.fetchAndValidate public async fetchAndValidate( opts: MetricSeriesFetchAndValidateOpts ): Promise<number> { log.debug("%s fetchAndValidate()", this); let samplesValidated = 0; let fragmentsValidated = 0; // `this.postedFragmentsSinceLastValidate` is `undefined` if // `this.collectValidationInfo` was set to `false`. if (this.postedFragmentsSinceLastValidate === undefined) { return 0; } for (const fragment of this.postedFragmentsSinceLastValidate) { const validated = await this.fetchAndValidateFragment(fragment, opts); samplesValidated += validated; fragmentsValidated += 1; // Control log verbosity if (fragmentsValidated % 20 === 0) { log.debug( "%s fetchAndValidate(): %s fragments validated (%s samples)", this.uniqueName, fragmentsValidated, samplesValidated ); } } this.postedFragmentsSinceLastValidate = []; return samplesValidated; } public disableValidation(): void { this.postedFragmentsSinceLastValidate = undefined; } public enableValidation(): void { this.postedFragmentsSinceLastValidate = []; } public shouldBeValidated(): boolean { if (this.postedFragmentsSinceLastValidate === undefined) { return false; } return true; } public rememberFragmentForValidation( f: LogSeriesFragment | MetricSeriesFragment ): void { if (this.postedFragmentsSinceLastValidate !== undefined) { this.postedFragmentsSinceLastValidate.push(f); } } public dropValidationInfo(): void { this.postedFragmentsSinceLastValidate = []; } }
the_stack
import ez = require("TypeScript/ez") import EZ_TEST = require("./TestFramework") function mul(m: ez.Mat4, v: ez.Vec3): ez.Vec3 { let r = v.Clone(); m.TransformPosition(r); return r; } export class TestMat4 extends ez.TypescriptComponent { /* BEGIN AUTO-GENERATED: VARIABLES */ /* END AUTO-GENERATED: VARIABLES */ constructor() { super() } static RegisterMessageHandlers() { ez.TypescriptComponent.RegisterMessageHandler(ez.MsgGenericEvent, "OnMsgGenericEvent"); } ExecuteTests(): void { // Constructor (default) { let m = new ez.Mat4(); EZ_TEST.FLOAT(m.GetElement(0, 0), 1, 0.001); EZ_TEST.FLOAT(m.GetElement(1, 0), 0, 0.001); EZ_TEST.FLOAT(m.GetElement(2, 0), 0, 0.001); EZ_TEST.FLOAT(m.GetElement(3, 0), 0, 0.001); EZ_TEST.FLOAT(m.GetElement(0, 1), 0, 0.001); EZ_TEST.FLOAT(m.GetElement(1, 1), 1, 0.001); EZ_TEST.FLOAT(m.GetElement(2, 1), 0, 0.001); EZ_TEST.FLOAT(m.GetElement(3, 1), 0, 0.001); EZ_TEST.FLOAT(m.GetElement(0, 2), 0, 0.001); EZ_TEST.FLOAT(m.GetElement(1, 2), 0, 0.001); EZ_TEST.FLOAT(m.GetElement(2, 2), 1, 0.001); EZ_TEST.FLOAT(m.GetElement(3, 2), 0, 0.001); EZ_TEST.FLOAT(m.GetElement(0, 3), 0, 0.001); EZ_TEST.FLOAT(m.GetElement(1, 3), 0, 0.001); EZ_TEST.FLOAT(m.GetElement(2, 3), 0, 0.001); EZ_TEST.FLOAT(m.GetElement(3, 3), 1, 0.001); EZ_TEST.BOOL(m.IsIdentity()); } // Constructor (Elements) { let m = new ez.Mat4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); EZ_TEST.FLOAT(m.GetElement(0, 0), 1, 0.001); EZ_TEST.FLOAT(m.GetElement(1, 0), 2, 0.001); EZ_TEST.FLOAT(m.GetElement(2, 0), 3, 0.001); EZ_TEST.FLOAT(m.GetElement(3, 0), 4, 0.001); EZ_TEST.FLOAT(m.GetElement(0, 1), 5, 0.001); EZ_TEST.FLOAT(m.GetElement(1, 1), 6, 0.001); EZ_TEST.FLOAT(m.GetElement(2, 1), 7, 0.001); EZ_TEST.FLOAT(m.GetElement(3, 1), 8, 0.001); EZ_TEST.FLOAT(m.GetElement(0, 2), 9, 0.001); EZ_TEST.FLOAT(m.GetElement(1, 2), 10, 0.001); EZ_TEST.FLOAT(m.GetElement(2, 2), 11, 0.001); EZ_TEST.FLOAT(m.GetElement(3, 2), 12, 0.001); EZ_TEST.FLOAT(m.GetElement(0, 3), 13, 0.001); EZ_TEST.FLOAT(m.GetElement(1, 3), 14, 0.001); EZ_TEST.FLOAT(m.GetElement(2, 3), 15, 0.001); EZ_TEST.FLOAT(m.GetElement(3, 3), 16, 0.001); } // Clone { let m0 = new ez.Mat4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); let m = m0.Clone(); EZ_TEST.FLOAT(m.GetElement(0, 0), 1, 0.001); EZ_TEST.FLOAT(m.GetElement(1, 0), 2, 0.001); EZ_TEST.FLOAT(m.GetElement(2, 0), 3, 0.001); EZ_TEST.FLOAT(m.GetElement(3, 0), 4, 0.001); EZ_TEST.FLOAT(m.GetElement(0, 1), 5, 0.001); EZ_TEST.FLOAT(m.GetElement(1, 1), 6, 0.001); EZ_TEST.FLOAT(m.GetElement(2, 1), 7, 0.001); EZ_TEST.FLOAT(m.GetElement(3, 1), 8, 0.001); EZ_TEST.FLOAT(m.GetElement(0, 2), 9, 0.001); EZ_TEST.FLOAT(m.GetElement(1, 2), 10, 0.001); EZ_TEST.FLOAT(m.GetElement(2, 2), 11, 0.001); EZ_TEST.FLOAT(m.GetElement(3, 2), 12, 0.001); EZ_TEST.FLOAT(m.GetElement(0, 3), 13, 0.001); EZ_TEST.FLOAT(m.GetElement(1, 3), 14, 0.001); EZ_TEST.FLOAT(m.GetElement(2, 3), 15, 0.001); EZ_TEST.FLOAT(m.GetElement(3, 3), 16, 0.001); } // CloneAsMat3 { let m0 = new ez.Mat4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); let m = m0.CloneAsMat3(); EZ_TEST.FLOAT(m.GetElement(0, 0), 1, 0.001); EZ_TEST.FLOAT(m.GetElement(1, 0), 2, 0.001); EZ_TEST.FLOAT(m.GetElement(2, 0), 3, 0.001); EZ_TEST.FLOAT(m.GetElement(0, 1), 5, 0.001); EZ_TEST.FLOAT(m.GetElement(1, 1), 6, 0.001); EZ_TEST.FLOAT(m.GetElement(2, 1), 7, 0.001); EZ_TEST.FLOAT(m.GetElement(0, 2), 9, 0.001); EZ_TEST.FLOAT(m.GetElement(1, 2), 10, 0.001); EZ_TEST.FLOAT(m.GetElement(2, 2), 11, 0.001); } // SetMat4 { let m0 = new ez.Mat4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); let m = new ez.Mat4(); m.SetMat4(m0); EZ_TEST.FLOAT(m.GetElement(0, 0), 1, 0.001); EZ_TEST.FLOAT(m.GetElement(1, 0), 2, 0.001); EZ_TEST.FLOAT(m.GetElement(2, 0), 3, 0.001); EZ_TEST.FLOAT(m.GetElement(3, 0), 4, 0.001); EZ_TEST.FLOAT(m.GetElement(0, 1), 5, 0.001); EZ_TEST.FLOAT(m.GetElement(1, 1), 6, 0.001); EZ_TEST.FLOAT(m.GetElement(2, 1), 7, 0.001); EZ_TEST.FLOAT(m.GetElement(3, 1), 8, 0.001); EZ_TEST.FLOAT(m.GetElement(0, 2), 9, 0.001); EZ_TEST.FLOAT(m.GetElement(1, 2), 10, 0.001); EZ_TEST.FLOAT(m.GetElement(2, 2), 11, 0.001); EZ_TEST.FLOAT(m.GetElement(3, 2), 12, 0.001); EZ_TEST.FLOAT(m.GetElement(0, 3), 13, 0.001); EZ_TEST.FLOAT(m.GetElement(1, 3), 14, 0.001); EZ_TEST.FLOAT(m.GetElement(2, 3), 15, 0.001); EZ_TEST.FLOAT(m.GetElement(3, 3), 16, 0.001); } // SetElement { let m = ez.Mat4.ZeroMatrix(); m.SetElement(0, 0, 1); m.SetElement(1, 0, 2); m.SetElement(2, 0, 3); m.SetElement(3, 0, 4); m.SetElement(0, 1, 5); m.SetElement(1, 1, 6); m.SetElement(2, 1, 7); m.SetElement(3, 1, 8); m.SetElement(0, 2, 9); m.SetElement(1, 2, 10); m.SetElement(2, 2, 11); m.SetElement(3, 2, 12); m.SetElement(0, 3, 13); m.SetElement(1, 3, 14); m.SetElement(2, 3, 15); m.SetElement(3, 3, 16); let m0 = new ez.Mat4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); EZ_TEST.BOOL(m.IsIdentical(m0)); } // SetElements { let m = ez.Mat4.ZeroMatrix(); m.SetElements(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); let m0 = new ez.Mat4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); EZ_TEST.BOOL(m.IsIdentical(m0)); } // SetFromArray { const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; { let m = new ez.Mat4(); m.SetFromArray(data, true); EZ_TEST.BOOL(m.m_ElementsCM[0] == 1.0 && m.m_ElementsCM[1] == 2.0 && m.m_ElementsCM[2] == 3.0 && m.m_ElementsCM[3] == 4.0 && m.m_ElementsCM[4] == 5.0 && m.m_ElementsCM[5] == 6.0 && m.m_ElementsCM[6] == 7.0 && m.m_ElementsCM[7] == 8.0 && m.m_ElementsCM[8] == 9.0 && m.m_ElementsCM[9] == 10.0 && m.m_ElementsCM[10] == 11.0 && m.m_ElementsCM[11] == 12.0 && m.m_ElementsCM[12] == 13.0 && m.m_ElementsCM[13] == 14.0 && m.m_ElementsCM[14] == 15.0 && m.m_ElementsCM[15] == 16.0); } { let m = new ez.Mat4(); m.SetFromArray(data, false); EZ_TEST.BOOL(m.m_ElementsCM[0] == 1.0 && m.m_ElementsCM[1] == 5.0 && m.m_ElementsCM[2] == 9.0 && m.m_ElementsCM[3] == 13.0 && m.m_ElementsCM[4] == 2.0 && m.m_ElementsCM[5] == 6.0 && m.m_ElementsCM[6] == 10.0 && m.m_ElementsCM[7] == 14.0 && m.m_ElementsCM[8] == 3.0 && m.m_ElementsCM[9] == 7.0 && m.m_ElementsCM[10] == 11.0 && m.m_ElementsCM[11] == 15.0 && m.m_ElementsCM[12] == 4.0 && m.m_ElementsCM[13] == 8.0 && m.m_ElementsCM[14] == 12.0 && m.m_ElementsCM[15] == 16.0); } } // SetTransformationMatrix { let mr = new ez.Mat3(1, 2, 3, 4, 5, 6, 7, 8, 9); let vt = new ez.Vec3(10, 11, 12); let m = new ez.Mat4(); m.SetTransformationMatrix(mr, vt); EZ_TEST.FLOAT(m.GetElement(0, 0), 1, 0); EZ_TEST.FLOAT(m.GetElement(1, 0), 2, 0); EZ_TEST.FLOAT(m.GetElement(2, 0), 3, 0); EZ_TEST.FLOAT(m.GetElement(3, 0), 10, 0); EZ_TEST.FLOAT(m.GetElement(0, 1), 4, 0); EZ_TEST.FLOAT(m.GetElement(1, 1), 5, 0); EZ_TEST.FLOAT(m.GetElement(2, 1), 6, 0); EZ_TEST.FLOAT(m.GetElement(3, 1), 11, 0); EZ_TEST.FLOAT(m.GetElement(0, 2), 7, 0); EZ_TEST.FLOAT(m.GetElement(1, 2), 8, 0); EZ_TEST.FLOAT(m.GetElement(2, 2), 9, 0); EZ_TEST.FLOAT(m.GetElement(3, 2), 12, 0); EZ_TEST.FLOAT(m.GetElement(0, 3), 0, 0); EZ_TEST.FLOAT(m.GetElement(1, 3), 0, 0); EZ_TEST.FLOAT(m.GetElement(2, 3), 0, 0); EZ_TEST.FLOAT(m.GetElement(3, 3), 1, 0); } // GetAsArray { let m = new ez.Mat4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); let data = m.GetAsArray(true); EZ_TEST.FLOAT(data[0], 1, 0.0001); EZ_TEST.FLOAT(data[1], 5, 0.0001); EZ_TEST.FLOAT(data[2], 9, 0.0001); EZ_TEST.FLOAT(data[3], 13, 0.0001); EZ_TEST.FLOAT(data[4], 2, 0.0001); EZ_TEST.FLOAT(data[5], 6, 0.0001); EZ_TEST.FLOAT(data[6], 10, 0.0001); EZ_TEST.FLOAT(data[7], 14, 0.0001); EZ_TEST.FLOAT(data[8], 3, 0.0001); EZ_TEST.FLOAT(data[9], 7, 0.0001); EZ_TEST.FLOAT(data[10], 11, 0.0001); EZ_TEST.FLOAT(data[11], 15, 0.0001); EZ_TEST.FLOAT(data[12], 4, 0.0001); EZ_TEST.FLOAT(data[13], 8, 0.0001); EZ_TEST.FLOAT(data[14], 12, 0.0001); EZ_TEST.FLOAT(data[15], 16, 0.0001); data = m.GetAsArray(false); EZ_TEST.FLOAT(data[0], 1, 0.0001); EZ_TEST.FLOAT(data[1], 2, 0.0001); EZ_TEST.FLOAT(data[2], 3, 0.0001); EZ_TEST.FLOAT(data[3], 4, 0.0001); EZ_TEST.FLOAT(data[4], 5, 0.0001); EZ_TEST.FLOAT(data[5], 6, 0.0001); EZ_TEST.FLOAT(data[6], 7, 0.0001); EZ_TEST.FLOAT(data[7], 8, 0.0001); EZ_TEST.FLOAT(data[8], 9, 0.0001); EZ_TEST.FLOAT(data[9], 10, 0.0001); EZ_TEST.FLOAT(data[10], 11, 0.0001); EZ_TEST.FLOAT(data[11], 12, 0.0001); EZ_TEST.FLOAT(data[12], 13, 0.0001); EZ_TEST.FLOAT(data[13], 14, 0.0001); EZ_TEST.FLOAT(data[14], 15, 0.0001); EZ_TEST.FLOAT(data[15], 16, 0.0001); } // SetZero { let m = new ez.Mat4(); m.SetZero(); for (let i = 0; i < 16; ++i) EZ_TEST.FLOAT(m.m_ElementsCM[i], 0.0, 0.0); } // SetIdentity { let m = new ez.Mat4(); m.SetIdentity(); EZ_TEST.FLOAT(m.GetElement(0, 0), 1, 0); EZ_TEST.FLOAT(m.GetElement(1, 0), 0, 0); EZ_TEST.FLOAT(m.GetElement(2, 0), 0, 0); EZ_TEST.FLOAT(m.GetElement(3, 0), 0, 0); EZ_TEST.FLOAT(m.GetElement(0, 1), 0, 0); EZ_TEST.FLOAT(m.GetElement(1, 1), 1, 0); EZ_TEST.FLOAT(m.GetElement(2, 1), 0, 0); EZ_TEST.FLOAT(m.GetElement(3, 1), 0, 0); EZ_TEST.FLOAT(m.GetElement(0, 2), 0, 0); EZ_TEST.FLOAT(m.GetElement(1, 2), 0, 0); EZ_TEST.FLOAT(m.GetElement(2, 2), 1, 0); EZ_TEST.FLOAT(m.GetElement(3, 2), 0, 0); EZ_TEST.FLOAT(m.GetElement(0, 3), 0, 0); EZ_TEST.FLOAT(m.GetElement(1, 3), 0, 0); EZ_TEST.FLOAT(m.GetElement(2, 3), 0, 0); EZ_TEST.FLOAT(m.GetElement(3, 3), 1, 0); } // SetTranslationMatrix { let m = new ez.Mat4(); m.SetTranslationMatrix(new ez.Vec3(2, 3, 4)); EZ_TEST.FLOAT(m.GetElement(0, 0), 1, 0); EZ_TEST.FLOAT(m.GetElement(1, 0), 0, 0); EZ_TEST.FLOAT(m.GetElement(2, 0), 0, 0); EZ_TEST.FLOAT(m.GetElement(3, 0), 2, 0); EZ_TEST.FLOAT(m.GetElement(0, 1), 0, 0); EZ_TEST.FLOAT(m.GetElement(1, 1), 1, 0); EZ_TEST.FLOAT(m.GetElement(2, 1), 0, 0); EZ_TEST.FLOAT(m.GetElement(3, 1), 3, 0); EZ_TEST.FLOAT(m.GetElement(0, 2), 0, 0); EZ_TEST.FLOAT(m.GetElement(1, 2), 0, 0); EZ_TEST.FLOAT(m.GetElement(2, 2), 1, 0); EZ_TEST.FLOAT(m.GetElement(3, 2), 4, 0); EZ_TEST.FLOAT(m.GetElement(0, 3), 0, 0); EZ_TEST.FLOAT(m.GetElement(1, 3), 0, 0); EZ_TEST.FLOAT(m.GetElement(2, 3), 0, 0); EZ_TEST.FLOAT(m.GetElement(3, 3), 1, 0); } // SetScalingMatrix { let m = new ez.Mat4(); m.SetScalingMatrix(new ez.Vec3(2, 3, 4)); EZ_TEST.FLOAT(m.GetElement(0, 0), 2, 0); EZ_TEST.FLOAT(m.GetElement(1, 0), 0, 0); EZ_TEST.FLOAT(m.GetElement(2, 0), 0, 0); EZ_TEST.FLOAT(m.GetElement(3, 0), 0, 0); EZ_TEST.FLOAT(m.GetElement(0, 1), 0, 0); EZ_TEST.FLOAT(m.GetElement(1, 1), 3, 0); EZ_TEST.FLOAT(m.GetElement(2, 1), 0, 0); EZ_TEST.FLOAT(m.GetElement(3, 1), 0, 0); EZ_TEST.FLOAT(m.GetElement(0, 2), 0, 0); EZ_TEST.FLOAT(m.GetElement(1, 2), 0, 0); EZ_TEST.FLOAT(m.GetElement(2, 2), 4, 0); EZ_TEST.FLOAT(m.GetElement(3, 2), 0, 0); EZ_TEST.FLOAT(m.GetElement(0, 3), 0, 0); EZ_TEST.FLOAT(m.GetElement(1, 3), 0, 0); EZ_TEST.FLOAT(m.GetElement(2, 3), 0, 0); EZ_TEST.FLOAT(m.GetElement(3, 3), 1, 0); } // SetRotationMatrixX { let m = new ez.Mat4(); m.SetRotationMatrixX(ez.Angle.DegreeToRadian(90)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(1, -3, 2), 0.0001)); m.SetRotationMatrixX(ez.Angle.DegreeToRadian(180)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(1, -2, -3), 0.0001)); m.SetRotationMatrixX(ez.Angle.DegreeToRadian(270)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(1, 3, -2), 0.0001)); m.SetRotationMatrixX(ez.Angle.DegreeToRadian(360)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(1, 2, 3), 0.0001)); } // SetRotationMatrixY { let m = new ez.Mat4(); m.SetRotationMatrixY(ez.Angle.DegreeToRadian(90)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(3, 2, -1), 0.0001)); m.SetRotationMatrixY(ez.Angle.DegreeToRadian(180)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(-1, 2, -3), 0.0001)); m.SetRotationMatrixY(ez.Angle.DegreeToRadian(270)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(-3, 2, 1), 0.0001)); m.SetRotationMatrixY(ez.Angle.DegreeToRadian(360)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(1, 2, 3), 0.0001)); } // SetRotationMatrixZ { let m = new ez.Mat4(); m.SetRotationMatrixZ(ez.Angle.DegreeToRadian(90)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(-2, 1, 3), 0.0001)); m.SetRotationMatrixZ(ez.Angle.DegreeToRadian(180)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(-1, -2, 3), 0.0001)); m.SetRotationMatrixZ(ez.Angle.DegreeToRadian(270)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(2, -1, 3), 0.0001)); m.SetRotationMatrixZ(ez.Angle.DegreeToRadian(360)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(1, 2, 3), 0.0001)); } // SetRotationMatrix { let m = new ez.Mat4(); m.SetRotationMatrix(new ez.Vec3(1, 0, 0), ez.Angle.DegreeToRadian(90)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(1, -3, 2), 0.001)); m.SetRotationMatrix(new ez.Vec3(1, 0, 0), ez.Angle.DegreeToRadian(180)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(1, -2, -3), 0.001)); m.SetRotationMatrix(new ez.Vec3(1, 0, 0), ez.Angle.DegreeToRadian(270)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(1, 3, -2), 0.001)); m.SetRotationMatrix(new ez.Vec3(0, 1, 0), ez.Angle.DegreeToRadian(90)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(3, 2, -1), 0.001)); m.SetRotationMatrix(new ez.Vec3(0, 1, 0), ez.Angle.DegreeToRadian(180)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(-1, 2, -3), 0.001)); m.SetRotationMatrix(new ez.Vec3(0, 1, 0), ez.Angle.DegreeToRadian(270)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(-3, 2, 1), 0.001)); m.SetRotationMatrix(new ez.Vec3(0, 0, 1), ez.Angle.DegreeToRadian(90)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(-2, 1, 3), 0.001)); m.SetRotationMatrix(new ez.Vec3(0, 0, 1), ez.Angle.DegreeToRadian(180)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(-1, -2, 3), 0.001)); m.SetRotationMatrix(new ez.Vec3(0, 0, 1), ez.Angle.DegreeToRadian(270)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(2, -1, 3), 0.001)); } // IdentityMatrix { let m = ez.Mat4.IdentityMatrix(); EZ_TEST.FLOAT(m.GetElement(0, 0), 1, 0); EZ_TEST.FLOAT(m.GetElement(1, 0), 0, 0); EZ_TEST.FLOAT(m.GetElement(2, 0), 0, 0); EZ_TEST.FLOAT(m.GetElement(3, 0), 0, 0); EZ_TEST.FLOAT(m.GetElement(0, 1), 0, 0); EZ_TEST.FLOAT(m.GetElement(1, 1), 1, 0); EZ_TEST.FLOAT(m.GetElement(2, 1), 0, 0); EZ_TEST.FLOAT(m.GetElement(3, 1), 0, 0); EZ_TEST.FLOAT(m.GetElement(0, 2), 0, 0); EZ_TEST.FLOAT(m.GetElement(1, 2), 0, 0); EZ_TEST.FLOAT(m.GetElement(2, 2), 1, 0); EZ_TEST.FLOAT(m.GetElement(3, 2), 0, 0); EZ_TEST.FLOAT(m.GetElement(0, 3), 0, 0); EZ_TEST.FLOAT(m.GetElement(1, 3), 0, 0); EZ_TEST.FLOAT(m.GetElement(2, 3), 0, 0); EZ_TEST.FLOAT(m.GetElement(3, 3), 1, 0); } // ZeroMatrix { let m = ez.Mat4.ZeroMatrix(); EZ_TEST.FLOAT(m.GetElement(0, 0), 0, 0); EZ_TEST.FLOAT(m.GetElement(1, 0), 0, 0); EZ_TEST.FLOAT(m.GetElement(2, 0), 0, 0); EZ_TEST.FLOAT(m.GetElement(3, 0), 0, 0); EZ_TEST.FLOAT(m.GetElement(0, 1), 0, 0); EZ_TEST.FLOAT(m.GetElement(1, 1), 0, 0); EZ_TEST.FLOAT(m.GetElement(2, 1), 0, 0); EZ_TEST.FLOAT(m.GetElement(3, 1), 0, 0); EZ_TEST.FLOAT(m.GetElement(0, 2), 0, 0); EZ_TEST.FLOAT(m.GetElement(1, 2), 0, 0); EZ_TEST.FLOAT(m.GetElement(2, 2), 0, 0); EZ_TEST.FLOAT(m.GetElement(3, 2), 0, 0); EZ_TEST.FLOAT(m.GetElement(0, 3), 0, 0); EZ_TEST.FLOAT(m.GetElement(1, 3), 0, 0); EZ_TEST.FLOAT(m.GetElement(2, 3), 0, 0); EZ_TEST.FLOAT(m.GetElement(3, 3), 0, 0); } // Transpose { let m = new ez.Mat4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); m.Transpose(); EZ_TEST.FLOAT(m.GetElement(0, 0), 1, 0); EZ_TEST.FLOAT(m.GetElement(1, 0), 5, 0); EZ_TEST.FLOAT(m.GetElement(2, 0), 9, 0); EZ_TEST.FLOAT(m.GetElement(3, 0), 13, 0); EZ_TEST.FLOAT(m.GetElement(0, 1), 2, 0); EZ_TEST.FLOAT(m.GetElement(1, 1), 6, 0); EZ_TEST.FLOAT(m.GetElement(2, 1), 10, 0); EZ_TEST.FLOAT(m.GetElement(3, 1), 14, 0); EZ_TEST.FLOAT(m.GetElement(0, 2), 3, 0); EZ_TEST.FLOAT(m.GetElement(1, 2), 7, 0); EZ_TEST.FLOAT(m.GetElement(2, 2), 11, 0); EZ_TEST.FLOAT(m.GetElement(3, 2), 15, 0); EZ_TEST.FLOAT(m.GetElement(0, 3), 4, 0); EZ_TEST.FLOAT(m.GetElement(1, 3), 8, 0); EZ_TEST.FLOAT(m.GetElement(2, 3), 12, 0); EZ_TEST.FLOAT(m.GetElement(3, 3), 16, 0); } // GetTranspose { let m0 = new ez.Mat4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); let m = m0.GetTranspose(); EZ_TEST.FLOAT(m.GetElement(0, 0), 1); EZ_TEST.FLOAT(m.GetElement(1, 0), 5); EZ_TEST.FLOAT(m.GetElement(2, 0), 9); EZ_TEST.FLOAT(m.GetElement(3, 0), 13); EZ_TEST.FLOAT(m.GetElement(0, 1), 2); EZ_TEST.FLOAT(m.GetElement(1, 1), 6); EZ_TEST.FLOAT(m.GetElement(2, 1), 10); EZ_TEST.FLOAT(m.GetElement(3, 1), 14); EZ_TEST.FLOAT(m.GetElement(0, 2), 3); EZ_TEST.FLOAT(m.GetElement(1, 2), 7); EZ_TEST.FLOAT(m.GetElement(2, 2), 11); EZ_TEST.FLOAT(m.GetElement(3, 2), 15); EZ_TEST.FLOAT(m.GetElement(0, 3), 4); EZ_TEST.FLOAT(m.GetElement(1, 3), 8); EZ_TEST.FLOAT(m.GetElement(2, 3), 12); EZ_TEST.FLOAT(m.GetElement(3, 3), 16); } // Invert { for (let x = 1.0; x < 360.0; x += 40.0) { for (let y = 2.0; y < 360.0; y += 37.0) { for (let z = 3.0; z < 360.0; z += 53.0) { let m = new ez.Mat4(); m.SetRotationMatrix(new ez.Vec3(x, y, z).GetNormalized(), ez.Angle.DegreeToRadian(19.0)); let inv = m.Clone(); EZ_TEST.BOOL(inv.Invert()); let v = mul(m, new ez.Vec3(1, 1, 1)); let vinv = mul(inv, v); EZ_TEST.VEC3(vinv, new ez.Vec3(1, 1, 1), 0.001); } } } } // GetInverse { for (let x = 1.0; x < 360.0; x += 39.0) { for (let y = 2.0; y < 360.0; y += 29.0) { for (let z = 3.0; z < 360.0; z += 51.0) { let m = new ez.Mat4(); m.SetRotationMatrix(new ez.Vec3(x, y, z).GetNormalized(), ez.Angle.DegreeToRadian(83.0)); let inv = m.GetInverse(); let v = mul(m, new ez.Vec3(1, 1, 1)); let vinv = mul(inv, v); EZ_TEST.VEC3(vinv, new ez.Vec3(1, 1, 1), 0.001); } } } } // IsZero { let m = new ez.Mat4(); m.SetIdentity(); EZ_TEST.BOOL(!m.IsZero()); m.SetZero(); EZ_TEST.BOOL(m.IsZero()); } // IsIdentity { let m = new ez.Mat4(); m.SetIdentity(); EZ_TEST.BOOL(m.IsIdentity()); m.SetZero(); EZ_TEST.BOOL(!m.IsIdentity()); } // GetRow { let m = new ez.Mat4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); EZ_TEST.ARRAY(4, m.GetRow(0), [1, 2, 3, 4], 0.0); EZ_TEST.ARRAY(4, m.GetRow(1), [5, 6, 7, 8], 0.0); EZ_TEST.ARRAY(4, m.GetRow(2), [9, 10, 11, 12], 0.0); EZ_TEST.ARRAY(4, m.GetRow(3), [13, 14, 15, 16], 0.0); } // SetRow { let m = new ez.Mat4(); m.SetZero(); m.SetRow(0, 1, 2, 3, 4); EZ_TEST.ARRAY(4, m.GetRow(0), [1, 2, 3, 4], 0.0); m.SetRow(1, 5, 6, 7, 8); EZ_TEST.ARRAY(4, m.GetRow(1), [5, 6, 7, 8], 0.0); m.SetRow(2, 9, 10, 11, 12); EZ_TEST.ARRAY(4, m.GetRow(2), [9, 10, 11, 12], 0.0); m.SetRow(3, 13, 14, 15, 16); EZ_TEST.ARRAY(4, m.GetRow(3), [13, 14, 15, 16], 0.0); } // GetColumn { let m = new ez.Mat4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); EZ_TEST.ARRAY(4, m.GetColumn(0), [1, 5, 9, 13], 0.0); EZ_TEST.ARRAY(4, m.GetColumn(1), [2, 6, 10, 14], 0.0); EZ_TEST.ARRAY(4, m.GetColumn(2), [3, 7, 11, 15], 0.0); EZ_TEST.ARRAY(4, m.GetColumn(3), [4, 8, 12, 16], 0.0); } // SetColumn { let m = new ez.Mat4(); m.SetZero(); m.SetColumn(0, 1, 2, 3, 4); EZ_TEST.ARRAY(4, m.GetColumn(0), [1, 2, 3, 4], 0.0); m.SetColumn(1, 5, 6, 7, 8); EZ_TEST.ARRAY(4, m.GetColumn(1), [5, 6, 7, 8], 0.0); m.SetColumn(2, 9, 10, 11, 12); EZ_TEST.ARRAY(4, m.GetColumn(2), [9, 10, 11, 12], 0.0); m.SetColumn(3, 13, 14, 15, 16); EZ_TEST.ARRAY(4, m.GetColumn(3), [13, 14, 15, 16], 0.0); } // GetDiagonal { let m = new ez.Mat4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); EZ_TEST.ARRAY(4, m.GetDiagonal(), [1, 6, 11, 16], 0.0); } // SetDiagonal { let m = new ez.Mat4(); m.SetZero(); m.SetDiagonal(1, 2, 3, 4); EZ_TEST.ARRAY(4, m.GetColumn(0), [1, 0, 0, 0], 0.0); EZ_TEST.ARRAY(4, m.GetColumn(1), [0, 2, 0, 0], 0.0); EZ_TEST.ARRAY(4, m.GetColumn(2), [0, 0, 3, 0], 0.0); EZ_TEST.ARRAY(4, m.GetColumn(3), [0, 0, 0, 4], 0.0); } // GetTranslationVector { let m = new ez.Mat4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); EZ_TEST.VEC3(m.GetTranslationVector(), new ez.Vec3(4, 8, 12), 0.0); } // SetTranslationVector { let m = new ez.Mat4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); m.SetTranslationVector(new ez.Vec3(17, 18, 19)); EZ_TEST.ARRAY(4, m.GetRow(0), [1, 2, 3, 17], 0.0); EZ_TEST.ARRAY(4, m.GetRow(1), [5, 6, 7, 18], 0.0); EZ_TEST.ARRAY(4, m.GetRow(2), [9, 10, 11, 19], 0.0); EZ_TEST.ARRAY(4, m.GetRow(3), [13, 14, 15, 16], 0.0); } // SetRotationalPart { let m = new ez.Mat4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); let r = new ez.Mat3(17, 18, 19, 20, 21, 22, 23, 24, 25); m.SetRotationalPart(r); EZ_TEST.ARRAY(4, m.GetRow(0), [17, 18, 19, 4], 0.0); EZ_TEST.ARRAY(4, m.GetRow(1), [20, 21, 22, 8], 0.0); EZ_TEST.ARRAY(4, m.GetRow(2), [23, 24, 25, 12], 0.0); EZ_TEST.ARRAY(4, m.GetRow(3), [13, 14, 15, 16], 0.0); } // GetRotationalPart { let m = new ez.Mat4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); let r = m.GetRotationalPart(); EZ_TEST.ARRAY(3, r.GetRow(0), [1, 2, 3], 0.0); EZ_TEST.ARRAY(3, r.GetRow(1), [5, 6, 7], 0.0); EZ_TEST.ARRAY(3, r.GetRow(2), [9, 10, 11], 0.0); } // GetScalingFactors { let m = new ez.Mat4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); let s = m.GetScalingFactors(); EZ_TEST.VEC3(s, new ez.Vec3(Math.sqrt((1 * 1 + 5 * 5 + 9 * 9)), Math.sqrt((2 * 2 + 6 * 6 + 10 * 10)), Math.sqrt((3 * 3 + 7 * 7 + 11 * 11))), 0.0001); } // SetScalingFactors { let m = new ez.Mat4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); EZ_TEST.BOOL(m.SetScalingFactors(1, 2, 3)); let s = m.GetScalingFactors(); EZ_TEST.VEC3(s, new ez.Vec3(1, 2, 3), 0.0001); } // TransformDirection { let m = new ez.Mat4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); let r = new ez.Vec3(1, 2, 3); m.TransformDirection(r); EZ_TEST.VEC3(r, new ez.Vec3(1 * 1 + 2 * 2 + 3 * 3, 1 * 5 + 2 * 6 + 3 * 7, 1 * 9 + 2 * 10 + 3 * 11), 0.0001); } // TransformPosition { let m = new ez.Mat4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); let r = new ez.Vec3(1, 2, 3); m.TransformPosition(r); EZ_TEST.VEC3(r, new ez.Vec3(1 * 1 + 2 * 2 + 3 * 3 + 4, 1 * 5 + 2 * 6 + 3 * 7 + 8, 1 * 9 + 2 * 10 + 3 * 11 + 12), 0.0001); } // IsIdentical { let m = new ez.Mat4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); let m2 = m.Clone(); EZ_TEST.BOOL(m.IsIdentical(m2)); m2.m_ElementsCM[0] += 0.001; EZ_TEST.BOOL(!m.IsIdentical(m2)); } // IsEqual { let m = new ez.Mat4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); let m2 = m.Clone(); EZ_TEST.BOOL(m.IsEqual(m2, 0.0001)); m2.m_ElementsCM[0] += 0.001; EZ_TEST.BOOL(m.IsEqual(m2, 0.001)); EZ_TEST.BOOL(!m.IsEqual(m2, 0.0001)); } // SetMulMat4 { let m1 = new ez.Mat4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); let m2 = new ez.Mat4(-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16); let r = new ez.Mat4(); r.SetMulMat4(m1, m2); EZ_TEST.ARRAY(4, r.GetColumn(0), [-1 * 1 + -5 * 2 + -9 * 3 + -13 * 4, -1 * 5 + -5 * 6 + -9 * 7 + -13 * 8, -1 * 9 + -5 * 10 + -9 * 11 + -13 * 12, -1 * 13 + -5 * 14 + -9 * 15 + -13 * 16], 0.001); EZ_TEST.ARRAY(4, r.GetColumn(1), [-2 * 1 + -6 * 2 + -10 * 3 + -14 * 4, -2 * 5 + -6 * 6 + -10 * 7 + -14 * 8, -2 * 9 + -6 * 10 + -10 * 11 + -14 * 12, -2 * 13 + -6 * 14 + -10 * 15 + -14 * 16], 0.001); EZ_TEST.ARRAY(4, r.GetColumn(2), [-3 * 1 + -7 * 2 + -11 * 3 + -15 * 4, -3 * 5 + -7 * 6 + -11 * 7 + -15 * 8, -3 * 9 + -7 * 10 + -11 * 11 + -15 * 12, -3 * 13 + -7 * 14 + -11 * 15 + -15 * 16], 0.001); EZ_TEST.ARRAY(4, r.GetColumn(3), [-4 * 1 + -8 * 2 + -12 * 3 + -16 * 4, -4 * 5 + -8 * 6 + -12 * 7 + -16 * 8, -4 * 9 + -8 * 10 + -12 * 11 + -16 * 12, -4 * 13 + -8 * 14 + -12 * 15 + -16 * 16], 0.001); } // MulNumber { let m0 = new ez.Mat4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); let m = m0.Clone(); m.MulNumber(2); EZ_TEST.ARRAY(4, m.GetRow(0), [2, 4, 6, 8], 0.0001); EZ_TEST.ARRAY(4, m.GetRow(1), [10, 12, 14, 16], 0.0001); EZ_TEST.ARRAY(4, m.GetRow(2), [18, 20, 22, 24], 0.0001); EZ_TEST.ARRAY(4, m.GetRow(3), [26, 28, 30, 32], 0.0001); } // DivNumber { let m0 = new ez.Mat4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); m0.MulNumber(4); let m = m0.Clone(); m.DivNumber(2); EZ_TEST.ARRAY(4, m.GetRow(0), [2, 4, 6, 8], 0.0001); EZ_TEST.ARRAY(4, m.GetRow(1), [10, 12, 14, 16], 0.0001); EZ_TEST.ARRAY(4, m.GetRow(2), [18, 20, 22, 24], 0.0001); EZ_TEST.ARRAY(4, m.GetRow(3), [26, 28, 30, 32], 0.0001); } // AddMat4 / SubMat4 { let m0 = new ez.Mat4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); let m1 = new ez.Mat4(-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16); let r1 = m0.Clone(); r1.AddMat4(m1); let r2 = m0.Clone(); r2.SubMat4(m1); let c2 = m0.Clone(); c2.MulNumber(2); EZ_TEST.BOOL(r1.IsZero()); EZ_TEST.BOOL(r2.IsEqual(c2, 0.0001)); } // IsIdentical { let m = new ez.Mat4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); let m2 = m.Clone(); EZ_TEST.BOOL(m.IsIdentical(m2)); m2.m_ElementsCM[0] += 0.001; EZ_TEST.BOOL(!m.IsIdentical(m2)); } } OnMsgGenericEvent(msg: ez.MsgGenericEvent): void { if (msg.Message == "TestMat4") { this.ExecuteTests(); msg.Message = "done"; } } }
the_stack
import * as vscode from 'vscode'; export const IOS_SUGGESTION = vscode.languages.registerCompletionItemProvider( 'html', { provideCompletionItems(document: vscode.TextDocument, position: vscode.Position) { const linePrefix = document.lineAt(position).text.substr(0, position.character); if (!linePrefix.endsWith('ios.')) { return undefined; } return [ new vscode.CompletionItem('position', vscode.CompletionItemKind.Value), new vscode.CompletionItem('systemIcon', vscode.CompletionItemKind.Value), ]; }, }, '.', ); const KEYBOARD_TYPE_SUGGESTION = vscode.languages.registerCompletionItemProvider( 'html', { provideCompletionItems(document: vscode.TextDocument, position: vscode.Position) { const linePrefix = document.lineAt(position).text.substr(0, position.character); if (!linePrefix.endsWith('keyboardType=')) { return undefined; } return [ new vscode.CompletionItem('email', vscode.CompletionItemKind.Value), new vscode.CompletionItem('phone', vscode.CompletionItemKind.Value), new vscode.CompletionItem('number', vscode.CompletionItemKind.Value), new vscode.CompletionItem('integer', vscode.CompletionItemKind.Value), new vscode.CompletionItem('datetime', vscode.CompletionItemKind.Value), new vscode.CompletionItem('url', vscode.CompletionItemKind.Value), ]; }, }, '=', // triggered whenever a '.' is being typed ); const AUTOCAPITALIZATION = vscode.languages.registerCompletionItemProvider( 'html', { provideCompletionItems(document: vscode.TextDocument, position: vscode.Position) { const linePrefix = document.lineAt(position).text.substr(0, position.character); if (!linePrefix.endsWith('autocapitalizationType=')) { return undefined; } return [ new vscode.CompletionItem('none', vscode.CompletionItemKind.Value), new vscode.CompletionItem('words', vscode.CompletionItemKind.Value), new vscode.CompletionItem('sentences', vscode.CompletionItemKind.Value), new vscode.CompletionItem('allCharacters', vscode.CompletionItemKind.Value), ]; }, }, '=', // triggered whenever a '.' is being typed ); const RETURN_KEY = vscode.languages.registerCompletionItemProvider( 'html', { provideCompletionItems(document: vscode.TextDocument, position: vscode.Position) { const linePrefix = document.lineAt(position).text.substr(0, position.character); if (!linePrefix.endsWith('returnKeyType=')) { return undefined; } return [ new vscode.CompletionItem('done', vscode.CompletionItemKind.Value), new vscode.CompletionItem('next', vscode.CompletionItemKind.Value), new vscode.CompletionItem('go', vscode.CompletionItemKind.Value), new vscode.CompletionItem('search', vscode.CompletionItemKind.Value), new vscode.CompletionItem('send', vscode.CompletionItemKind.Value), ]; }, }, '=', // triggered whenever a '.' is being typed ); const TAB_BACKGROUND_COLOR = vscode.languages.registerCompletionItemProvider( 'html', { provideCompletionItems(document: vscode.TextDocument, position: vscode.Position) { const linePrefix = document.lineAt(position).text.substr(0, position.character); if (!linePrefix.endsWith('tabBackgroundColor=')) { return undefined; } return [ new vscode.CompletionItem('gray', vscode.CompletionItemKind.Value), new vscode.CompletionItem('#FF0000', vscode.CompletionItemKind.Value), new vscode.CompletionItem('rgb(200,100,200)', vscode.CompletionItemKind.Value), ]; }, }, '=', // triggered whenever a '.' is being typed ); const SELECTED_TAB_TEXT_COLOR = vscode.languages.registerCompletionItemProvider( 'html', { provideCompletionItems(document: vscode.TextDocument, position: vscode.Position) { const linePrefix = document.lineAt(position).text.substr(0, position.character); if (!linePrefix.endsWith('selectedTabTextColor=')) { return undefined; } return [ new vscode.CompletionItem('gray', vscode.CompletionItemKind.Value), new vscode.CompletionItem('#FF0000', vscode.CompletionItemKind.Value), new vscode.CompletionItem('rgb(200,100,200)', vscode.CompletionItemKind.Value), ]; }, }, '=', // triggered whenever a '.' is being typed ); const TAB_TEXT_COLOR = vscode.languages.registerCompletionItemProvider( 'html', { provideCompletionItems(document: vscode.TextDocument, position: vscode.Position) { const linePrefix = document.lineAt(position).text.substr(0, position.character); if (!linePrefix.endsWith('tabTextColor=')) { return undefined; } return [ new vscode.CompletionItem('gray', vscode.CompletionItemKind.Value), new vscode.CompletionItem('#FF0000', vscode.CompletionItemKind.Value), new vscode.CompletionItem('rgb(200,100,200)', vscode.CompletionItemKind.Value), ]; }, }, '=', // triggered whenever a '.' is being typed ); const ORIENTATION = vscode.languages.registerCompletionItemProvider( 'html', { provideCompletionItems(document: vscode.TextDocument, position: vscode.Position) { const linePrefix = document.lineAt(position).text.substr(0, position.character); if (!linePrefix.endsWith('orientation=')) { return undefined; } return [ new vscode.CompletionItem('vertical', vscode.CompletionItemKind.Value), new vscode.CompletionItem('horizontal', vscode.CompletionItemKind.Value), ]; }, }, '=', // triggered whenever a '.' is being typed ); const FONT_STYLE = vscode.languages.registerCompletionItemProvider( 'html', { provideCompletionItems(document: vscode.TextDocument, position: vscode.Position) { const linePrefix = document.lineAt(position).text.substr(0, position.character); if (!linePrefix.endsWith('fontStyle=')) { return undefined; } return [ new vscode.CompletionItem('normal', vscode.CompletionItemKind.Value), new vscode.CompletionItem('italic', vscode.CompletionItemKind.Value), ]; }, }, '=', // triggered whenever a '.' is being typed ); const TEXT_ALIGNMENT = vscode.languages.registerCompletionItemProvider( 'html', { provideCompletionItems(document: vscode.TextDocument, position: vscode.Position) { const linePrefix = document.lineAt(position).text.substr(0, position.character); if (!linePrefix.endsWith('textAlignment=')) { return undefined; } return [ new vscode.CompletionItem('left', vscode.CompletionItemKind.Value), new vscode.CompletionItem('center', vscode.CompletionItemKind.Value), new vscode.CompletionItem('right', vscode.CompletionItemKind.Value), ]; }, }, '=', // triggered whenever a '.' is being typed ); const TEXT_DECORATION = vscode.languages.registerCompletionItemProvider( 'html', { provideCompletionItems(document: vscode.TextDocument, position: vscode.Position) { const linePrefix = document.lineAt(position).text.substr(0, position.character); if (!linePrefix.endsWith('textDecoration=')) { return undefined; } return [ new vscode.CompletionItem('none', vscode.CompletionItemKind.Value), new vscode.CompletionItem('underline', vscode.CompletionItemKind.Value), new vscode.CompletionItem('line-through', vscode.CompletionItemKind.Value), ]; }, }, '=', // triggered whenever a '.' is being typed ); const TEXT_TRANSFORM = vscode.languages.registerCompletionItemProvider( 'html', { provideCompletionItems(document: vscode.TextDocument, position: vscode.Position) { const linePrefix = document.lineAt(position).text.substr(0, position.character); if (!linePrefix.endsWith('textTransform=')) { return undefined; } return [ new vscode.CompletionItem('none', vscode.CompletionItemKind.Value), new vscode.CompletionItem('capitalize', vscode.CompletionItemKind.Value), new vscode.CompletionItem('uppercase', vscode.CompletionItemKind.Value), new vscode.CompletionItem('lowercase', vscode.CompletionItemKind.Value), ]; }, }, '=', // triggered whenever a '.' is being typed ); const DOCK = vscode.languages.registerCompletionItemProvider( 'html', { provideCompletionItems(document: vscode.TextDocument, position: vscode.Position) { const linePrefix = document.lineAt(position).text.substr(0, position.character); if (!linePrefix.endsWith('dock=')) { return undefined; } return [ new vscode.CompletionItem('top', vscode.CompletionItemKind.Value), new vscode.CompletionItem('left', vscode.CompletionItemKind.Value), new vscode.CompletionItem('right', vscode.CompletionItemKind.Value), new vscode.CompletionItem('bottom', vscode.CompletionItemKind.Value), ]; }, }, '=', // triggered whenever a '.' is being typed ); const STRETCH = vscode.languages.registerCompletionItemProvider( 'html', { provideCompletionItems(document: vscode.TextDocument, position: vscode.Position) { const linePrefix = document.lineAt(position).text.substr(0, position.character); if (!linePrefix.endsWith('stretch=')) { return undefined; } return [ new vscode.CompletionItem('aspectFit', vscode.CompletionItemKind.Value), new vscode.CompletionItem('none', vscode.CompletionItemKind.Value), new vscode.CompletionItem('fill', vscode.CompletionItemKind.Value), new vscode.CompletionItem('aspectFill', vscode.CompletionItemKind.Value), ]; }, }, '=', // triggered whenever a '.' is being typed ); const VISIBILITY = vscode.languages.registerCompletionItemProvider( 'html', { provideCompletionItems(document: vscode.TextDocument, position: vscode.Position) { const linePrefix = document.lineAt(position).text.substr(0, position.character); if (!linePrefix.endsWith('visibility=')) { return undefined; } return [ new vscode.CompletionItem('visible', vscode.CompletionItemKind.Value), new vscode.CompletionItem('collapsed', vscode.CompletionItemKind.Value), new vscode.CompletionItem('hidden', vscode.CompletionItemKind.Value), ]; }, }, '=', // triggered whenever a '.' is being typed ); const VERTICAL_ALIGNMENT = vscode.languages.registerCompletionItemProvider( 'html', { provideCompletionItems(document: vscode.TextDocument, position: vscode.Position) { const linePrefix = document.lineAt(position).text.substr(0, position.character); if (!linePrefix.endsWith('verticalAlignment=')) { return undefined; } return [ new vscode.CompletionItem('stretch', vscode.CompletionItemKind.Value), new vscode.CompletionItem('top', vscode.CompletionItemKind.Value), new vscode.CompletionItem('center', vscode.CompletionItemKind.Value), new vscode.CompletionItem('middle', vscode.CompletionItemKind.Value), new vscode.CompletionItem('bottom', vscode.CompletionItemKind.Value), ]; }, }, '=', // triggered whenever a '.' is being typed ); const HORIZONTAL_ALIGNMENT = vscode.languages.registerCompletionItemProvider( 'html', { provideCompletionItems(document: vscode.TextDocument, position: vscode.Position) { const linePrefix = document.lineAt(position).text.substr(0, position.character); if (!linePrefix.endsWith('horizontalAlignment=')) { return undefined; } return [ new vscode.CompletionItem('stretch', vscode.CompletionItemKind.Value), new vscode.CompletionItem('center', vscode.CompletionItemKind.Value), new vscode.CompletionItem('left', vscode.CompletionItemKind.Value), new vscode.CompletionItem('right', vscode.CompletionItemKind.Value), ]; }, }, '=', // triggered whenever a '.' is being typed ); export const SUGGESTION_PROVIDERS = [ IOS_SUGGESTION, KEYBOARD_TYPE_SUGGESTION, AUTOCAPITALIZATION, RETURN_KEY, TAB_BACKGROUND_COLOR, TAB_TEXT_COLOR, SELECTED_TAB_TEXT_COLOR, ORIENTATION, FONT_STYLE, TEXT_ALIGNMENT, TEXT_DECORATION, TEXT_TRANSFORM, DOCK, STRETCH, VISIBILITY, VERTICAL_ALIGNMENT, HORIZONTAL_ALIGNMENT, ];
the_stack
import path = require("path"); import fs = require("fs"); import ts = require("typescript"); import Hjson = require("hjson"); import collectClassInfo from "./collectClassInfo"; import { generateMethods, generateSettingsInterface, addLineBreakBefore, } from "./astGenerationHelper"; import astToString from "./astToString"; import log from "loglevel"; const interestingBaseClasses: { [key: string]: | "ManagedObject" | "EventProvider" | "Element" | "Control" | undefined; } = { '"sap/ui/base/ManagedObject".ManagedObject': "ManagedObject", '"sap/ui/base/EventProvider".EventProvider': "EventProvider", '"sap/ui/core/Element".UI5Element': "Element", '"sap/ui/core/Control".Control': "Control", }; /** * Checks the given source file for any classes derived from sap.ui.base.ManagedObject and generates for each one an interface file next to the source file * with the name <className>.generated.tsinterface.ts * * @param sourceFile * @param typeChecker * @param allKnownGlobals * @param {function} [resultProcessor] * * @public */ function generateInterfaces( sourceFile: ts.SourceFile, typeChecker: ts.TypeChecker, allKnownGlobals: GlobalToModuleMapping, resultProcessor: ( sourceFileName: string, className: string, interfaceText: string ) => void = writeInterfaceFile ) { const mos = getManagedObjects(sourceFile, typeChecker); mos.forEach((managedObjectOccurrence) => { const interfaceText = generateInterface( managedObjectOccurrence, allKnownGlobals ); // only returns the interface text if actually needed (it's not for ManagedObjects without metadata etc.) if (interfaceText) { resultProcessor( sourceFile.fileName, managedObjectOccurrence.className, interfaceText ); } }); } /** * * @param sourceFileName the complete path and name of the original source file, so the generated file can be placed next to it * @param className the name of the class for which the interface shall be generated (there may be several classes within one sourceFile) * @param interfaceText the interface file content to write */ function writeInterfaceFile( sourceFileName: string, className: string, interfaceText: string ) { // file output const pathName = path.dirname(sourceFileName); const newFileName = path.join( pathName, className + ".generated.tsinterface.ts" ); log.info(`Writing interface file: ${newFileName}\n\n`); fs.writeFileSync(newFileName, interfaceText); } function getManagedObjects( sourceFile: ts.SourceFile, typeChecker: ts.TypeChecker ) { const managedObjects: ManagedObjectInfo[] = []; sourceFile.statements.forEach((statement) => { if (ts.isClassDeclaration(statement)) { let managedObjectFound = false; statement.heritageClauses && statement.heritageClauses.forEach((heritageClause) => { heritageClause.types && heritageClause.types.forEach((typeNode) => { const type = typeChecker.getTypeFromTypeNode(typeNode); const symbol = type.getSymbol(); if (!symbol) { throw new Error( "Type '" + typeNode.getText() + "' in " + sourceFile.fileName + " could not be resolved - are the UI5 (and other) type definitions available and known in the tsconfig? Or is there a different reason why this type would not be known?" ); } const settingsTypeNode = getSettingsType(type); if (settingsTypeNode) { const settingsType = typeChecker.getTypeFromTypeNode(settingsTypeNode); const symbol = settingsType.getSymbol(); const settingsTypeFullName = typeChecker.getFullyQualifiedName(symbol); const interestingBaseClass = getInterestingBaseClass( type, typeChecker ); if (interestingBaseClass) { managedObjectFound = true; const constructorSignaturesAvailable = checkConstructors(statement); managedObjects.push({ sourceFile, className: statement.name ? statement.name.text : "", classDeclaration: statement, settingsTypeFullName, interestingBaseClass, constructorSignaturesAvailable, }); return; } } }); if (managedObjectFound) { // do not look at any other heritage clauses return; } }); } }); return managedObjects; } // checks for the presence of the standard constructor signatures, so the tool can report them as missing function checkConstructors(classDeclaration: ts.ClassDeclaration) { let singleParameterDeclarationFound = false, doubleParameterDeclarationFound = false, implementationFound = false; classDeclaration.members.forEach((member: ts.ClassElement) => { if (ts.isConstructorDeclaration(member)) { if (member.parameters.length === 1 && member.body === undefined) { const parameter = member.parameters[0]; if (parameter.questionToken && ts.isUnionTypeNode(parameter.type)) { if (parameter.type.types.length === 2) { if ( isOneAStringAndTheOtherASettingsObject( parameter.type.types[0], parameter.type.types[1] ) ) { singleParameterDeclarationFound = true; } } } } else if (member.parameters.length === 2) { if ( isOneAStringAndTheOtherASettingsObject( member.parameters[0].type, member.parameters[1].type ) ) { if (member.body) { implementationFound = true; } else { doubleParameterDeclarationFound = true; } } } else { log.warn( `Unexpected constructor signature with a parameter number other than 1 or 2 in class ${member.parent.name.text}` ); } } }); const found = singleParameterDeclarationFound && doubleParameterDeclarationFound && implementationFound; if (!found) { log.debug( classDeclaration.name.text + " is missing required constructor signatures: " + (singleParameterDeclarationFound ? "" : "\n- constructor declaration with single parameter") + (doubleParameterDeclarationFound ? "" : "\n- constructor declaration with two parameters") + (implementationFound ? "" : "\n- constructor implementation with two parameters") ); } return found; } function isOneAStringAndTheOtherASettingsObject( type1: ts.TypeNode, type2: ts.TypeNode ) { return ( (type1.kind === ts.SyntaxKind.StringKeyword && ts.isTypeReferenceNode(type2)) || // TODO: more specific check for second type (type2.kind === ts.SyntaxKind.StringKeyword && ts.isTypeReferenceNode(type1)) ); } /** * Returns the type of the settings object used in the constructor of the given type * Needed to derive the new settings object type for the subclass from it. * * @param type */ function getSettingsType(type: ts.Type) { const declarations = type.getSymbol().getDeclarations(); const constructors: ts.ConstructorDeclaration[] = []; for (let i = 0; i < declarations.length; i++) { const declaration = declarations[i] as ts.ClassDeclaration; const members = declaration.members; for (let j = 0; j < members.length; j++) { if (ts.isConstructorDeclaration(members[j])) { constructors.push(members[j] as ts.ConstructorDeclaration); } } } let settingsType: ts.TypeNode = null; constructors.forEach((ctor) => { const lastParameter = ctor.parameters[ctor.parameters.length - 1]; //if (settingsType !== null && settingsType.typeName.escapedText !== lastParameter.type.typeName.escapedText) { // TODO // log.warn("different constructors have different settings type") //} if (!lastParameter) { // we deal with arbitrary classes here, so the parent class constructor may well have no parameters. TODO: log a warning when this is actually a ManagedObject: in this case the generator ignores it. return; } if (lastParameter.type.kind === ts.SyntaxKind.TypeReference) { // without this check, we get incorrect settings types from e.g. controllers which have a different constructor structure TODO: check for more deviations settingsType = lastParameter.type; } }); return settingsType; } /** * Returns "ManagedObject", "EventProvider", "Element", "Control" - or undefined */ function getInterestingBaseClass( type: ts.Type, typeChecker: ts.TypeChecker ): "ManagedObject" | "EventProvider" | "Element" | "Control" | undefined { //const typeName = typeChecker.typeToString(type); //log.debug("-> " + typeName + " (" + typeChecker.getFullyQualifiedName(type.getSymbol()) + ")"); let interestingBaseClass = interestingBaseClasses[typeChecker.getFullyQualifiedName(type.getSymbol())]; if (interestingBaseClass) { return interestingBaseClass; } if (!type.isClassOrInterface()) { return; } const baseTypes = typeChecker.getBaseTypes(type); for (let i = 0; i < baseTypes.length; i++) { if ( (interestingBaseClass = getInterestingBaseClass( baseTypes[i], typeChecker )) ) { return interestingBaseClass; } } return undefined; } // const sourceFile = ts.createSourceFile("src/control/MyButton.ts", fs.readFileSync("src/control/MyButton.ts").toString(), ts.ScriptTarget.Latest); function generateInterface( { sourceFile, className, classDeclaration, settingsTypeFullName, interestingBaseClass, constructorSignaturesAvailable, }: { sourceFile: ts.SourceFile; className: string; classDeclaration: ts.ClassDeclaration; settingsTypeFullName: string; interestingBaseClass: | "ManagedObject" | "EventProvider" | "Element" | "Control" | undefined; constructorSignaturesAvailable: boolean; }, allKnownGlobals: GlobalToModuleMapping ) { const fileName = sourceFile.fileName; const metadata: ts.PropertyDeclaration[] = <ts.PropertyDeclaration[]>( classDeclaration.members.filter((member) => { if ( ts.isPropertyDeclaration(member) && ts.isIdentifier(member.name) && member.name.escapedText === "metadata" && member.modifiers && member.modifiers.some((modifier) => { return modifier.kind === ts.SyntaxKind.StaticKeyword; }) ) { return true; } }) ); if (!metadata || metadata.length === 0) { // no metadata? => nothing to do log.debug( `ManagedObject with no metadata in class ${className} inside ${fileName}. This is not necessarily an issue, but if there is a metadata member in this class which *should* be recognized, make sure it has the 'static' keyword!` ); return; } else if (metadata.length > 1) { // no metadata? => nothing to do log.warn( `ManagedObject with ${metadata.length} static metadata members in class ${className} inside ${fileName}. This is unexpected. Ignoring this class.` ); return; } if (!metadata[0].initializer) { log.warn( `Class ${className} inside ${fileName} has a static metadata member without initializer. Please assign the metadata object immediately to have an interface generated for the API. Write: 'static readonly metadata = { ... }'` ); return; } // by now we have something that looks pretty much like a ManagedObject metadata object const metadataText = metadata[0].initializer.getText(sourceFile); let metadataObject: ClassInfo; try { metadataObject = Hjson.parse(metadataText) as ClassInfo; // parse with some fault tolerance: it's not a real JSON object, but JS code which may contain comments and property names which are not enclosed in double quotes } catch (e) { throw new Error( `When parsing the metadata of ${className} in ${fileName}: metadata is no valid JSON and could not be quick-fixed to be. Please make the metadata at least close to valid JSON. In particular, TypeScript type annotations cannot be used. Error: ${ (e as Error).message }` ); } if ( !metadataObject.properties && !metadataObject.aggregations && !metadataObject.associations && !metadataObject.events ) { // No API for which accessors are generated? => no interface needed // FIXME // TODO: constructor may still be needed for inherited properties? return; } log.debug( `\n\nClass ${className} inside ${fileName} inherits from ${interestingBaseClass} and contains metadata.` ); const classInfo = collectClassInfo(metadataObject, className); const moduleName = path.basename(fileName, path.extname(fileName)); const ast = buildAST( classInfo, sourceFile.fileName, constructorSignaturesAvailable, moduleName, settingsTypeFullName, allKnownGlobals ); if (!ast) { // no interface needs to be generated return; } return astToString(ast); } function buildAST( classInfo: ClassInfo, classFileName: string, constructorSignaturesAvailable: boolean, moduleName: string, settingsTypeFullName: string, allKnownGlobals: GlobalToModuleMapping ) { const requiredImports: RequiredImports = {}; const methods = generateMethods(classInfo, requiredImports, allKnownGlobals); if (methods.length === 0) { // nothing needs to be generated! return null; } const settingsInterface = generateSettingsInterface( classInfo, classFileName, constructorSignaturesAvailable, settingsTypeFullName, requiredImports, allKnownGlobals ); const statements: ts.Statement[] = getImports(requiredImports); const myInterface = ts.createInterfaceDeclaration( undefined, [ ts.createModifier(ts.SyntaxKind.ExportKeyword), ts.createModifier(ts.SyntaxKind.DefaultKeyword), ], classInfo.name, undefined, undefined, methods ); addLineBreakBefore(myInterface, 2); // assemble the module declaration const module = ts.createModuleDeclaration( [], [ts.createModifier(ts.SyntaxKind.DeclareKeyword)], ts.createStringLiteral("./" + moduleName), ts.createModuleBlock([settingsInterface, myInterface]) ); if (statements.length > 0) { addLineBreakBefore(module, 2); } statements.push(module); // if needed, assemble the second module declaration if (requiredImports.selfIsUsed) { const myInterface2 = ts.createInterfaceDeclaration( undefined, undefined, classInfo.name, undefined, undefined, methods ); const module2 = ts.createModuleDeclaration( [], [ts.createModifier(ts.SyntaxKind.DeclareKeyword)], ts.createStringLiteral("./" + moduleName), ts.createModuleBlock([myInterface2]) ); addLineBreakBefore(module2, 2); ts.addSyntheticLeadingComment( module2, ts.SyntaxKind.SingleLineCommentTrivia, " this duplicate interface without export is needed to avoid \"Cannot find name '" + classInfo.name + "'\" TypeScript errors above" ); statements.push(module2); } return statements; } function getImports(requiredImports: RequiredImports) { const imports = []; for (const dependencyName in requiredImports) { if (dependencyName === "selfIsUsed") { continue; } const singleImport = requiredImports[dependencyName]; const localNameIdentifier = ts.createIdentifier(singleImport.localName); const namedImportOriginalNameIdentifier = singleImport.exportName && singleImport.localName !== singleImport.exportName ? ts.createIdentifier(singleImport.exportName) : undefined; let importClause; if (singleImport.exportName) { // if we have a named (non-default) export, we need a different import clause (with curly braces around the names to import) let importSpecifier; if (parseFloat(ts.version) >= 4.5) { // TypeScript API changed incompatibly in 4.5 importSpecifier = ts.createImportSpecifier( false /* typeOnly */, namedImportOriginalNameIdentifier, // @ts-ignore after 4.5, createImportSpecifier got a third parameter (in the beginning!). This code shall work with older and newer versions, but as the compile-time error check is considering either <4.5 or >=4.5, one of these lines is recognized as error localNameIdentifier ); } else { // @ts-ignore after 4.5, createImportSpecifier got a third parameter (in the beginning!). This code shall work with older and newer versions, but as the compile-time error check is considering either <4.5 or >=4.5, one of these lines is recognized as error importSpecifier = ts.createImportSpecifier( namedImportOriginalNameIdentifier, localNameIdentifier ); } importClause = ts.createImportClause( undefined, ts.createNamedImports([importSpecifier]) ); } else { importClause = ts.createImportClause( ts.createIdentifier(singleImport.localName), undefined ); // importing the default export, so only the local name matters } imports.push( ts.createImportDeclaration( undefined, undefined, importClause, ts.createStringLiteral(singleImport.moduleName) ) ); } if (!imports.length) { // this would result in an ambient module declaration which doesn't work for us. Enforce some implementation code to make it non-ambient. const importDeclaration = ts.createImportDeclaration( undefined, undefined, ts.createImportClause(ts.createIdentifier("Core"), undefined), ts.createStringLiteral("sap/ui/core/Core") ); ts.addSyntheticTrailingComment( importDeclaration, ts.SyntaxKind.SingleLineCommentTrivia, " dummy import to make this non-ambient" ); imports.push(importDeclaration); } return imports; } export { generateInterfaces };
the_stack
module TDev { function fetchConfigAsync() { if (!Cloud.config.liteVersion) { var storeCfg = r => Object.keys(r).forEach(k => Cloud.config[k] = r[k]); var p = Cloud.getPublicApiAsync("clientconfig") .then(r => { localStorage['clientconfig'] = JSON.stringify(r) storeCfg(r) }) if (localStorage['clientconfig']) { storeCfg(JSON.parse(localStorage['clientconfig'])) p.done() return Promise.as() } else return p.then(() => {}, e => { Util.log("cannot download client config: " + e.message) }); } else return Promise.as() } function initEditorAsync() { SizeMgr.earlyInit(); Util.log("initialize editor"); TheLoadingScreen = new LoadingScreen(); TheEditor = new Editor(); Browser.TheHost = new Browser.Host(); Browser.TheHub = new Browser.Hub(); Browser.TheApiCacheMgr = new Browser.ApiCacheMgr(); allScreens = [TheEditor, Browser.TheHost, Browser.TheHub, TheLoadingScreen]; SVG.loadScriptIcons(ScriptIcons.getScriptIcons()); TDev.Browser.EditorSettings.init(); Util.log("initialize api cache"); return Promise.as() .then(() => LocalProxy.updateShellAsync()) .then(() => LocalProxy.loadCachesAsync()) .then(() => fetchConfigAsync()) .then(() => Browser.TheApiCacheMgr.initAsync()) .then(() => { initScreens(); var upd:HTMLElement = null; if (window.localStorage["lastExceptionMessage"]) { var msg = window.localStorage["lastExceptionMessage"]; window.localStorage.removeItem("lastExceptionMessage"); if (TDev.Browser.EditorSettings.widgets().notifyAppReloaded) upd = div("app-updated", lf("Something went wrong and we reloaded the app")); } if (!upd && window.localStorage["appUpdated"]) { window.localStorage.removeItem("appUpdated"); if (dbg) upd = div("app-updated", lf("The Touch Develop app has been updated.")); } if (upd) { elt("root").appendChild(upd) upd.withClick(() => { upd.removeSelf() }) Util.setTimeout(10000, () => { upd.removeSelf() }) } TheEditor.historyMgr.initialHash(); // needs to be done again after login Browser.TheApiCacheMgr.initWebsocketAsync().done(); window.addEventListener("message", event => { if (External.TheChannel) External.TheChannel.receive(event); }); handleChromeSerial(); Hex.preCacheEmptyExtensionAsync().done(); Cookies.initAsync().done(); }); } function handleChromeSerial() { var buffers: StringMap<string> = {}; var chrome = (<any>window).chrome; if (chrome && chrome.runtime) { var m = /chromeid=([a-z]+)/.exec(window.location.href); var extensionId = m ? m[1] : "cihhkhnngbjlhahcfmhekmbnnjcjdbge" var port = chrome.runtime.connect(extensionId, { name: "micro:bit" }); port.onMessage.addListener(function(msg) { if (msg.type == "serial") { Browser.serialLog = true; var buf = (buffers[msg.id] || "") + msg.data; var i = buf.lastIndexOf("\n"); if (i >= 0) { var msgb = buf.substring(0, i + 1); TDev.RT.App.logEvent(TDev.RT.App.INFO, "serial", msgb, { id: msg.id }); buf = buf.slice(i + 1); } buffers[msg.id] = buf; } }); } } function onlyOneTab() { // implicit web apps don't use the database to // avoid multiple tabs issues if (!TDev.Storage.temporary) { // to avoid races with database storage, // detect multiple tabs and prevent it var id = Random.uniqueId(); window.localStorage["currentTabId"] = id; window.setInterval(() => { if (window.localStorage["currentTabId"] != id && !Util.navigatingAway) { Util.navigateInWindow((<any>window).errorUrl + "#oneTab"); } }, 5000); } } function initScreens():void { allScreens.forEach((s) => s.init()); // Debug.enableFirstChanceException(true); window.addEventListener("resize", Util.catchErrors("windowResize", function () { SizeMgr.applySizes(); })); window.addEventListener("hashchange", Util.catchErrors("hashchange", function (ev) { TheEditor.historyMgr.hashChange(); }), false); window.addEventListener("popstate", Util.catchErrors("popState", function (ev) { if (TheEditor.historyMgr.popState) { TheEditor.historyMgr.popState(ev); } }), false); document.onkeypress = Util.catchErrors("documentKeyPress", (e) => TheEditor.keyMgr.processKey(e)); document.onkeydown = Util.catchErrors("documentKeyDown", (e) => TheEditor.keyMgr.processKey(e)); document.onkeyup = Util.catchErrors("documentKeyUp", (e) => TheEditor.keyMgr.keyUp(e)); function saveState() { TheEditor.saveStateAsync({ forReal: true }).done(); Browser.TheApiCacheMgr.save(); Ticker.saveCurrent() RT.Perf.saveCurrentAsync().done(); } (<any>window).tdevSaveState = saveState; window.onunload = saveState; /* // bad idea for development - refresh key triggers that if (false) { window.onbeforeunload = (e) => { var s = "Any changes will be lost."; if (e) { e.returnValue = s; } return s; }; } */ if (Browser.mobileWebkit) { window.scrollTo(0,1); } SizeMgr.applySizes(); var appCache = window.applicationCache; function markUpdate() { tick(Ticks.appUpdateAvailable); Browser.Host.updateIsWaiting = true; } (<any>window).tdevMarkRefresh = markUpdate; if (appCache.status == appCache.UPDATEREADY) { markUpdate(); tick(Ticks.appQuickUpdate) Browser.Host.tryUpdate(); return; } appCache.addEventListener('updateready', () => { if (appCache.status == appCache.UPDATEREADY) { markUpdate(); } else { tick(Ticks.appNoUpdate); } }, false); onlyOneTab(); } export function initAsync(): Promise { Util.log("baseUrl0: {0}", baseUrl); Util.log("userAgent: {0}", window.navigator.userAgent); Util.log("browser: {0}/{1}/{2}", Browser.browserShortName, Browser.browserVersion, Browser.browserVersion2); if (Browser.isWebkit) { Util.log("Browser: webkit/{0}", Browser.webkitVersion); if (Browser.isMobileSafari) Util.log("Browser: mobileSafari"); } if ((<any>window.navigator).standalone) Util.log("standalone"); statusMsg("page loaded, initializing"); return init2Async() } function init2Async(): Promise { Util.initHtmlExtensions(); Util.initGenericExtensions(); Util.sendPendingBugReports(); Util.log("baseUrl: {0}", baseUrl); var localStorage = window.localStorage; var experimentalVersion = "8"; if (localStorage["experimentalVersion"] != experimentalVersion) { Util.log("updating local storage, '{0}' to '{1}'", localStorage["experimentalVersion"], experimentalVersion); return Storage.clearAsync().then(() => { // hard reset of all storage Util.log("storage clear"); localStorage["experimentalVersion"] = experimentalVersion; return initCoreAsync(); }); } return initCoreAsync(); } function initCoreAsync() { Util.log("setting up flags and knobs"); var url = document.URL; // in debuggerExceptions mode erros are displayed inline in the page, not in window.alert() kind of thing // the "debugger" statement in the handler is also not triggered - we're are assuming the debugger // was attached to begin with and it caught the exception if (/debuggerExceptions/.test(url)) debuggerExceptions = true; if (/withTracing/.test(url)) withTracing = true; if (/enableUndo/.test(url)) TDev.Collab.enableUndo = true; if (/nohub/.test(url) || Cloud.isRestricted()) { TDev.noHub = true; TDev.hubHash = "list:installed-scripts"; } if (/bitvm=0/.test(url)) { Cloud.useNativeCompilation = true; } //if (/endKeywords/.test(url)) Renderer.useEndKeywords = true; if (/lfDebug/.test(url)) Util.translationDebug = true; if (Browser.noStorage || /temporaryStorage/.test(url)) { Browser.supportMemoryTable(true); Storage.temporary = true; } var m = /lang=([a-zA-Z\-]+)/.exec(url) if (m) { Util.setTranslationLanguage(m[1]) } else if (!Util.loadUserLanguageSetting()) { m = /TD_LANG=([\w\-]+)/.exec(document.cookie) if (m) Util.setTranslationLanguage(m[1]) else { var lang = window.navigator.language || window.navigator.userLanguage if (lang) Util.setTranslationLanguage(lang) } } if (Math.random() < 0.05 || /translationTracking/.test(url)) Util.enableTranslationTracking() if (/localTranslationTracking/.test(url)) Util.enableTranslationTracking(true) var m = /translationTracking=([a-zA-Z0-9]+)/.exec(url) if (m) { Util.enableTranslationTracking() Util.translationToken = m[1] } Revisions.parseUrlParameters(url); Ticker.init() RT.Perf.init(TDev.AST.Compiler.version, Cloud.currentReleaseId); tick(Ticks.mainInit); AST.Lexer.init(); var appCache = window.applicationCache; function logAppCacheEvent(ev:Event) { Ticker.dbg("app cache event: {0}, status={1}", ev.type, appCache.status); } [ 'cached', 'checking', 'downloading', 'error', 'noupdate', 'obsolete', 'progress', 'updateready' ].forEach((ev) => appCache.addEventListener(ev, logAppCacheEvent, false)); Cloud._migrate = Login.migrate; World.getScriptMeta = (script) => { var s = AST.Parser.parseScript(script); return s.toMeta(); }; World.mergeScripts = (o, a, b) => AST.mergeScripts(o, a, b).serialize(); World.sanitizeScriptTextForCloud = AST.App.sanitizeScriptTextForCloud; var onBoxSelected = () => { if (!(currentScreen instanceof Editor)) return; var editor: Editor = <Editor>currentScreen; var box = LayoutMgr.instance.getSelectedBox(); if (box === null) return; var id = box.getAstNodeId(); // Live view in the code editor if (!editor.isWallVisible()) { if (id) editor.goToNodeId(id); // Paused view on the main wall } else { LayoutMgr.instance.showBoxMenu(() => { if (id) editor.goToNodeId(id); LayoutMgr.instance.hideBoxMenu(); }); } } LayoutMgr.instance.onBoxSelected = onBoxSelected; var onRendered = () => { if (!(currentScreen instanceof Editor)) return; var editor: Editor = <Editor>currentScreen; var rt = editor.currentRt; // Live view in the code editor if (!editor.isWallVisible()) { LayoutMgr.instance.highlightSelectedBox(); // GUI selection LayoutMgr.instance.highlightRelatedBoxes(); // Code selection // Paused view on the main wall } else if (rt.isStopped()) { LayoutMgr.instance.highlightSelectedBox(); // GUI selection LayoutMgr.instance.refreshBoxMenu(); // Box edit menu } // Otherwise, program is running on the main wall } LayoutMgr.instance.onRendered = onRendered; Util.log("initialize apis"); api.initFrom(); ArtEditor.initEditors(); try { var testProto = div(null, "test"); } catch (e) { Util.reportError("protoError", e, false); Util.setTimeout(1000, () => { Util.navigateInWindow((<any>window).errorUrl + "#prototype"); }) return Promise.as(); } return initEditorAsync(); } function search(query: string) { Browser.TheHost.startSearch(query) } // return at most 5 results function searchResultSuggestions(query: string) : string[] { return Browser.TheHost.quickSearch(query) } function searchPaneVisible(visible: boolean) { // TODO: handle visibility changes } function initJs() { statusMsg("setting up load hook"); window.onload = Util.catchErrors("windowOnLoad", () => { initAsync().done(); }); } function statusMsg(m:string) { if (/dbg/.test(document.URL)) { var e = elt("statusMsg"); if (e) Browser.setInnerHTML(e, m); } } export function updateLoop(id:string, msg:string) { Cloud.transientOfflineMode = true; var updateCnt = 0; var last = window.localStorage["lastForcedUpdate"] if (last) { var diff = Date.now() - parseInt(last) if (diff < 8*3600*1000) { HTML.showProgressNotification(msg + " failed"); return; } } ProgressOverlay.lockAndShow(msg); function checkUpdate() { Browser.Host.tryUpdate(); if (updateCnt++ == 20) { var bug = Ticker.mkBugReport("waitForUpdate", "Cannot update") bug.jsUrl = "fake://" + id + "/main.js"; Util.sendErrorReport(bug); } if (updateCnt >= 30) { ProgressOverlay.hide() window.localStorage["lastForcedUpdate"] = Date.now() ModalDialog.info("couldn't connect to cloud services",lf("{0} failed; we are now using offline mode;\n make sure your internet connection is working",msg)) } else { Util.setTimeout(1000, checkUpdate) } } checkUpdate(); } export function globalInit() { statusMsg("global init 0"); if ((typeof window == "object" && (<any>window).isWebWorker) || !(typeof window == "object" && typeof document == "object" && window.document == document)) { isWebWorker = true; Browser.isHeadless = true; Plugins.initWebWorker(); return; } window.onerror = (errMsg:any, url, lineNumber) => { if (errMsg == "Script error.") return true; // ignore cross domain errors if (url == "chrome://global/content/bindings/videocontrols.xml") return true; // FF bug; ignore if (errMsg == "InvalidStateError") return true; // FF "bug" when running in "private" method and one tries to access IndexedDB Util.reportError(url + ":" + lineNumber, errMsg, false); return true; }; function waitForUpdate(id:string) { if (/releaseid=/.test(document.URL)) return; // this will never update //if (!Cloud.isOnline()) return; try { window.applicationCache.update(); } catch (e) { } updateLoop(id, "updating the web app"); return true; } var mx = /lite=([0-9a-z\.]+)/.exec(document.URL) if (mx && mx[1] != "0") { Cloud.lite = true; Cloud.config.rootUrl = "https://" + mx[1] } if ((<any>window).tdlite) { Cloud.lite = true; if ((<any>window).tdlite == "url") { mx = /^(https?:\/\/[^\/]+)/.exec(document.URL); Cloud.config.rootUrl = mx[1] } else { Cloud.config.rootUrl = (<any>window).tdlite; } var cfg = (<any>window).tdConfig if (cfg) Object.keys(cfg).forEach(k => Cloud.config[k] = cfg[k]) } mx = /microbit=(\w+)/.exec(document.URL) if (mx) Cloud.config.microbitGitTag = mx[1] if (Cloud.lite) (<any>window).rootUrl = Cloud.config.rootUrl; Cloud.fullTD = (!Cloud.lite || /touchdevelop.com/.test(Cloud.config.rootUrl)); if (/httplog=1/.test(document.URL)) { HttpLog.enabled = true; } var ms = document.getElementById("mainScript"); if (ms && (<HTMLScriptElement>ms).src) { Ticker.mainJsName = (<HTMLScriptElement>ms).src; baseUrl = Ticker.mainJsName.replace(/[^\/]*$/, ""); var mm = /\/([0-9]{18}[^\/]*)/.exec(Ticker.mainJsName); if (mm) { Cloud.currentReleaseId = mm[1]; } } World.waitForUpdate = waitForUpdate; statusMsg("global init 1"); Ticker.fillEditorInfoBugReport = (b:BugReport) => { try { b.currentUrl = TheEditor && TheEditor.historyMgr ? TheEditor.historyMgr.currentHash() : ""; b.scriptId = Script ? Script.localGuid : ""; b.userAgent = window.navigator.userAgent; b.resolution = SizeMgr.windowWidth + "x" + SizeMgr.windowHeight; b.platform = Browser.platformCaps; b.worldId = Cloud.getWorldId(); if (TheEditor && TheEditor.undoMgr) { var src = TheEditor.undoMgr.getScriptSource(); if (src) b.attachments.push(src) } } catch (e) { debugger; } }; Ticker.fillEditorInfoTicksReport = (b: TicksReport) => { try { b.worldId = Cloud.getWorldId(); } catch (e) { debugger; } }; // init API keys TDev.RT.ApiManager.bingMapsKey = 'AsnQk63tYReqttLHcIL1RUsc_0h0BwCOib6j0Zvk8QjWs4FQjM9JRM9wEKescphX'; Browser.inEditor = true; statusMsg("global init 2"); if (Browser.inCordova) { // TODO: move all TD code inside of this handler, including browser.js TDev.RT.Cordova.setup(() => { statusMsg("global init deviceready"); initAsync().done(); }); } else if ((<any>window).browserSupported) { statusMsg("global init 4"); initJs(); } else { statusMsg("global init 5"); } } } TDev.globalInit();
the_stack
import { CONFIGS } from './config'; import { MichelsonMap, MichelCodecPacker } from '@taquito/taquito'; import { permit_admin_42_expiry } from './data/permit_admin_42_expiry'; import { permit_admin_42_set } from './data/permit_admin_42_set'; import { permit_fa12_smartpy } from './data/permit_fa12_smartpy'; import { buf2hex, char2Bytes, hex2buf } from '@taquito/utils'; import { tzip16, Tzip16Module } from '@taquito/tzip16'; const blake = require('blakejs'); const bob_address = 'tz1Xk7HkSwHv6dTEgR7E2WC2yFj4cyyuj2Gh'; const errors_to_missigned_bytes = (errors: any[]) => { return errors[1].with.args[1].bytes; }; CONFIGS().forEach(({ lib, rpc, setup, createAddress }) => { const Tezos = lib; Tezos.setPackerProvider(new MichelCodecPacker()); describe(`Test of contracts having a permit for tzip-17: ${rpc}`, () => { beforeEach(async (done) => { await setup(true); done(); }); test('Permit can be submitted and set', async (done) => { const op = await Tezos.contract.originate({ code: permit_admin_42_set, storage: { 0: new MichelsonMap(), 1: 300, 2: bob_address, }, }); await op.confirmation(); expect(op.hash).toBeDefined(); expect(op.includedInBlock).toBeLessThan(Number.POSITIVE_INFINITY); const permit_contract = await op.contract(); expect(op.status).toEqual('applied'); const signer_key = await Tezos.signer.publicKey(); const dummy_sig = 'edsigu5scrvoY2AB7cnHzUd7x7ZvXEMYkArKeehN5ZXNkmfUSkyApHcW5vPcjbuTrnHUMt8mJkWmo8WScNgKL3vu9akFLAXvHxm'; const wrapped_param: any = permit_contract.methods['wrapped'](42).toTransferParams().parameter?.value; const wrapped_param_type = permit_contract.entrypoints.entrypoints['wrapped']; const raw_packed = await Tezos.rpc.packData({ data: wrapped_param, type: wrapped_param_type, }); const packed_param = raw_packed.packed; const param_hash = buf2hex(blake.blake2b(hex2buf(packed_param), null, 32)); const bytes_to_sign = await permit_contract.methods .permit(signer_key, dummy_sig, param_hash) .send() .catch((e) => errors_to_missigned_bytes(e.errors)); //The error here catches the bytes that are needed, so we have to catch the error for later use. const param_sig = await Tezos.signer .sign(bytes_to_sign) .then((s) => s.prefixSig) .catch((error) => console.log(JSON.stringify(error))); const permitMethodCall = await permit_contract.methods .permit(signer_key, param_sig, param_hash) .send(); await permitMethodCall.confirmation(); expect(permitMethodCall.hash).toBeDefined(); expect(permitMethodCall.status).toEqual('applied'); done(); }); test('Originate a permit contract and set expiry', async (done) => { const op = await Tezos.contract.originate({ code: permit_admin_42_expiry, storage: { 0: 300, 1: new MichelsonMap(), 2: 0, 3: bob_address, 4: bob_address, }, }); await op.confirmation(); expect(op.hash).toBeDefined(); expect(op.includedInBlock).toBeLessThan(Number.POSITIVE_INFINITY); const expiry_contract = await op.contract(); expect(op.status).toEqual('applied'); const setExpiryMethodCall = await expiry_contract.methods .setExpiry( null, //bytes await Tezos.signer.publicKeyHash(), //address of current signer 42 // nat ) .send(); await setExpiryMethodCall.confirmation(); expect(setExpiryMethodCall.hash).toBeDefined(); expect(setExpiryMethodCall.status).toEqual('applied'); done(); }); test('Originate a permit contract and set defaultExpiry', async (done) => { const op = await Tezos.contract.originate({ code: permit_admin_42_expiry, storage: { 0: 300, 1: new MichelsonMap(), 2: 0, 3: await Tezos.signer.publicKeyHash(), 4: await Tezos.signer.publicKeyHash(), }, }); await op.confirmation(); expect(op.hash).toBeDefined(); expect(op.includedInBlock).toBeLessThan(Number.POSITIVE_INFINITY); const defaultExpiry_contract = await op.contract(); expect(op.status).toEqual('applied'); const defaultExpiryMethodCall = await defaultExpiry_contract.methods .defaultExpiry( 100 // nat ) .send(); await defaultExpiryMethodCall.confirmation(); expect(defaultExpiryMethodCall.hash).toBeDefined(); expect(defaultExpiryMethodCall.status).toEqual('applied'); done(); }); test('Originate a permit fa1.2 contract with metadata views', async (done) => { const url = 'https://storage.googleapis.com/tzip-16/permit_metadata.json'; const bytesUrl = char2Bytes(url); const metadata = new MichelsonMap(); metadata.set('', bytesUrl); const op = await Tezos.contract.originate({ code: permit_fa12_smartpy, storage: { administrator: await Tezos.signer.publicKeyHash(), balances: new MichelsonMap(), counter: '0', default_expiry: '50000', max_expiry: '2628000', metadata: metadata, paused: false, permit_expiries: new MichelsonMap(), permits: new MichelsonMap(), totalSupply: '0', user_expiries: new MichelsonMap(), }, }); await op.confirmation(); expect(op.hash).toBeDefined(); expect(op.includedInBlock).toBeLessThan(Number.POSITIVE_INFINITY); const fa12_contract = await op.contract(); const contractAddress = fa12_contract.address; expect(op.status).toEqual('applied'); const mint_amount = 42; const setMintMethodCall = await fa12_contract.methods .mint( await Tezos.signer.publicKeyHash(), //address :to mint_amount // nat :value ) .send(); await setMintMethodCall.confirmation(); expect(setMintMethodCall.hash).toBeDefined(); expect(setMintMethodCall.status).toEqual('applied'); const storage: any = await fa12_contract.storage(); expect(storage['totalSupply'].toString()).toEqual('42'); Tezos.addExtension(new Tzip16Module()); const contract = await Tezos.contract.at(contractAddress, tzip16); const contract_metadata = await contract.tzip16().getMetadata(); expect(contract_metadata.uri).toEqual(url); expect(contract_metadata.integrityCheckResult).toBeUndefined(); expect(contract_metadata.sha256Hash).toBeUndefined(); const views = await contract.tzip16().metadataViews(); const viewGetCounterResult = await views.GetCounter().executeView('Unit'); expect(viewGetCounterResult.toString()).toEqual('0'); const viewGetDefaultExpiryResult = await views.GetDefaultExpiry().executeView('Unit'); expect(viewGetDefaultExpiryResult.toString()).toEqual('50000'); done(); }); describe(`Test of contracts having a permit for tzip-17: ${rpc}`, () => { beforeEach(async (done) => { await setup(true); done(); }); test('Show that any user can submit the permit hash to use an entrypoint', async (done) => { //following https://github.com/EGuenz/smartpy-permits const LocalTez1 = await createAddress(); const bootstrap1_address = await LocalTez1.signer.publicKeyHash(); const funding_op1 = await Tezos.contract.transfer({ to: bootstrap1_address, amount: 0.5, }); await funding_op1.confirmation(); const LocalTez2 = await createAddress(); const bootstrap2_address = await LocalTez2.signer.publicKeyHash(); const funding_op2 = await Tezos.contract.transfer({ to: bootstrap2_address, amount: 0.5, }); await funding_op2.confirmation(); const LocalTez3 = await createAddress(); const bootstrap3_address = await LocalTez3.signer.publicKeyHash(); const funding_op3 = await Tezos.contract.transfer({ to: bootstrap3_address, amount: 0.5, }); await funding_op3.confirmation(); const LocalTez4 = await createAddress(); const bootstrap4_address = await LocalTez4.signer.publicKeyHash(); const funding_op4 = await Tezos.contract.transfer({ to: bootstrap4_address, amount: 0.5, }); await funding_op4.confirmation(); //Originate permit-fa1.2 contract with bootstrap1_address as administrator const url = 'https://storage.googleapis.com/tzip-16/permit_metadata.json'; const bytesUrl = char2Bytes(url); const metadata = new MichelsonMap(); metadata.set('', bytesUrl); const op = await Tezos.contract.originate({ code: permit_fa12_smartpy, storage: { administrator: await LocalTez1.signer.publicKeyHash(), balances: new MichelsonMap(), counter: '0', default_expiry: '50000', max_expiry: '2628000', metadata: metadata, paused: false, permit_expiries: new MichelsonMap(), permits: new MichelsonMap(), totalSupply: '100', user_expiries: new MichelsonMap(), }, }); await op.confirmation(); expect(op.hash).toBeDefined(); expect(op.includedInBlock).toBeLessThan(Number.POSITIVE_INFINITY); const fa12_contract = await op.contract(); const contractAddress = fa12_contract.address; expect(op.status).toEqual('applied'); //Mint 10 tokens to bootstrap 2 const mint_contract = await LocalTez1.contract.at(fa12_contract.address); const mint = await mint_contract.methods.mint(bootstrap2_address, 10).send(); expect(mint.hash).toBeDefined(); expect(mint.status).toEqual('applied'); await mint.confirmation(); //Observe transfer by non bootstrap2 sender fails const fail_contract = await LocalTez4.contract.at(fa12_contract.address); try { await fail_contract.methods.transfer(bootstrap3_address, bootstrap4_address, 1).send(); } catch (errors) { let jsonStr: string = JSON.stringify(errors); let jsonObj = JSON.parse(jsonStr); let error_code = JSON.stringify(jsonObj.errors[1].with.int); expect((error_code = '26')); } //Define a fake permit parameter to get the expected unsigned bytes const transfer_param: any = fa12_contract.methods['transfer']( bootstrap2_address, bootstrap3_address, 1 ).toTransferParams().parameter?.value; const type = fa12_contract.entrypoints.entrypoints['transfer']; const TRANSFER_PARAM_PACKED = await Tezos.rpc.packData({ data: transfer_param, type: type, }); //Get the BLAKE2B of TRANSFER_PARAM_PACKED const packed_param = TRANSFER_PARAM_PACKED.packed; const TRANSFER_PARAM_HASHED = buf2hex(blake.blake2b(hex2buf(packed_param), null, 32)); //Set a random signature const RAND_SIG = 'edsigtfkWys7vyeQy1PnHcBuac1dgj2aJ8Jv3fvoDE5XRtxTMRgJBwVgMTzvhAzBQyjH48ux9KE8jRZBSk4Rv2bfphsfpKP3ggM'; //Get Bootstrap2's public_key and capture it const PUB_KEY = await LocalTez2.signer.publicKey(); //Set Fake permit param //PERMIT_PARAM_FAKE="{Pair \"$PUB_KEY\" (Pair \"$RAND_SIG\" $TRANSFER_PARAM_HASHED)}" //Set MISSIGNED with bytes returned in error message of fake permit submission const trial_permit_contract = await LocalTez4.contract.at(fa12_contract.address); const bytes_to_sign = await trial_permit_contract.methods .permit([ { 0: PUB_KEY, //key, 1: RAND_SIG, //signature 2: TRANSFER_PARAM_HASHED, //bytes }, ]) .send() .catch((e) => errors_to_missigned_bytes(e.errors)); //Sign MISSIGNED bytes for bootstrap_address2 const SIGNATURE = await LocalTez2.signer.sign(bytes_to_sign).then((s) => s.prefixSig) .catch((error) => console.log(JSON.stringify(error))); //Craft correct permit parameter //PERMIT_PARAM="{Pair \"$PUB_KEY\" (Pair \"$SIGNATURE\" $TRANSFER_PARAM_HASHED)}" //Anyone can submit permit start const signed_permit_contract = await LocalTez4.contract.at(fa12_contract.address); const permit_contract = await signed_permit_contract.methods .permit([ { 0: PUB_KEY, //key, 1: SIGNATURE, //signature 2: TRANSFER_PARAM_HASHED, //bytes }, ]) .send(); await permit_contract.confirmation(); expect(permit_contract.hash).toBeDefined(); expect(permit_contract.status).toEqual('applied'); //Successfully execute transfer away from bootstrap2 by calling transfer endpoint from any account const successful_transfer = await signed_permit_contract.methods .transfer(bootstrap2_address, bootstrap3_address, 1) .send(); await successful_transfer.confirmation(); expect(successful_transfer.hash).toBeDefined(); expect(successful_transfer.status).toEqual('applied'); done(); }); }); }); });
the_stack
declare module "fs" { /** * File system flag that controls opening of a file. * * - `'a'` - Open a file for appending. The file is created if it does not exist. * - `'ax'` - The same as `'a'` but fails if the file already exists. * - `'a+'` - Open a file for reading and appending. If the file does not exist, it will be created. * - `'ax+'` - The same as `'a+'` but fails if the file already exists. * - `'as'` - Open a file for appending in synchronous mode. If the file does not exist, it will be created. * - `'as+'` - Open a file for reading and appending in synchronous mode. If the file does not exist, it will be created. * - `'r'` - Open a file for reading. An exception occurs if the file does not exist. * - `'r+'` - Open a file for reading and writing. An exception occurs if the file does not exist. * - `'rs+'` - Open a file for reading and writing in synchronous mode. Instructs the operating system to bypass the local file system cache. * - `'w'` - Open a file for writing. If the file does not exist, it will be created. If the file exists, it will be replaced. * - `'wx'` - The same as `'w'` but fails if the file already exists. * - `'w+'` - Open a file for reading and writing. If the file does not exist, it will be created. If the file exists, it will be replaced. * - `'wx+'` - The same as `'w+'` but fails if the file already exists. */ export type OpenMode = "a" | "ax" | "a+" | "ax+" | "as" | "as+" | "r" | "r+" | "rs+" | "w" | "wx" | "w+" | "wx+"; export type FileEncoding = BufferEncoding; /** * Valid types for path values in "fs". */ export type PathLike = string | Buffer; /** * A representation of a directory entry - a file or a subdirectory. * * When `readdirSync()` is called with the `withFileTypes` option, the resulting array contains * `fs.Dirent` objects. */ export interface Dirent { /** * @returns `true` if the object describes a block device. */ isBlockDevice(): boolean; /** * @returns `true` if the object describes a character device. */ isCharacterDevice(): boolean; /** * @returns `true` if the object describes a file system directory. */ isDirectory(): boolean; /** * @returns `true` if the object describes a first-in-first-out (FIFO) pipe. */ isFIFO(): boolean; /** * @returns `true` if the object describes a regular file. */ isFile(): boolean; /** * @returns `true` if the object describes a socket. */ isSocket(): boolean; /** * @returns `true` if the object describes a symbolic link. */ isSymbolicLink(): boolean; /** * The name of the file this object refers to. */ name: string; } type WriteFileOptions = { mode?: number; flag?: OpenMode; }; type Constants = { /** * Indicates that the file is visible to the calling process, used by default if no mode * is specified. */ F_OK: 0; /** * Indicates that the file can be read by the calling process. */ R_OK: 4; /** * Indicates that the file can be written by the calling process. */ W_OK: 2; /** * Indicates that the file can be executed by the calling process. */ X_OK: 1; }; interface Promises { /** * Asynchronously tests permissions for a file or directory specified in the `path`. * If the check fails, an error will be returned, otherwise, the method will return undefined. * * @example * import fs from 'fs' * fs.promises.access('/file/path', fs.constants.R_OK | fs.constants.W_OK) * .then(() => console.log('has access')) * .catch(() => console.log('no access')) * * @since 0.3.9 * @param path A path to a file or directory. * @param mode An optional integer that specifies the accessibility checks to be performed. * Defaults to `fs.constants.F_OK`. */ access(path: PathLike, mode?: number): Promise<void>; /** * Asynchronously appends specified `data` to a file with provided `filename`. * If the file does not exist, it will be created. * * @since 0.4.4 * @param path A path to a file. * @param data The data to write. * @param options An object optionally specifying the file mode and flag. * If `mode` is not supplied, the default of `0o666` is used. * If `flag` is not supplied, the default of `'a'` is used. */ appendFile(path: PathLike, data: NjsStringOrBuffer, options?: WriteFileOptions): Promise<void>; /** * Asynchronously creates a directory at the specified `path`. * * @since 0.4.2 * @param path A path to a file. * @param options The file mode (or an object specifying the file mode). Defaults to `0o777`. */ mkdir(path: PathLike, options?: { mode?: number } | number): Promise<void>; /** * Asynchronously reads the contents of a directory at the specified `path`. * * @since 0.4.2 * @param path A path to a file. * @param options A string that specifies encoding or an object optionally specifying * the following keys: * - `encoding` - `'utf8'` (default) or `'buffer'` (since 0.4.4) * - `withFileTypes` - if set to `true`, the files array will contain `fs.Dirent` objects; defaults to `false`. */ readdir(path: PathLike, options?: { encoding?: "utf8"; withFileTypes?: false; } | "utf8"): Promise<string[]>; readdir(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false; } | "buffer"): Promise<Buffer[]>; readdir(path: PathLike, options: { encoding?: "utf8" | "buffer"; withFileTypes: true; }): Promise<Dirent[]>; /** * Asynchronously returns the contents of the file with provided `filename`. * If an encoding is specified, a `string` is returned, otherwise, a `Buffer`. * * @param path A path to a file. * @param options A string that specifies encoding or an object with the following optional keys: * - `encoding` - `'utf8'`, `'hex'`, `'base64'`, or `'base64url'` (the last three since 0.4.4). * - `flag` - file system flag, defaults to `r`. */ readFile(path: PathLike): Promise<Buffer>; readFile(path: PathLike, options?: { flag?: OpenMode; }): Promise<Buffer>; readFile(path: PathLike, options: { encoding?: FileEncoding; flag?: OpenMode; } | FileEncoding): Promise<string>; /** * Asynchronously computes the canonical pathname by resolving `.`, `..` and symbolic links using * `realpath(3)`. * * @since 0.3.9 * @param path A path to a file. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. */ realpath(path: PathLike, options?: { encoding?: "utf8" } | "utf8"): Promise<string>; realpath(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise<Buffer>; /** * Asynchronously changes the name or location of a file from `oldPath` to `newPath`. * * @since 0.3.4 * @param oldPath A path to a file. * @param newPath A path to a file. */ rename(oldPath: PathLike, newPath: PathLike): Promise<void>; /** * Asynchronously removes a directory at the specified `path`. * * @since 0.4.2 * @param path A path to a file. */ rmdir(path: PathLike): Promise<void>; /** * Asynchronously creates the link called `path` pointing to `target` using `symlink(2)`. * Relative targets are relative to the link’s parent directory. * * @since 0.3.9 * @param target A path to an existing file. * @param path A path to the new symlink. */ symlink(target: PathLike, path: PathLike): Promise<void>; /** * Asynchronously unlinks a file by `path`. * * @since 0.3.9 * @param path A path to a file. */ unlink(path: PathLike): Promise<void>; /** * Asynchronously writes `data` to a file with provided `filename`. If the file does not * exist, it will be created, if the file exists, it will be replaced. * * @since 0.4.4 * @param path A path to a file. * @param data The data to write. * @param options An object optionally specifying the file mode and flag. * If `mode` is not supplied, the default of `0o666` is used. * If `flag` is not supplied, the default of `'w'` is used. */ writeFile(path: PathLike, data: NjsStringOrBuffer, options?: WriteFileOptions): Promise<void>; } interface NjsFS { /** * Promissified versions of file system methods. * * @since 0.3.9 */ promises: Promises /** * File Access Constants */ constants: Constants /** * Synchronously tests permissions for a file or directory specified in the `path`. * If the check fails, an error will be returned, otherwise, the method will return undefined. * * @example * try { * fs.accessSync('/file/path', fs.constants.R_OK | fs.constants.W_OK); * console.log('has access'); * } catch (e) { * console.log('no access'); * } * * @since 0.3.9 * @param path A path to a file or directory. * @param mode An optional integer that specifies the accessibility checks to be performed. * Defaults to `fs.constants.F_OK`. */ accessSync(path: PathLike, mode?: number): void; /** * Synchronously appends specified `data` to a file with provided `filename`. * If the file does not exist, it will be created. * * @since 0.4.4 * @param path A path to a file. * @param data The data to write. * @param options An object optionally specifying the file mode and flag. * If `mode` is not supplied, the default of `0o666` is used. * If `flag` is not supplied, the default of `'a'` is used. */ appendFileSync(path: PathLike, data: NjsStringOrBuffer, options?: WriteFileOptions): void; /** * Synchronously creates a directory at the specified `path`. * * @since 0.4.2 * @param path A path to a file. * @param options The file mode (or an object specifying the file mode). Defaults to `0o777`. */ mkdirSync(path: PathLike, options?: { mode?: number } | number): void; /** * Synchronously reads the contents of a directory at the specified `path`. * * @since 0.4.2 * @param path A path to a file. * @param options A string that specifies encoding or an object optionally specifying * the following keys: * - `encoding` - `'utf8'` (default) or `'buffer'` (since 0.4.4) * - `withFileTypes` - if set to `true`, the files array will contain `fs.Dirent` objects; * defaults to `false`. */ readdirSync(path: PathLike, options?: { encoding?: "utf8"; withFileTypes?: false; } | "utf8"): string[]; readdirSync(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false; } | "buffer"): Buffer[]; readdirSync(path: PathLike, options: { encoding?: "utf8" | "buffer"; withFileTypes: true; }): Dirent[]; /** * Synchronously returns the contents of the file with provided `filename`. * If an encoding is specified, a `string` is returned, otherwise, a `Buffer`. * * @example * import fs from 'fs' * var file = fs.readFileSync('/file/path.tar.gz') * var gzipped = file.slice(0,2).toString('hex') === '1f8b'; gzipped // => true * * @param path A path to a file. * @param options A string that specifies encoding or an object with the following optional keys: * - `encoding` - `'utf8'`, `'hex'`, `'base64'`, or `'base64url'` (the last three since 0.4.4). * - `flag` - file system flag, defaults to `r`. */ readFileSync(path: PathLike): Buffer; readFileSync(path: PathLike, options?: { flag?: OpenMode; }): Buffer; readFileSync(path: PathLike, options: { encoding?: FileEncoding; flag?: OpenMode; } | FileEncoding): string; /** * Synchronously computes the canonical pathname by resolving `.`, `..` and symbolic links using * `realpath(3)`. * * @since 0.3.9 * @param path A path to a file. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. */ realpathSync(path: PathLike, options?: { encoding?: "utf8" } | "utf8"): string; realpathSync(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; /** * Synchronously changes the name or location of a file from `oldPath` to `newPath`. * * @example * import fs from 'fs' * var file = fs.renameSync('hello.txt', 'HelloWorld.txt') * * @since 0.3.4 * @param oldPath A path to a file. * @param newPath A path to a file. */ renameSync(oldPath: PathLike, newPath: PathLike): void; /** * Synchronously removes a directory at the specified `path`. * * @since 0.4.2 * @param path A path to a file. */ rmdirSync(path: PathLike): void; /** * Synchronously creates the link called `path` pointing to `target` using `symlink(2)`. * Relative targets are relative to the link’s parent directory. * * @since 0.3.9 * @param target A path to an existing file. * @param path A path to the new symlink. */ symlinkSync(target: PathLike, path: PathLike): void; /** * Synchronously unlinks a file by `path`. * * @since 0.3.9 * @param path A path to a file. */ unlinkSync(path: PathLike): void; /** * Synchronously writes `data` to a file with provided `filename`. If the file does not exist, * it will be created, if the file exists, it will be replaced. * * @example * import fs from 'fs' * fs.writeFileSync('hello.txt', 'Hello world') * * @since 0.4.4 * @param path A path to a file. * @param data The data to write. * @param options An object optionally specifying the file mode and flag. * If `mode` is not supplied, the default of `0o666` is used. * If `flag` is not supplied, the default of `'w'` is used. */ writeFileSync(path: PathLike, data: NjsStringOrBuffer, options?: WriteFileOptions): void; } const fs: NjsFS; // It's exported like this because njs doesn't support named imports. // TODO: Replace NjsFS with individual named exports as soon as njs supports named imports. export default fs; }
the_stack
import type { ObjectFixedUnionToIntersectionByKeys, UpdateToSetExpressionMethod, ObjectFixedKeys, UpdateFieldDescriptor, } from './types' const empty = (Symbol('empty') as unknown) as null const updateToSetExpression: UpdateToSetExpressionMethod = ( expression, escapeId, escapeStr, makeNestedPath, splitNestedPath ) => { const updatingFieldsDescriptors = new Set<UpdateFieldDescriptor>() const updatingFields = new Map<string, UpdateFieldDescriptor>() const errors: Array<Error> = [] for (let operatorName of Object.keys(expression) as Array< ObjectFixedKeys<typeof expression> >) { if ( !( operatorName === '$set' || operatorName === '$unset' || operatorName === '$inc' ) ) { errors.push(new Error(`Update operator "${operatorName}" is invalid`)) continue } const extractedExpression = (expression as ObjectFixedUnionToIntersectionByKeys< typeof expression, typeof operatorName >)[operatorName] for (let fieldName of Object.keys(extractedExpression)) { const fieldValue = extractedExpression[fieldName] const [baseName, ...nestedPath] = splitNestedPath(fieldName) let updatingFieldLevelMap = updatingFields let updatingFieldDescriptor: | UpdateFieldDescriptor | null | undefined = null for (const partName of [baseName, ...nestedPath]) { if (!updatingFieldLevelMap.has(partName)) { updatingFieldLevelMap.set(partName, { key: updatingFieldDescriptor !== empty && updatingFieldDescriptor != null ? `${updatingFieldDescriptor.key}.${partName}` : partName, nestedKey: nestedPath, baseName, selectedOperation: empty, children: new Map(), $set: empty, $unset: empty, $inc: empty, }) } updatingFieldDescriptor = updatingFieldLevelMap.get( partName ) as UpdateFieldDescriptor updatingFieldLevelMap = updatingFieldDescriptor.children updatingFieldsDescriptors.add(updatingFieldDescriptor) } void (((updatingFieldDescriptor as UpdateFieldDescriptor)[ operatorName ] as typeof fieldValue) = fieldValue) } } for (const descriptor of updatingFieldsDescriptors) { const flags = { unset: descriptor['$unset'] !== empty, set: descriptor['$set'] !== empty, inc: descriptor['$inc'] !== empty, child: descriptor.children.size > 0, } if (Object.values(flags).reduce((acc, flag) => +flag + acc, 0) !== 1) { errors.push( new Error( [ `Updating set for key "${descriptor.key}" came into conflict: `, `either key includes "$set", "$unset", "$inc" simultaneously, `, `either key has children update nodes`, ].join('') ) ) } switch (true) { case flags.unset: descriptor.selectedOperation = '$unset' descriptor['$set'] = empty // eslint-disable-next-line no-fallthrough case flags.set: descriptor.selectedOperation = descriptor.selectedOperation !== empty ? descriptor.selectedOperation : '$set' descriptor['$inc'] = empty // eslint-disable-next-line no-fallthrough case flags.inc: descriptor.selectedOperation = descriptor.selectedOperation !== empty ? descriptor.selectedOperation : '$inc' descriptor.children.clear() // eslint-disable-next-line no-fallthrough default: break } } for (const descriptor of updatingFieldsDescriptors) { if (descriptor.children.size !== 0) { continue } const baseDescriptor = updatingFields.get( descriptor.baseName ) as UpdateFieldDescriptor const operationName = descriptor.selectedOperation const fieldValue = operationName !== empty && operationName != null ? descriptor[operationName] : empty if (fieldValue === empty) { errors.push(new Error(`Empty field value at ${descriptor.key}`)) } const operation: { operationName: typeof operationName fieldValue: typeof fieldValue nestedPath?: typeof descriptor.nestedKey } = { operationName, fieldValue } if (descriptor.nestedKey.length > 0) { operation.nestedPath = descriptor.nestedKey } if (baseDescriptor === descriptor) { baseDescriptor.operations = operation } else if (Array.isArray(baseDescriptor.operations)) { baseDescriptor.operations.push(operation) } else { baseDescriptor.operations = [operation] } } let inlineTableNameIdx = 0 const updateOperations = new Map< string, UpdateFieldDescriptor['operations'] >() for (const [baseKey, baseDescriptor] of updatingFields) { updateOperations.set(baseKey, baseDescriptor.operations) } const updateExprArray: Array<string> = [] updatingFieldsDescriptors.clear() updatingFields.clear() for (const [baseName, operations] of updateOperations) { if (!Array.isArray(operations) && operations != null) { const baseOperation = operations if (baseOperation.operationName === '$unset') { updateExprArray.push(`${escapeId(baseName)} = NULL `) } else if (baseOperation.operationName === '$set') { const fieldValue = baseOperation.fieldValue updateExprArray.push( `${escapeId(baseName)} = ${ fieldValue != null ? `CAST(${escapeStr(JSON.stringify(fieldValue))} AS JSONB)` : `CAST('null' AS JSONB)` } ` ) } else if (baseOperation.operationName === '$inc') { const inlineTableName = escapeId(`inline-table-${inlineTableNameIdx++}`) const fieldValue = baseOperation.fieldValue const fieldValueType = escapeStr( fieldValue != null ? fieldValue.constructor === String ? 'string' : fieldValue.constructor === Number ? 'number' : 'unknown' : 'unknown' ) updateExprArray.push( `${escapeId(baseName)} = (SELECT CASE WHEN (jsonb_typeof(${inlineTableName}."val") || '-' || ${fieldValueType} ) = 'string-string' THEN to_jsonb( CAST(${inlineTableName}."val" #>> '{}' AS VARCHAR) || CAST(${escapeStr(`${fieldValue}`)} AS VARCHAR) ) WHEN (jsonb_typeof(${inlineTableName}."val") || '-' || ${fieldValueType} ) = 'number-number' THEN to_jsonb( CAST(${inlineTableName}."val" #>> '{}' AS DECIMAL(48, 16)) + CAST(${+(fieldValue as number)} AS DECIMAL(48, 16)) ) ELSE to_jsonb(jsonb_typeof((SELECT 'MalformedIncOperation')::jsonb)) END FROM ( SELECT ${escapeId(baseName)} AS "val" ) ${inlineTableName}) ` ) } } else if (Array.isArray(operations)) { let updateExpr = escapeId(baseName) for (const { operationName, nestedPath, fieldValue, } of operations as Array<Required<typeof operations[0]>>) { const inlineTableName = escapeId(`inline-table-${inlineTableNameIdx++}`) if (operationName === '$unset') { updateExpr = `(SELECT CASE WHEN jsonb_typeof(${inlineTableName}."val" #> '${makeNestedPath( nestedPath )}') IS NOT NULL THEN ${inlineTableName}."val" #- '${makeNestedPath(nestedPath)}' ELSE to_jsonb(jsonb_typeof((SELECT 'MalformedUnsetOperation')::jsonb)) END FROM ( SELECT ${updateExpr} AS "val" ) ${inlineTableName}) ` } else if (operationName === '$set') { const baseNestedPath = makeNestedPath(nestedPath.slice(0, -1)) const lastNestedPathElementType = escapeStr( nestedPath[nestedPath.length - 1] != null ? !isNaN(+nestedPath[nestedPath.length - 1]) ? 'number' : 'string' : 'unknown' ) updateExpr = `(SELECT CASE WHEN ((jsonb_typeof(${inlineTableName}."val" #> '${baseNestedPath}') || '-' || ${lastNestedPathElementType} ) = 'object-string' OR (jsonb_typeof(${inlineTableName}."val" #> '${baseNestedPath}') || '-' || ${lastNestedPathElementType} ) = 'array-number') THEN jsonb_set(${updateExpr}, '${makeNestedPath(nestedPath)}', ${ fieldValue != null ? `CAST(${escapeStr(JSON.stringify(fieldValue))} AS JSONB)` : `CAST('null' AS JSONB)` }) ELSE to_jsonb(jsonb_typeof((SELECT 'MalformedSetOperation')::jsonb)) END FROM ( SELECT ${updateExpr} AS "val" ) ${inlineTableName}) ` } else if (operationName === '$inc') { const fieldValueType = escapeStr( fieldValue != null ? fieldValue.constructor === String ? 'string' : fieldValue.constructor === Number ? 'number' : 'unknown' : 'unknown' ) updateExpr = `(SELECT CASE WHEN (jsonb_typeof(${inlineTableName}."val" #> '${makeNestedPath( nestedPath )}') || '-' || ${fieldValueType} ) = 'string-string' THEN jsonb_set(${updateExpr}, '${makeNestedPath( nestedPath )}', to_jsonb( CAST(${inlineTableName}."val" #>> '${makeNestedPath( nestedPath )}' AS VARCHAR) || CAST(${escapeStr(`${fieldValue}`)} AS VARCHAR) )) WHEN (jsonb_typeof(${inlineTableName}."val" #> '${makeNestedPath( nestedPath )}') || '-' || ${fieldValueType} ) = 'number-number' THEN jsonb_set(${updateExpr}, '${makeNestedPath( nestedPath )}', to_jsonb( CAST(${inlineTableName}."val" #>> '${makeNestedPath( nestedPath )}' AS DECIMAL(48, 16)) + CAST(${+(fieldValue as number)} AS DECIMAL(48, 16)) )) ELSE to_jsonb(jsonb_typeof((SELECT 'MalformedIncOperation')::jsonb)) END FROM ( SELECT ${updateExpr} AS "val" ) ${inlineTableName}) ` } } updateExprArray.push(`${escapeId(baseName)} = ${updateExpr}`) } } if (errors.length > 0) { const summaryError = new Error( errors.map(({ message }) => message).join('\n') ) summaryError.stack = errors.map(({ stack }) => stack).join('\n') throw summaryError } return updateExprArray.join(', ') } export default updateToSetExpression
the_stack
import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { AngularFireAuth } from '@angular/fire/auth'; //import { AngularFireAuth } from 'angularfire2/auth'; import * as firebase from 'firebase/app'; import { environment } from '../../environments/environment'; // import { auth } from 'firebase/app'; import auth from 'firebase'; import { Observable, of } from 'rxjs'; import { switchMap, take } from 'rxjs/operators'; // import { firestore } from 'firebase/app'; import firestore from 'firebase'; // import { AngularFirestore, AngularFirestoreDocument, AngularFirestoreCollection } from 'angularfire2/firestore'; import { AngularFirestore, AngularFirestoreDocument, AngularFirestoreCollection } from '@angular/fire/firestore'; import { BehaviorSubject } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class FirebaseService { private _defaultCenterColl: string = "elish"; private _userColl: string = "userdb"; private _eStoreColl: string = "estore"; authState: any = null; constructor(private _http: HttpClient, public afAuth: AngularFireAuth, private afs: AngularFirestore) { this.afAuth.authState.subscribe( authState => { this.authState = authState; }); } getConfig() { return environment.social; } checkIfUserSignedIn() { return this.afAuth.authState; } // function to send emails using a PHP API sendEmail(messageData) { const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/X-www-form-urlencoded' }) }; return this._http.post(environment.emailAPI, messageData, httpOptions); } // sign-up page - create a new user createUser(formData) { if (environment.database == 'firebase') { return this.afAuth.createUserWithEmailAndPassword(formData.value.email, formData.value.password); } if (environment.database == 'SQL') { // need to call SQL API here if a SQL Database is used } } // login page - login with FB/GOOGLE/EMAIL, if formData is passed, this means is user is using email/password login login(loginType, formData?) { if (formData) { return this.afAuth.signInWithEmailAndPassword(formData.email, formData.password); } else { let loginMethod; if (loginType == 'FB') { loginMethod = new auth.auth.FacebookAuthProvider(); } if (loginType == 'GOOGLE') { loginMethod = new auth.auth.GoogleAuthProvider() } return this.afAuth.signInWithRedirect(loginMethod) } } logout() { window.localStorage.removeItem("displayName"); window.localStorage.removeItem("email"); window.localStorage.removeItem("picture"); window.localStorage.removeItem("center"); window.localStorage.removeItem("token"); return this.afAuth.signOut(); } // method to retreive firebase auth after login redirect redirectLogin() { return this.afAuth.getRedirectResult(); } //////////// firebase eStore funcitons START /////////////// get timestamp() { var d = new Date(); return d; //return firebase.firestore.FieldValue.serverTimestamp(); } timestampMinusDays(filter) { var d = new Date(); d.setDate(d.getDate() - filter); return d; } getCollectionURL(coll){ let localCenter = localStorage.getItem('center') ? localStorage.getItem('center') : this._defaultCenterColl; return this._eStoreColl + "/" + localCenter + "/" + coll; /** let _collURL = ""; if (filter == "customer") { _collURL = this._custColl; } if (filter == "lead") { _collURL = this._leadColl; } return _collURL; */ } setExistingDoc(coll: string, docId: string, data: any) { const timestamp = this.timestamp var docRef = this.afs.collection(coll).doc(docId); return docRef.set(({ ...data, updatedAt: timestamp, createdAt: timestamp, delete_flag: "N" }), { merge: true }); } getAdminPortal(coll?: string){ if (!coll || coll == "store") { coll = this._eStoreColl; } let x; return this.getDoc(coll,this.authState.uid); } // set product functions start getProduct(coll: string, docId: string) { coll = this._eStoreColl + "/" + localStorage.getItem('center') + "/" + coll; return this.getDoc(coll, docId); } setProduct(coll: string, formData: any, docId?: string) { coll = this._eStoreColl + "/" + localStorage.getItem('center') + "/" + coll; return this.setNewDoc(coll, formData); } setProductPic(filePath, coll, docId?){ coll = this._eStoreColl + "/" + localStorage.getItem('center') + "/" + coll; var docRef = this.afs.collection(coll).doc(docId); return docRef.set({ path: filePath },{merge: true}); } deleteProductPic(coll, docId?){ coll = this._eStoreColl + "/" + localStorage.getItem('center') + "/" + coll; var docRef = this.afs.collection(coll).doc(docId); return docRef.set({ path: null },{merge: true}); } getProducts(coll: string) { return this.afs.collection(this.getCollectionURL(coll), ref => ref.where('delete_flag', '==', 'N') .orderBy('name', 'desc') ).valueChanges(); // return this.afs.collection(this.getCollectionURL(coll), ref => // ref.where('delete_flag', '==', 'N') // .orderBy('name', 'desc') // ) // .snapshotChanges().map(actions => { // return actions.map(a => { // const data = a.payload.doc.data(); // const id = a.payload.doc.id; // return { id, ...data }; // }); // }); } getFilterProducts(coll: string, filters) { return this.afs.collection(this.getCollectionURL(coll), ref => ref.where('delete_flag', '==', 'N') .where('tags' , 'array-contains', filters) .orderBy('tags', 'desc') ).valueChanges(); // .snapshotChanges() // .map(actions => { // return actions.map(a => { // const data = a.payload.doc.data(); // const id = a.payload.doc.id; // return { id, ...data }; // }); // }); } deleteProduct(coll,docId){ return this.deleteDoc(this.getCollectionURL(coll),docId); } updateProduct(coll,formData){ return this.updateDoc(this.getCollectionURL(coll),formData._id,formData); } updateShoppingCart(coll: string, data){ const id = this.afs.createId(); const item = { id, name }; const timestamp = this.timestamp var docRef = this.afs.collection(this.getCollectionURL(coll)).doc(item.id); return docRef.set({ ...data, //author: this.afAuth.currentUser.uid, author: this.authState.uid, // authorName: this.afAuth.currentUser.displayName, // authorEmail: this.afAuth.currentUser.email, // authorPhoto: this.afAuth.currentUser.photoURL, // authorPhone: this.afAuth.currentUser.phoneNumber, authorName: this.authState.displayName, authorEmail: this.authState.email, authorPhoto: this.authState.photoURL, authorPhone: this.authState.phoneNumber, updatedAt: timestamp, createdAt: timestamp, delete_flag: "N", }); } updateShoppingInterest(coll: string, data){ const id = this.afs.createId(); const item = { id, name }; const timestamp = this.timestamp var docRef = this.afs.collection(this.getCollectionURL(coll)).doc(item.id); return docRef.set({ ...data, author: this.authState.uid, authorName: this.authState.displayName, authorEmail: this.authState.email, authorPhoto: this.authState.photoURL, authorPhone: this.authState.phoneNumber, updatedAt: timestamp, createdAt: timestamp, delete_flag: "N", }); } getCart(coll: string) { return this.afs.collection(this.getCollectionURL(coll), ref => ref.where('delete_flag', '==', 'N') .where('author', '==', this.authState.uid) .orderBy('name', 'desc') ).valueChanges(); // .snapshotChanges().map(actions => { // return actions.map(a => { // const data = a.payload.doc.data(); // const id = a.payload.doc.id; // return { id, ...data }; // }); // }); } // helper functions getDoc(coll: string, docId: string) { return this.afs.collection(coll).doc(docId).valueChanges(); } setNewDoc(coll: string, data: any, docId?: any) { const id = this.afs.createId(); const item = { id, name }; const timestamp = this.timestamp var docRef = this.afs.collection(coll).doc(item.id); return docRef.set({ ...data, _id: id, updatedAt: timestamp, createdAt: timestamp, delete_flag: "N", username: this.authState.displayName, useremail: this.authState.email }); } updateDoc(coll: string, docId: string, data: any) { const timestamp = this.timestamp var docRef = this.afs.collection(coll).doc(docId); return docRef.update({ ...data, updatedAt: timestamp, delete_flag: "N", username: this.authState.displayName, useremail: this.authState.email }); } deleteDoc(coll: string, docId: string) { const timestamp = this.timestamp var docRef = this.afs.collection(coll).doc(docId); return docRef.update({ updatedAt: timestamp, delete_flag: "Y", username: this.authState.displayName, useremail: this.authState.email }); } getDocs(coll: string, filters?: any) { if (filters) { if (filters.name > "") { return this.afs.collection(coll, ref => ref.where('name', '>=', filters.name) .where('delete_flag', '==', 'N') .orderBy('name', 'desc') ).valueChanges(); // .snapshotChanges().map(actions => { // return actions.map(a => { // const data = a.payload.doc.data(); // const id = a.payload.doc.id; // return { id, ...data }; // }); // }); } if (filters.category > "") { return this.afs.collection(coll, ref => ref.where('category', '>=', filters.category) .where('delete_flag', '==', 'N') .orderBy('category', 'desc') ).valueChanges(); // .snapshotChanges().map(actions => { // return actions.map(a => { // const data = a.payload.doc.data(); // const id = a.payload.doc.id; // return { id, ...data }; // }); // }); } else { let fromDt = new Date(filters.fromdt); let toDt = new Date(filters.todt); return this.afs.collection(coll, ref => ref.where('updatedAt', '>=', fromDt) .where('updatedAt', '<', toDt) .where('delete_flag', '==', 'N') .orderBy('updatedAt', 'desc') ).valueChanges(); // .snapshotChanges().map(actions => { // return actions.map(a => { // const data = a.payload.doc.data(); // const id = a.payload.doc.id; // return { id, ...data }; // }); // }); } } else { return this.afs.collection(coll, ref => ref.where('delete_flag', '==', 'N') .orderBy('name') .orderBy('updatedAt', "desc")) .valueChanges(); // .snapshotChanges().map(actions => { // return actions.map(a => { // const data = a.payload.doc.data(); // const id = a.payload.doc.id; // return { id, ...data }; // }); // }); } } //////////// firebase eStore funcitons END /////////////// // firebase SAMPLE functions below getMemberType() { this.member.counter = 25; this.member.usertype = 'regular'; this.member.company = localStorage.getItem('eCRMkeyC'); this.member.name = localStorage.getItem('eCRMkeyN'); this.member.email = localStorage.getItem('eCRMkeyE'); if (localStorage.getItem('eCRMkeyA') == '7PjNil') { this.member.usertype = 'regular'; } if (localStorage.getItem('eCRMkeyA') == '7PjAil') { this.member.usertype = 'admin'; } if (localStorage.getItem('eCRMkeyA') == '7PjPil') { this.member.usertype = 'pro'; } if (localStorage.getItem('eCRMkeyA') == '7PjNil') { this.member.counter = 25; } if (localStorage.getItem('eCRMkeyA') == '7PjAil') { this.member.counter = 500; } if (localStorage.getItem('eCRMkeyA') == '7PjPil') { this.member.counter = 50000000; } return this.member; } serverCol: AngularFirestoreCollection<any>; serverDoc: AngularFirestoreDocument<any>; private _newsUrl = "https://newsapi.org/v1/articles?source=the-hindu&sortBy=top&apiKey=1fbee980d10644bca6e4c3243034c10a"; private _timeNewsUrl = "https://newsapi.org/v2/top-headlines?sources=google-news-in&apiKey=1fbee980d10644bca6e4c3243034c10a"; private _finNewsUrl = "https://newsapi.org/v2/top-headlines?sources=financial-times&apiKey=1fbee980d10644bca6e4c3243034c10a"; private _wikiUrl = 'http://en.wikipedia.org/w/api.php?callback=JSONP_CALLBACK'; private _userAuthColl: string = "userauth"; private _portalColl: string = "portaldb"; private _locColl: string = "location"; private _custColl: string = "customer"; private _leadColl: string = "lead"; private _callsColl: string = "calls"; private _salesColl: string = "sales"; private _workColl: string = "workorder"; private _emailsColl: string = "email"; private _enquiryColl: string = "enquiry"; private _visitsColl: string = "visit"; private _visitorColl: string = "visitor"; private _guestColl: string = "guest"; private _hostColl: string = "host"; private _attdColl: string = "attendance"; private _vhColl: string = "visitregister"; dbRef: any; geoFire: any; public lat; public lng; data; private userAuthData = new BehaviorSubject(undefined); public userPreferences = this.userAuthData.asObservable(); public member = { company: '', counter: 25, usertype: 'regular', name: '', email: '' } getUser(): Promise<any> { return this.afAuth.authState.pipe(take(1)).toPromise(); } getUserAuth(coll?: string, docId?: string) { if (!coll) { coll = this._userAuthColl; } if (!docId) { docId = this.authState.uid } return this.getDoc(coll, docId); } // this method is used when user logs in first time setUserAuth(uid, uname, phoneNumber, email, photoURL) { let data = { 'authuid': uid, 'authuname': uname, 'authphoneNumber': phoneNumber, 'authemail': email, 'authphoto': photoURL }; this.setExistingDoc(this._userAuthColl, uid, data); } //helper functions// get local or serverTimestamp setUser(formData: any, coll?: string, docId?: string) { if (!coll) { coll = this._userAuthColl; } if (!docId) { docId = this.authState.uid } //return this.setExistingDoc(coll, docId, formData); this.setExistingDoc(coll, docId, formData); } getCustomers(coll?: string, docId?: string, filters?: any) { coll = this._userColl + "/" + localStorage.getItem('eCRMkeyC') + "/" + this.getCollectionURL(coll); //if (!docId) { docId = localStorage.getItem('eCRMkeyI'); } return this.getDocs(coll); //console.log(coll); } getFilterCustomers(coll: string, filters: any) { coll = this._userColl + "/" + localStorage.getItem('eCRMkeyC') + "/" + this.getCollectionURL(coll); //if (!docId) { docId = localStorage.getItem('eCRMkeyI'); } return this.getDocs(coll, filters); //console.log(coll); } setCustomer(coll: string, formData: any, docId?: string) { coll = this._userColl + "/" + localStorage.getItem('eCRMkeyC') + "/" + coll; return this.setNewDoc(coll, formData); } getCustomerDoc(coll: string, docId?: string, coll_userdb?: string, userId?: string) { if (!coll_userdb) { coll_userdb = this._userColl; } if (!userId) { userId = localStorage.getItem('eCRMkeyC'); } coll = coll_userdb + "/" + userId + "/" + this.getCollectionURL(coll); return this.getDoc(coll, docId); } updateCustomerDoc(coll: string, formData: any, docId?: string, coll_userdb?: string, userId?: string) { if (!coll_userdb) { coll_userdb = this._userColl; } if (!userId) { userId = localStorage.getItem('eCRMkeyC'); } coll = coll_userdb + "/" + userId + "/" + this.getCollectionURL(coll); return this.updateDoc(coll, docId, formData); } deleteCustomerDoc(coll: string, docId?: string, coll_userdb?: string, userId?: string) { if (!coll_userdb) { coll_userdb = this._userColl; } if (!userId) { userId = localStorage.getItem('eCRMkeyC'); } coll = coll_userdb + "/" + userId + "/" + this.getCollectionURL(coll); let formData = { "delete_flag": "Y" } return this.deleteDoc(coll, docId); } // helper functions /** OLD_Method_getDocs(coll: string, filters?: any) { if (localStorage.getItem('eCRMkeyA') == '7PjNil') { //not an admin user if (filters) { if (filters.name > "") { return this.afs.collection(coll, ref => ref.where('name', '>=', filters.name) .where('delete_flag', '==', 'N') .where('useremail', '==', localStorage.getItem('eCRMkeyE')) .limit(this.getMemberType().counter) .orderBy('name', 'desc') ) .snapshotChanges().map(actions => { return actions.map(a => { const data = a.payload.doc.data(); const id = a.payload.doc.id; return { id, ...data }; }); }); } if (filters.phone > 0) { return this.afs.collection(coll, ref => ref.where('phone', '>=', filters.phone) .where('delete_flag', '==', 'N') .where('useremail', '==', localStorage.getItem('eCRMkeyE')) .limit(this.getMemberType().counter) .orderBy('phone', 'desc') ) .snapshotChanges().map(actions => { return actions.map(a => { const data = a.payload.doc.data(); const id = a.payload.doc.id; return { id, ...data }; }); }); } else { let fromDt = new Date(filters.fromdt); let toDt = new Date(filters.todt); return this.afs.collection(coll, ref => ref.where('updatedAt', '>=', fromDt) .where('updatedAt', '<', toDt) .where('delete_flag', '==', 'N') .where('useremail', '==', localStorage.getItem('eCRMkeyE')) .limit(this.getMemberType().counter) .orderBy('updatedAt', 'desc') ) .snapshotChanges().map(actions => { return actions.map(a => { const data = a.payload.doc.data(); const id = a.payload.doc.id; return { id, ...data }; }); }); } } else { return this.afs.collection(coll, ref => ref.where('delete_flag', '==', 'N') .where('useremail', '==', localStorage.getItem('eCRMkeyE')) .limit(this.getMemberType().counter) .orderBy('name') .orderBy('updatedAt', "desc")) .snapshotChanges().map(actions => { return actions.map(a => { const data = a.payload.doc.data(); const id = a.payload.doc.id; return { id, ...data }; }); }); } } else { // an admin user if (filters) { if (filters.name > "") { return this.afs.collection(coll, ref => ref.where('name', '>=', filters.name) .where('delete_flag', '==', 'N') .limit(this.getMemberType().counter) .orderBy('name', 'desc') ) .snapshotChanges().map(actions => { return actions.map(a => { const data = a.payload.doc.data(); const id = a.payload.doc.id; return { id, ...data }; }); }); } if (filters.phone > 0) { return this.afs.collection(coll, ref => ref.where('phone', '>=', filters.phone) .where('delete_flag', '==', 'N') .limit(this.getMemberType().counter) .orderBy('phone', 'desc') ) .snapshotChanges().map(actions => { return actions.map(a => { const data = a.payload.doc.data(); const id = a.payload.doc.id; return { id, ...data }; }); }); } else { let fromDt = new Date(filters.fromdt); let toDt = new Date(filters.todt); return this.afs.collection(coll, ref => ref.where('updatedAt', '>=', fromDt) .where('updatedAt', '<', toDt) .where('delete_flag', '==', 'N') .limit(this.getMemberType().counter) .orderBy('updatedAt', 'desc') ) .snapshotChanges().map(actions => { return actions.map(a => { const data = a.payload.doc.data(); const id = a.payload.doc.id; return { id, ...data }; }); }); } } else { return this.afs.collection(coll, ref => ref.where('delete_flag', '==', 'N') .limit(this.getMemberType().counter) .orderBy('name') .orderBy('updatedAt', "desc")) .snapshotChanges().map(actions => { return actions.map(a => { const data = a.payload.doc.data(); const id = a.payload.doc.id; return { id, ...data }; }); }); } } } */ OLD_Method_setNewDoc(coll: string, data: any, docId?: any) { const id = this.afs.createId(); const item = { id, name }; const timestamp = this.timestamp var docRef = this.afs.collection(coll).doc(item.id); return docRef.set({ ...data, updatedAt: timestamp, createdAt: timestamp, delete_flag: "N", username: localStorage.getItem('eCRMkeyN'), useremail: localStorage.getItem('eCRMkeyE') }); } OLD_Method_updateDoc(coll: string, docId: string, data: any) { const timestamp = this.timestamp var docRef = this.afs.collection(coll).doc(docId); return docRef.update({ ...data, updatedAt: timestamp, delete_flag: "N", username: localStorage.getItem('eCRMkeyN'), useremail: localStorage.getItem('eCRMkeyE') }); } OLD_Method_deleteDoc(coll: string, docId: string) { const timestamp = this.timestamp var docRef = this.afs.collection(coll).doc(docId); return docRef.update({ updatedAt: timestamp, delete_flag: "Y", username: localStorage.getItem('eCRMkeyN'), useremail: localStorage.getItem('eCRMkeyE') }); } }
the_stack
import { World } from '@antv/g-webgpu'; import * as d3 from 'd3'; import { Container } from './Container'; import fragmentShaderGLSL from './shaders/webgl.point.frag.glsl'; import vertexShaderGLSL from './shaders/webgl.point.vert.glsl'; export function encodePickingColor( featureIdx: number, ): [number, number, number] { return [ (featureIdx + 1) & 255, ((featureIdx + 1) >> 8) & 255, (((featureIdx + 1) >> 8) >> 8) & 255, ]; } export interface IMarkInitializationOptions { shape: 'circle'; color: { key: string; type: 'categorical'; }; size: { type: 'max'; isShared: boolean; }; } export class Mark { private colorScale: d3.ScaleOrdinal<string, string>; private world: World; private material: any; private geometry: any; private startTime: number; private activeLayout: string; private inited: boolean; private attributesMap: Record< string, { positions: number[]; instancedStartOffsets: number[]; instancedEndOffsets: number[]; instancedColors: number[]; instancedStartSizes: number[]; instancedEndSizes: number[]; instancedShapes: number[]; instancedPickingColors: number[]; } > = {}; constructor(private options: IMarkInitializationOptions) {} public update() { if (!this.startTime) { this.startTime = window.performance.now(); } else { const elaspedTime = window.performance.now() - this.startTime; if (elaspedTime < 600) { this.material.setUniform('u_time', elaspedTime / 600); } else { this.material.setUniform('u_time', 1); } } } public buildAttributesForAllContainers( containerMap: Record<string, Container>, ) { if (this.options.color.type === 'categorical') { this.colorScale = d3.scaleOrdinal(d3.schemeCategory10); } Object.keys(containerMap).forEach((layoutName) => { this.attributesMap[layoutName] = { positions: [1, 1, 1, -1, -1, -1, -1, 1], instancedStartOffsets: [], instancedEndOffsets: [], instancedColors: [], instancedStartSizes: [], instancedEndSizes: [], instancedShapes: [], instancedPickingColors: [], }; this.buildAttributes( containerMap[layoutName], containerMap[layoutName], this.attributesMap[layoutName], ); }); } public render( world: World, scene: Entity, rootContainer: Container, layout: string, ) { this.world = world; const attributes = this.attributesMap[layout]; if (!this.inited) { // create geometry, material and attach them to mesh const geometry = world.createInstancedBufferGeometry({ maxInstancedCount: attributes.instancedStartOffsets.length / 2, vertexCount: 6, }); this.geometry = geometry; geometry.setIndex([0, 2, 1, 0, 3, 2]); geometry.setAttribute( 'position', Float32Array.from(attributes.positions), { arrayStride: 4 * 2, stepMode: 'vertex', attributes: [ { shaderLocation: 0, offset: 0, format: 'float2', }, ], }, ); geometry.setAttribute( 'startOffset', Float32Array.from(attributes.instancedStartOffsets), { arrayStride: 4 * 2, stepMode: 'instance', attributes: [ { shaderLocation: 1, offset: 0, format: 'float2', }, ], }, ); geometry.setAttribute( 'color', Float32Array.from(attributes.instancedColors), { arrayStride: 4 * 4, stepMode: 'instance', attributes: [ { shaderLocation: 2, offset: 0, format: 'float4', }, ], }, ); geometry.setAttribute( 'startSize', Float32Array.from(attributes.instancedStartSizes), { arrayStride: 4, stepMode: 'instance', attributes: [ { shaderLocation: 3, offset: 0, format: 'float', }, ], }, ); geometry.setAttribute( 'endSize', Float32Array.from(attributes.instancedEndSizes), { arrayStride: 4, stepMode: 'instance', attributes: [ { shaderLocation: 3, offset: 0, format: 'float', }, ], }, ); geometry.setAttribute( 'shape', Float32Array.from(attributes.instancedShapes), { arrayStride: 4, stepMode: 'instance', attributes: [ { shaderLocation: 4, offset: 0, format: 'float', }, ], }, ); geometry.setAttribute( 'endOffset', Float32Array.from(attributes.instancedEndOffsets), { arrayStride: 4 * 2, stepMode: 'instance', attributes: [ { shaderLocation: 5, offset: 0, format: 'float2', }, ], }, ); geometry.setAttribute( 'a_PickingColor', Float32Array.from(attributes.instancedPickingColors), { arrayStride: 4 * 3, stepMode: 'instance', attributes: [ { shaderLocation: 6, offset: 0, format: 'float3', }, ], }, ); const material = world.createShaderMaterial({ vertexShader: vertexShaderGLSL, fragmentShader: fragmentShaderGLSL, }); this.material = material; const { width: rootWidth, height: rootHeight, } = rootContainer.visualspace; material.setUniform({ u_stroke_width: 1, u_device_pixel_ratio: window.devicePixelRatio, u_stroke_color: [0, 0, 0, 0], u_stroke_opacity: 1, u_opacity: 0.35, u_blur: 0.2, u_time: 0, u_viewport: [rootWidth, rootHeight], }); // add meshes to current scene const entity = world.createEntity(); scene.addEntity(entity); world .createRenderable(entity) .setGeometry(geometry) .setMaterial(material); this.inited = true; } else { // 布局切换,更新顶点数据 if (this.activeLayout !== layout) { const currentAttributes = this.attributesMap[this.activeLayout]; this.geometry.setAttribute( 'startOffset', Float32Array.from(currentAttributes.instancedEndOffsets), { arrayStride: 4 * 2, stepMode: 'instance', attributes: [ { shaderLocation: 1, offset: 0, format: 'float2', }, ], }, ); this.geometry.setAttribute( 'endOffset', Float32Array.from(attributes.instancedEndOffsets), { arrayStride: 4 * 2, stepMode: 'instance', attributes: [ { shaderLocation: 5, offset: 0, format: 'float2', }, ], }, ); this.geometry.setAttribute( 'startSize', Float32Array.from(currentAttributes.instancedEndSizes), { arrayStride: 4, stepMode: 'instance', attributes: [ { shaderLocation: 3, offset: 0, format: 'float', }, ], }, ); this.geometry.setAttribute( 'endSize', Float32Array.from(attributes.instancedEndSizes), { arrayStride: 4, stepMode: 'instance', attributes: [ { shaderLocation: 3, offset: 0, format: 'float', }, ], }, ); } this.startTime = window.performance.now(); } this.activeLayout = layout; } private buildAttributes( container: Container, rootContainer: Container, attributes: { positions: number[]; instancedStartOffsets: number[]; instancedEndOffsets: number[]; instancedColors: number[]; instancedStartSizes: number[]; instancedEndSizes: number[]; instancedShapes: number[]; instancedPickingColors: number[]; }, ) { container.children.forEach((childContainer) => { if (!this.isContainer(childContainer)) { this.buildMark(container, rootContainer, attributes); } else { this.buildAttributes(childContainer, rootContainer, attributes); } }); } private isContainer(container: Container) { if ( container.hasOwnProperty('data') && container.hasOwnProperty('visualspace') && container.hasOwnProperty('parent') ) { return true; } return false; } private buildMark( container: Container, rootContainer: Container, attributes: { positions: number[]; instancedStartOffsets: number[]; instancedEndOffsets: number[]; instancedColors: number[]; instancedStartSizes: number[]; instancedEndSizes: number[]; instancedShapes: number[]; instancedPickingColors: number[]; }, ) { const { posX, posY, width, height } = container.visualspace; const { posX: parentPosX, posY: parentPosY, } = container.parent!.visualspace; const { width: rootWidth, height: rootHeight } = rootContainer.visualspace; const index = Number(container.data[0].$unitChartId); attributes.instancedStartSizes[index] = width / 2; attributes.instancedEndSizes[index] = width / 2; // attributes.instancedStartSizes.push(width / 2); // attributes.instancedEndSizes.push(width / 2); const color = d3 // @ts-ignore .color(this.colorScale(container.data[0][this.options.color.key])) ?.rgb(); if (color) { const { r, g, b } = color; attributes.instancedColors[index * 4] = r / 255; attributes.instancedColors[index * 4 + 1] = g / 255; attributes.instancedColors[index * 4 + 2] = b / 255; attributes.instancedColors[index * 4 + 3] = 1; // attributes.instancedColors.push(r / 255, g / 255, b / 255, 1); // attributes.instancedEndOffsets.push( // this.convertCanvas2WebGLCoord(posX + parentPosX, rootWidth), // -this.convertCanvas2WebGLCoord(posY + parentPosY, rootHeight), // ); // attributes.instancedStartOffsets.push( // Math.random() * 2 - 1, // Math.random() * 2 - 1, // ); attributes.instancedEndOffsets[index * 2] = this.convertCanvas2WebGLCoord( posX + parentPosX, rootWidth, ); attributes.instancedEndOffsets[ index * 2 + 1 ] = -this.convertCanvas2WebGLCoord(posY + parentPosY, rootHeight); attributes.instancedStartOffsets[index * 2] = Math.random() * 2 - 1; attributes.instancedStartOffsets[index * 2 + 1] = Math.random() * 2 - 1; // attributes.instancedShapes.push(0); attributes.instancedShapes[index] = 0; // attributes.instancedPickingColors.push( // ...encodePickingColor(Number(container.contents[0].$unitChartId)), // ); const [encodedR, encodedG, encodedB] = encodePickingColor( Number(container.data[0].$unitChartId), ); attributes.instancedPickingColors[index * 3] = encodedR; attributes.instancedPickingColors[index * 3 + 1] = encodedG; attributes.instancedPickingColors[index * 3 + 2] = encodedB; } } private convertCanvas2WebGLCoord(c: number, size: number) { return (c / size) * 2 - 1; } }
the_stack
import * as vscode from 'vscode'; import {LabelsClass} from '../labels/labels'; import {Settings, SettingsParameters} from '../settings'; import {readFileSync} from 'fs'; import {Utility} from '../misc/utility'; import * as path from 'path'; import {FileWatcher} from '../misc/filewatcher'; /** * An item that represents a unit test and connect the vscode TestItem, * the unit test and the file watcher. * There are 4 different types of test items: * - A test suite representing a launch.json file * - A test suite representing a sld/list file * - A test suite collecting several unit test (this base class here) * - A unit test itself (the UT label) * plus the rootSuite which is a suite without parent and testItem references. */ export class UnitTestCaseBase { // Pointer to the corresponding test item. public testItem: vscode.TestItem; // A weak map that associates vscode test cases with "real" UnitTestCases. public static tcMap = new Map<vscode.TestItem, UnitTestCaseBase>(); /** * Constructor. * @param id The unique id. File name plus assembly label. * @param label The human readable name of the unit test. * @param filePath An optional file path. */ constructor(id: string, label: string, filePath?: string) { if (id) { let uri; if (filePath) uri = vscode.Uri.file(filePath); this.testItem = RootTestSuite.testController.createTestItem(id, label, uri); UnitTestCaseBase.tcMap.set(this.testItem, this); } } /** * Returns the "real" UnitTestCase for a vscode test item. */ public static getUnitTestCase(item: vscode.TestItem): UnitTestCaseBase { const ut = UnitTestCaseBase.tcMap.get(item); Utility.assert(ut); return ut!; } /** * Searches the parents until it finds the config (UnitTestSuiteConfig) * from the launch.json. * @returns The config test suite or undefined. */ public getConfigParent(): UnitTestSuiteConfig | undefined { let testItem = this.testItem.parent; let testConfig; while (testItem) { // Get "real" test testConfig = UnitTestCaseBase.getUnitTestCase(testItem) as UnitTestSuiteConfig; Utility.assert(testConfig); if (testConfig instanceof UnitTestSuiteConfig) { return testConfig; } // Next testItem = testItem.parent; } return undefined; } } /** * A test case. * Additionally contains information for executing the test case, e.g. the label. */ export class UnitTestCase extends UnitTestCaseBase { // The label for execution. E.g. "TestSuite.UT_clear_screen" public utLabel: string; /** * Constructor. * @param id The unique id. File name plus assembly label. * @param label The human readable name of the unit test. * @param utLabel The (assembly) label of the unit test. * @param filePath An optional file path. */ constructor(id: string, label: string, utLabel: string, filePath: string) { super(id, label, filePath); this.utLabel = utLabel; } } /** * A test suite containing other test suites or test cases. */ export class UnitTestSuite extends UnitTestCase { // A map that contains children unit tests. protected children: Array<UnitTestSuite | UnitTestCaseBase>; /** * Constructor. * @param id The unique id. File name plus assembly label. * @param label The human readable name of the unit test. * @param utLabel The (assembly) label of the unit test. * @param filePath An optional file path. */ constructor(id: string, label: string, utLabel: string, filePath: string) { super(id, label, utLabel, filePath); this.children = []; } /** * Adds a child. If necessary removes the child from its old parent. */ public addChild(child: UnitTestCaseBase) { // child.parent?.removeChild(child); this.children.push(child); // child.parent = this; // Add vscode item this.testItem.children.add(child.testItem); } /** * Removes a child from the list. */ public removeChild(child: UnitTestCaseBase) { const reducedList = this.children.filter(item => item != child); this.children = reducedList; // Delete vscode test item this.testItem.children.delete(child.testItem.id); } /** * Delete a test suite and it's children. */ public delete() { this.deleteChildren(); } /** * Deletes all children. * Calls delete on each child. */ public deleteChildren() { // Delete children for (const child of this.children) { //child.parent = undefined; this.testItem.children.delete(child.testItem.id); } this.children = []; } } /** * The root test suite. Used to hold all other test suites. * Is associated with a test controller but not with a test item. */ export class RootTestSuite extends UnitTestSuite { // Pointer to the test controller. public static testController: vscode.TestController; // A map that remembers the workspaces/launch.json associations protected wsTsMap: Map<string, UnitTestSuiteLaunchJson>; // A map that remembers the workspaces/file watcher associations protected wsFwMap: Map<string, FileWatcher>; /** * Constructor. */ constructor(testController: vscode.TestController) { super(undefined as any, undefined as any, undefined as any, undefined as any); UnitTestCaseBase.tcMap.clear(); // A map that remembers the workspaces this.wsTsMap = new Map<string, UnitTestSuiteLaunchJson>(); this.wsFwMap = new Map<string, FileWatcher>(); RootTestSuite.testController = testController; testController.resolveHandler = (testItem) => { this.resolveTests(testItem); } } /** * Create the test items. * Due to the nature how the test items are discovered they are all * discovered at once when this function is called first with 'undefined'. * Otherwise it should not be called anymore by vscode. * 'resolveTests' should be called only once. Every test item is populated, * so there is no need to call it anymore afterwards. * If there are changes to the test cases it will be handled by the file watchers. * @param testItem If undefined create all test cases. Otherwise do nothing. */ protected resolveTests(testItem: vscode.TestItem | undefined) { if (testItem) return; if (!vscode.workspace.workspaceFolders) return; // Loop over all workspaces this.addWorkspaces(vscode.workspace.workspaceFolders); // And observe changes to the workspace vscode.workspace.onDidChangeWorkspaceFolders(e => { // Add workspaces this.addWorkspaces(e.added); // Remove workspaces for (const ws of e.removed) { const wsFolder = ws.uri.fsPath; // Delete test suite const tsSuite = this.wsTsMap.get(wsFolder)!; tsSuite.delete(); // And dispose this.wsTsMap.delete(wsFolder); // Delete file watcher const fw = this.wsFwMap.get(wsFolder)!; fw.dispose(); this.wsFwMap.delete(wsFolder); } }); } /** * Add workspaces. * A workspace exists in the test controller only if a launch.json exists for it. * @param workspaces A list of workspaces to watch. */ protected addWorkspaces(workspaces: readonly vscode.WorkspaceFolder[],) { for (const ws of workspaces) { // Retrieve all unit test configs const wsFolder = ws.uri.fsPath; // The test id is at the same time the file name (if test item is a file) const filePath = Utility.getlaunchJsonPath(wsFolder); const fileWatcher = new FileWatcher(filePath); this.wsFwMap.set(wsFolder, fileWatcher)!; let wsSuite: UnitTestSuiteLaunchJson; fileWatcher.onDidCreate(() => { wsSuite = new UnitTestSuiteLaunchJson(wsFolder, path.basename(wsFolder)); // Add child this.addChild(wsSuite); // Remember test suite this.wsTsMap.set(wsFolder, wsSuite); }); fileWatcher.onDidChange(() => { wsSuite.fileChanged(); }); fileWatcher.onDidDelete(() => { // Remove child this.removeChild(wsSuite); // Forget test suite this.wsTsMap.delete(wsFolder); }); } } /** * Adds a child. If necessary removes the child from its old parent. */ public addChild(child: UnitTestCaseBase) { this.children.push(child); } /** * Removes a child from the list. */ public removeChild(child: UnitTestCaseBase) { const reducedList = this.children.filter(item => item != child); this.children = reducedList; // Delete vscode test item RootTestSuite.testController.items.delete(child.testItem.id); } } /** * Extends the base class with functionality for handling files (file watcher) * and especially the launch.json file. */ class UnitTestSuiteLaunchJson extends UnitTestSuite { // The path to the workspace. protected wsFolder: string; /** * Constructor. * @param wsFolder Workspace folder */ constructor(wsFolder: string, label: string) { super(Utility.getlaunchJsonPath(wsFolder), label, undefined as any, Utility.getlaunchJsonPath(wsFolder)); this.testItem.description = 'workspace'; this.wsFolder = wsFolder; this.fileChanged(); } /** * Call if launch.json file has been changed. */ public fileChanged() { // Delete all children this.deleteChildren(); // Read launch.json try { // Get launch configs const launchJsonPath = this.testItem.id; const configs = this.getUnitTestsLaunchConfigs(launchJsonPath); // Delete this test item for now. RootTestSuite.testController.items.delete(this.testItem.id); // Loop over all unit test launch configs (usually 1) for (const config of configs) { // Create new test item const testConfig = new UnitTestSuiteConfig(this.wsFolder, config); this.addChild(testConfig); // Add line number const lineNr = config.__lineNr; if (lineNr != undefined) { const vsTest: vscode.TestItem = testConfig.testItem; vsTest.range = new vscode.Range(lineNr, 0, lineNr, 0); } } // If there are test configuration, add the test item. // Note: in launch.json without dezog this will not show any test item. if (this.children.length > 0) { RootTestSuite.testController.items.add(this.testItem); } } catch (e) { // Ignore, e.g. errors in launch.json } } /** * Returns the unit tests launch configurations. I.e. the configuration * from .vscode/launch.json with property unitTests set to true. * @param launchJsonPath The absolute path to the .vscode/launch.json file. * @returns Array of unit test configs or empty array. * Throws an exception if launch.json cannot be parsed. Or if file does not exist. */ protected getUnitTestsLaunchConfigs(launchJsonPath: string): any { // Read file for the line numbers. const launchData = readFileSync(launchJsonPath, 'utf8'); // Parse file const launch = Utility.readLaunchJson(launchJsonPath, launchData); // Find the right configurations const configurations = launch.configurations.filter(config => (config.type == 'dezog') && config.unitTests); // Find the right lines for the configs, i.e. search for "name": config.name for (const config of configurations) { const regStr = '"name"\\s*:\\s*"' + config.name + '"'; const regex = new RegExp(regStr); const lineNr = Utility.getLineNumberInText(regex, launchData); // Add this additional info config.__lineNr = lineNr; } return configurations; } } /** * Extends the base class with functionality for handling launch.json configs. */ export class UnitTestSuiteConfig extends UnitTestSuite { // The workspace folder. public wsFolder: string; // Pointer to the launch.json config public config: SettingsParameters; // A file watcher for each sld/list file. protected fileWatchers: FileWatcher[]; // Timer for "debouncing" protected timerId: NodeJS.Timeout; /** * Constructor. * @param wsFolder Workspace folder. * @param config launch.json configuration. */ constructor(wsFolder: string, config: any) { super(wsFolder + '#' + config.name, config.name, undefined as any, Utility.getlaunchJsonPath(wsFolder)); this.testItem.description = 'config'; this.wsFolder = wsFolder; this.config = Settings.Init(config); this.fileWatchers = []; // Read launch.json try { // Get all list files const listFiles = Settings.GetAllAssemblerListFiles(this.config); // Loop over all list files for (const listFile of listFiles) { // Create a new file watcher const fw = new FileWatcher(listFile.path); this.fileWatchers.push(fw); fw.onDidCreate(() => { this.fileChanged(); }); fw.onDidChange(() => { this.fileChanged(); }); fw.onDidDelete(() => { // Note: it might be (if several list files are used) that // only one file was deleted. // On a build normally all files should be recreated, but // in a pathological case one might be removed. // In that case parsing would fail. this.fileChanged(); }); } } catch (e) { // Ignore, e.g. errors in launch.json } } /** * Delete a test item and it's children. * Removes the file watcher. */ public delete() { super.delete(); // Delete file watchers this.fileWatchers.forEach(element => element.dispose()); } /** * Called if a sld/list file changes. * Start a timer to wait for other file changes (changes of other list files). */ protected fileChanged() { // "Debounce" with a timer in case several files are touched at the same time clearTimeout(this.timerId); this.timerId = setTimeout(() => { try { this.delayedFileChanged(); } catch (e) {} }, 200); } /** * Called if a sld/list file changed and no change happened for 1 second. * Creates labels from the list files. * From the UT-labels test suites and test cases are created. */ public delayedFileChanged() { // Remove old structures (+ children) this.deleteChildren(); // Read labels from sld/list file const labels = new LabelsClass(); Utility.setRootPath(this.wsFolder); try { labels.readListFiles(this.config); } catch (e) { console.log(e); throw e; } // Now parse for Unit test labels, i.e. starting with "UT_" const utLabels = this.getAllUtLabels(labels); // Convert labels into intermediate map const map = this.convertLabelsToMap(utLabels); // Convert into test suite/cases this.createTestSuite(labels, map, ''); } /** * Create a test suite object from the given map. * Calls itself recursively. * @param map A map of maps. An entry with a map of length 0 is a leaf, * i.e. a test case. Others are test suites. */ protected createTestSuite(labels: LabelsClass, map: Map<string, any>, name: string, parent?: UnitTestSuite) { // Check if test suite or test case let testItem; if (parent) { const fullId = parent.testItem.id + '.' + name; let fullUtLabel = ''; if (parent.utLabel) fullUtLabel = parent.utLabel + '.'; fullUtLabel += name; // Get file/line location const location = labels.getLocationOfLabel(fullUtLabel)!; let file; if (location) { file = Utility.getAbsFilePath(location.file); } // Suite or test case if (map.size == 0) { // It has no children, it is a leaf, i.e. a test case Utility.assert(file); testItem = new UnitTestCase(fullId, name, fullUtLabel, file); } else { testItem = new UnitTestSuite(fullId, name, fullUtLabel, file); } parent.addChild(testItem); // Now the location inside the file if (location) { const vsTest: vscode.TestItem = testItem.testItem; vsTest.range = new vscode.Range(location.lineNr, 0, location.lineNr, 0); } } else { // Root testItem = this; } for (const [key, childMap] of map) { this.createTestSuite(labels, childMap, key, testItem); } } /** * Returns all labels that start with "UT_". * @returns An array with label names. */ protected getAllUtLabels(labels: LabelsClass): UtLabelFileLine[] { const utLabels = labels.getLabelsForRegEx('.*\\bUT_\\w*$', ''); // case sensitive // Convert to filenames and line numbers. const labelFilesLines: UtLabelFileLine[] = utLabels.map(label => { const location = labels.getLocationOfLabel(label)! Utility.assert(location, "'getAllUtLabels'"); return {label, file: Utility.getAbsFilePath(location.file), line: location.lineNr}; }); return labelFilesLines; } /** * Function that converts the string labels in a test suite map structure. * @param lblLocations List of unit test labels. */ protected convertLabelsToMap(lblLocations: UtLabelFileLine[]): Map<string, any> { const labels = lblLocations.map(lblLoc => lblLoc.label); const labelMap = new Map<string, any>(); for (const label of labels) { const parts = label.split('.'); let map = labelMap; // E.g. "ut_string" "UTT_byte_to_string" for (const part of parts) { // Check if entry exists let nextMap = map.get(part); // Check if already existent if (!nextMap) { // Create entry nextMap = new Map<string, any>(); map.set(part, nextMap); } // Next map = nextMap; } } /* // Note: an entry with a map of length 0 is a leaf, i.e. a testcase. Others are test suites. if (labelMap.size == 0) { // Return an empty suite return undefined; } */ return labelMap; } } /** * This structure is returned by getAllUnitTests. */ interface UtLabelFileLine { label: string; // The full label of the test case, e.g. "test.UT_test1" file: string; // The full path of the file line: number; // The line number of the label }
the_stack
import * as tf from "@tensorflow/tfjs"; import * as d3 from "d3"; import { generateTfjsModel, topologicalSort } from "../../model/build_network"; import { changeDataset } from "../../model/data"; import { svgData } from "../app"; import { displayError } from "../error"; import { parseString } from "../utils"; import { windowProperties } from "../window"; import { Draggable } from "./draggable"; import { Point, Shape } from "./shape"; import { Wire } from "./wire"; export interface ILayerJson { layer_name: string; id: number; children_ids: number[]; parent_ids: number[]; params: any; xPosition: number; yPosition: number; } // TODO params for entering things in UI for layer properties export abstract class Layer extends Draggable { public static getNextID(): number { const id = Layer.nextID; Layer.nextID += 1; return id; } private static nextID: number = 0; // a global id counter for labeling layers public layerType: string = ""; // A string indicating layer type for each layer used for serialization public parameterDefaults: { [key: string]: any }; // tfjs keys for layer parameters to input values public children: Set<Layer> = new Set(); // Predecessors (closer to the input layer) public parents: Set<Layer> = new Set(); // Successors (closer to the output layer) public wires: Set<Wire> = new Set(); // The line objects connecting this layer to other layers public uid: number; // Each layer gets a unique ID public shape: number[]; // The shape/dimensions of the layer. public readonly outputWiresAllowed: boolean = true; public readonly wireGuidePresent: boolean = true; protected tfjsLayer: tf.SymbolicTensor; protected readonly tfjsEmptyLayer: any; protected paramBox: HTMLElement; private selectText: any = d3.select("body") .append("div") .style("position", "absolute") .style("padding", "6px") .style("background", "rgba(0, 0, 0, 0.8)") .style("color", "#eee") .style("border-radius", "2px") .style("display", "none") .style("font-family", "Helvetica") .style("user-select", "none"); private block: Shape[]; constructor(block: Shape[], defaultLocation: Point) { super(defaultLocation); this.uid = Layer.nextID; Layer.nextID += 1; this.block = block; for (const rect of this.block) { this.svgComponent.call(rect.svgAppender.bind(rect)); } this.paramBox = document.createElement("div"); this.paramBox.className = "parambox"; this.paramBox.style.visibility = "hidden"; this.paramBox.style.position = "absolute"; document.getElementById("paramtruck").appendChild(this.paramBox); this.svgComponent.on("click", () => { this.select(); window.clearTimeout(this.moveTimeout); this.hoverText.style("visibility", "hidden"); }); this.populateParamBox(); } public abstract lineOfPython(): string; public abstract getHoverText(): string; public abstract clone(): Layer; public moveAction(): void { for (const wire of this.wires) { wire.updatePosition(); } if (windowProperties.selectedElement === this) { windowProperties.shapeTextBox.setPosition(this.getPosition()); } } public raise(): void { this.wires.forEach((w) => w.raiseGroup()); this.parents.forEach((p) => p.raiseGroup()); this.children.forEach((c) => c.raiseGroup()); this.raiseGroup(); } public select(): void { const currSelected = windowProperties.selectedElement; if (currSelected != null && currSelected !== this && currSelected instanceof Layer && currSelected.outputWiresAllowed) { currSelected.addChild(this); } super.select(); document.getElementById("defaultparambox").style.display = "none"; this.paramBox.style.visibility = "visible"; this.svgComponent.selectAll("path").style("stroke", "yellow").style("stroke-width", "2"); this.svgComponent.selectAll(".outerShape").style("stroke", "yellow").style("stroke-width", "2"); const bbox = this.outerBoundingBox(); windowProperties.shapeTextBox.setOffset(new Point((bbox.left + bbox.right) / 2, bbox.bottom + 25)); windowProperties.shapeTextBox.setText("[" + this.layerShape().toString() + "]"); windowProperties.shapeTextBox.setPosition(this.getPosition()); windowProperties.shapeTextBox.show(); } public unselect(): void { super.unselect(); document.getElementById("defaultparambox").style.display = null; this.paramBox.style.visibility = "hidden"; this.svgComponent.selectAll("path").style("stroke", null).style("stroke-width", null); this.svgComponent.selectAll(".outerShape").style("stroke", null).style("stroke-width", null); this.selectText.style("visibility", "hidden"); windowProperties.shapeTextBox.hide(); } /** * Add a child layer of this node (successor). * @param child the layer pointed to by the given wire */ public addChild(child: Layer): void { if (!this.children.has(child) && !child.children.has(this)) { this.children.add(child); child.parents.add(this); const newWire = new Wire(this, child); this.wires.add(newWire); child.wires.add(newWire); } } /** * Add a parent layer of this node (predecessor). * @param parent the layer pointed to by the given wire */ public addParent(parent: Layer): void { parent.addChild(this); } public delete(): void { super.delete(); this.wires.forEach((w) => w.delete()); // deleting wires should delete layer connection sets } public toJson(): ILayerJson { return { children_ids: Array.from(this.children, (child) => child.uid), id: this.uid, layer_name: this.layerType, params: this.getJSONParams(), parent_ids: Array.from(this.parents, (parent) => parent.uid), xPosition: this.getPosition().x, yPosition: this.getPosition().y, }; } public getJSONParams(): { [key: string]: any } { const params: { [key: string]: any } = {}; const defaultParams = this.parameterDefaults; for (const line of this.paramBox.children) { const name = line.children[0].getAttribute("data-name"); if (line.children[1].className === "select") { const selectElement: HTMLSelectElement = line.children[1].children[0] as HTMLSelectElement; params[name] = selectElement.options[selectElement.selectedIndex].value; } else { const value = ( line.children[1] as HTMLInputElement).value; // Need to not parse as integer for float parameters if ((defaultParams[name].toString()).indexOf(".") >= 0) { params[name] = parseFloat(value); } else { params[name] = parseString(value); } } } return params; } public getParams(): { [key: string]: any; } { const params: { [key: string]: any } = {}; const defaultParams = this.parameterDefaults; for (const line of this.paramBox.children) { const name = line.children[0].getAttribute("data-name"); if (line.children[1].className === "select") { const selectElement: HTMLSelectElement = line.children[1].children[0] as HTMLSelectElement; params[name] = selectElement.options[selectElement.selectedIndex].value; } else { const value = ( line.children[1] as HTMLInputElement).value; // Need to not parse as integer for float parameters if ((defaultParams[name].toString()).indexOf(".") >= 0) { params[name] = parseFloat(value); } else { params[name] = parseString(value); } } } return params; } public setParams(params: Map<string, any>): void { for (const line of this.paramBox.children) { const name = line.children[0].getAttribute("data-name"); if (line.children[1].className === "select") { const selectElement: HTMLSelectElement = line.children[1].children[0] as HTMLSelectElement; // Get index with the correct value and select it for (let i = 0; i < selectElement.options.length; i++) { if (selectElement.options.item(i).value === params.get(name)) { selectElement.selectedIndex = i; break; } } } else { ( line.children[1] as HTMLInputElement).value = params.get(name); } } } /** * Make parent -> this become parent -> layer -> this. * @param layer a layer that will become the new parent * @param parent a parent of this */ public addParentLayerBetween(layer: Layer, parent: Layer): void { parent.children.delete(this); parent.children.add(layer); layer.parents.add(parent); layer.children.add(this); this.parents.delete(parent); this.parents.add(layer); } /** * Make parents -> this become parents -> layer -> this. * @param parent a parent of this */ public addParentLayer(layer: Layer): void { for (const parent of this.parents) { parent.children.delete(this); parent.children.add(layer); } layer.parents = new Set([...layer.parents, ...this.parents]); layer.children.add(this); this.parents.clear(); this.parents.add(layer); } /** * Make new child -> this become this -> newChild -> old children. * @param newChild a new child of this */ public addChildLayerBetween(newChild: Layer): void { for (const child of this.children) { newChild.addChild(child); child.parents.delete(this); } this.children.clear(); this.addChild(newChild); newChild.addParent(this); } public getTfjsLayer(): tf.SymbolicTensor { return this.tfjsLayer; } public generateTfjsLayer(): void { // TODO change defaults to class level const parameters = this.getParams(); let parent: Layer = null; for (const p of this.parents) { parent = p; break; } // Concatenate layers handle fan-in if (this.parents.size > 1) { displayError(new Error("Must use a concatenate when a layer has multiple parents")); } this.tfjsLayer = this.tfjsEmptyLayer(parameters).apply(parent.getTfjsLayer()); } public layerShape(): number[] { // Computes all of the predecessors to determine shape if (this.layerType === "Input") { changeDataset(svgData.input.getParams().dataset); } try { generateTfjsModel(topologicalSort(svgData.input, false)); return this.getTfjsLayer().shape; } catch (err) { // Hide errors while building the network return null; } } public initLineOfJulia(): string { return ""; } public lineOfJulia(): string { let connections = ""; for (const child of this.children) { connections += `connect!(net, x${this.uid}, x${child.uid})\n`; } return connections; } public hasParentType(type: any ): boolean { for (const p of this.parents) { if (p instanceof type) { return true; } } return false; } protected abstract populateParamBox(): void; protected focusing(): void { for (const line of this.paramBox.children) { ( line.children[1] as HTMLInputElement).onfocus = this.toggleFocus.bind(line.children[1]); ( line.children[1] as HTMLInputElement).onblur = this.toggleFocus.bind(line.children[1]); } } private toggleFocus(textField: any): void { textField.target.classList.toggle("focusParam"); } }
the_stack
import { ElasticMatch } from './ElasticMatch'; import { ElasticMatches } from './ElasticMatches'; 'use script'; import * as vscode from 'vscode'; import * as request from 'request'; import { Range, ParameterInformation, commands, Selection } from 'vscode'; import url = require('url'); import routington = require('routington'); import closestSemver = require('semver-closest'); import * as os from 'os'; export class ElasticCompletionItemProvider implements vscode.CompletionItemProvider, vscode.HoverProvider { private readonly context: vscode.ExtensionContext; private readonly restSpec: any; constructor(context: vscode.ExtensionContext) { this.context = context; this.restSpec = this.buildRestSpecRouter(); } private buildRestSpecRouter() { const restSpec = require('./rest-spec').default; const versions = Object.keys(restSpec); const result = {}; versions.forEach(version => { const endpointDescriptions = restSpec[version].default; const common = endpointDescriptions._common; delete endpointDescriptions._common; const endpointNames = Object.keys(endpointDescriptions); const router = result[version] = routington(); endpointNames.forEach(endpointName => { const endpointDescription = endpointDescriptions[endpointName]; if (common) { if (endpointDescription.url.params) Object.keys(common.params) .forEach(param => endpointDescription.url.params[param] = common.params[param]); else endpointDescription.url.params = common.params; } const paths = endpointDescription.url.paths.map(path => path.replace(/\{/g, ':').replace(/\}/g, '')); const methods = endpointDescription.methods; methods.forEach(method => paths .forEach(path => (router.define(`${method}${path}`)[0].spec = endpointDescription))); }); }); return result; } provideCompletionItems(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): vscode.ProviderResult<vscode.CompletionItem[] | vscode.CompletionList> { return this.asyncProvideCompletionItems(document, position, token); } provideHover(document: vscode.TextDocument, position: vscode.Position): Promise<vscode.Hover> { return this.asyncProvideHover(document, position); } private async asyncProvideHover(document: vscode.TextDocument, position: vscode.Position): Promise<vscode.Hover> { let esVersion = await this.getElasticVersion(); esVersion = '6.0.0' if (!esVersion) return; let apiVersion = closestSemver(esVersion, Object.keys(this.restSpec)); let restSpec = this.restSpec[apiVersion]; if (!restSpec) return; const line = document.lineAt(position); var match = ElasticMatch.RegexMatch.exec(line.text); var params = [] if (match != null) { let range = line.range; var path = match[2].split('?')[0]; var signature = path.split('/').pop(); const m = restSpec.match(`${match[1]}${path}`) params.push(`${m.node.spec.body.description}`) if (m.node.spec.url.params) { params.push(os.EOL + 'url params:') for (var i in m.node.spec.url.params) { var p = m.node.spec.url.params[i]; var text = `* ${i} *(${p.type})*` params.push(text) } } var htm = [`${m.node.spec.methods.join(' | ')} **${m.node.string}** ([documentation](${m.node.spec.documentation}))`, params.join(os.EOL)]; return Promise.resolve<vscode.Hover>(new vscode.Hover(htm, range)); } return; } private async asyncProvideCompletionItems(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): Promise<vscode.CompletionItem[] | vscode.CompletionList> { let esVersion = await this.getElasticVersion(); esVersion = '6.0.0' if (!esVersion) return []; const editor = vscode.window.activeTextEditor let esMatch = new ElasticMatches(editor).Selection if (!esMatch) return []; let apiVersion = closestSemver(esVersion, Object.keys(this.restSpec)); let restSpec = this.restSpec[apiVersion]; if (!restSpec) return []; if (this.isPathCompletion(esMatch, position)) return this.providePathCompletionItem(esMatch, restSpec); else if (this.isPathParamCompletion(esMatch, position)) return this.providePathParamCompletionItem(esMatch, restSpec); console.log(esMatch.Body.Text); return []; } private async providePathParamCompletionItem(esMatch: any, restSpec: any): Promise<vscode.CompletionItem[] | vscode.CompletionList> { const match = restSpec.match(`${esMatch.Method.Text}${esMatch.Path.Text.split('?')[0]}`); if (!match) return []; return Object.keys(match.node.spec.url.params) .map(param => new vscode.CompletionItem(param)); } private async providePathCompletionItem(esMatch: any, restSpec: any): Promise<vscode.CompletionItem[] | vscode.CompletionList> { let parts = esMatch.Path.Text.split('/').filter(part => part.length); let parent = restSpec.child[esMatch.Method.Text]; let grandParent; parts.forEach(part => { if (!parent) return; grandParent = parent; parent = part in parent.child ? parent.child[part] : parent.children[0]; }); if (!parent) return []; let result = []; let variable = parent.children[0]; if (variable) { if (variable.name == 'index') { result = result.concat((await this.listIndices()).map(index => ({ label: index }))); result = result.concat((await this.listAliases()).map(index => ({ label: index }))); } else if (variable.name == 'name' && grandParent && grandParent.string === '_alias') result = result.concat((await this.listAliases()).map(index => ({ label: index }))); else if (variable.name == 'repository') result = result.concat((await this.listRepositories()).map(repository => ({ label: repository }))); else result.push({ label: `<${variable.name}>`}); } result = result.concat(Object.keys(parent.child).map(child => ({ label: child }))); return result.filter(part => part.label.length) .map(part => new vscode.CompletionItem(part.label)); } private isPathCompletion(esMatch: ElasticMatch, position: vscode.Position): boolean { return esMatch.Method.Range.start.line === position.line && esMatch.Path.Text[esMatch.Path.Text.length - 1] === '/'; } private isPathParamCompletion(esMatch: ElasticMatch, position: vscode.Position): boolean { return esMatch.Method.Range.start.line === position.line && (esMatch.Path.Text[esMatch.Path.Text.length - 1] === '?' || esMatch.Path.Text[esMatch.Path.Text.length - 1] === '&'); } //private lookupEndpoint(esVersion: string, ) private async listIndices() : Promise<string[]> { const host: string = this.context.workspaceState.get("elastic.host", null); const requestUrl: string = url.format({ host, pathname: '/_cat/indices', protocol: 'http' }); return new Promise<string[]>((resolve, reject) => { request(<request.UrlOptions & request.CoreOptions>{ url: requestUrl + '?format=json', method: 'GET', headers: { 'Content-Type': 'application/json' } }, (error, response, body) => { try { resolve(JSON.parse(body).map(entry => entry.index)); } catch(e) { resolve([]); } }) }); } private async listAliases() : Promise<string[]> { const host: string = this.context.workspaceState.get("elastic.host", null); const requestUrl: string = url.format({ host, pathname: '/_cat/aliases', protocol: 'http' }); return new Promise<string[]>((resolve, reject) => { request(<request.UrlOptions & request.CoreOptions>{ url: requestUrl + '?format=json', method: 'GET', headers: { 'Content-Type': 'application/json' } }, (error, response, body) => { try { resolve(JSON.parse(body).map(entry => entry.alias)); } catch(e) { resolve([]); } }) }); } private async listRepositories() : Promise<string[]> { const host: string = this.context.workspaceState.get("elastic.host", null); const requestUrl: string = url.format({ host, pathname: '/_snapshot', protocol: 'http' }); return new Promise<string[]>((resolve, reject) => { request(<request.UrlOptions & request.CoreOptions>{ url: requestUrl, method: 'GET', headers: { 'Content-Type': 'application/json' } }, (error, response, body) => { try { resolve(Object.keys(JSON.parse(body))); } catch(e) { resolve([]); } }) }); } private async getElasticVersion(): Promise<string> { const host: string = this.context.workspaceState.get("elastic.host", null); const requestUrl: string = url.format({ host, pathname: '/', protocol: 'http' }); return new Promise<string>((resolve, reject) => { request(<request.UrlOptions & request.CoreOptions>{ url: requestUrl, method: 'GET', headers: { 'Content-Type': 'application/json' } }, (error, response, body) => { try { resolve(JSON.parse(body).version.number); } catch(e) { resolve(null); } }) }); } /*resolveCompletionItem?(item: vscode.CompletionItem, token: vscode.CancellationToken): vscode.ProviderResult<vscode.CompletionItem> { throw new Error("Method not implemented."); }*/ }
the_stack
namespace SchemeDesigner { /** * Map manager * @author Nikitchenko Sergey <nikitchenko.sergey@yandex.ru> */ export class MapManager { /** * Scheme object */ protected scheme: Scheme; /** * Canvas element for map */ protected mapCanvas: HTMLCanvasElement; /** * Map view */ protected mapView: View; /** * Is dragging */ protected isDragging: boolean = false; /** * Left button down */ protected leftButtonDown: boolean = false; /** * Last client position */ protected lastClientPosition: Coordinates; /** * distance for touch zoom */ protected touchDistance: number; /** * Last touch end time * @type {number} */ protected lastTouchEndTime: number = 0; /** * Constructor * @param {SchemeDesigner.Scheme} scheme */ constructor(scheme: Scheme) { this.scheme = scheme; } /** * Scaled scheme rect * @returns {number} */ protected getScaledSchemeRect(): ScaledRect { let imageBoundingRect = this.scheme.getStorageManager().getObjectsBoundingRect(); let imageWidth = imageBoundingRect.right; let imageHeight = imageBoundingRect.bottom; let mapWidth = this.mapView.getWidth(); let mapHeight = this.mapView.getHeight(); let mapRatio = mapWidth / mapHeight; let imageRatio = imageWidth / imageHeight; let scaleFactor = mapRatio < imageRatio ? mapWidth / imageWidth : mapHeight / imageHeight; let newImageWidth = imageWidth * scaleFactor; let newImageHeight = imageHeight * scaleFactor; let leftOffset = (mapWidth - newImageWidth) / 2; let topOffset = (mapHeight - newImageHeight) / 2; return { scaleFactor: scaleFactor, width: newImageWidth, height: newImageHeight, leftOffset: leftOffset, topOffset: topOffset }; } /** * Get rect dimensions * @param scaledSchemeRect * @returns BoundingRect */ protected getRectBoundingRect(scaledSchemeRect: ScaledRect): BoundingRect { let visibleBoundingRect = this.scheme.getVisibleBoundingRect(); let rectX = visibleBoundingRect.left * scaledSchemeRect.scaleFactor + scaledSchemeRect.leftOffset; let rectY = visibleBoundingRect.top * scaledSchemeRect.scaleFactor + scaledSchemeRect.topOffset; let rectWidth = (visibleBoundingRect.right - visibleBoundingRect.left) * scaledSchemeRect.scaleFactor; let rectHeight = (visibleBoundingRect.bottom - visibleBoundingRect.top) * scaledSchemeRect.scaleFactor; return { left: rectX, top: rectY, right: rectX + rectWidth, bottom: rectY + rectHeight }; } /** * Draw map * @returns {boolean} */ public drawMap(): boolean { let cacheView = this.scheme.getCacheView(); if (!this.mapView || !cacheView) { return false; } let scaledSchemeRect = this.getScaledSchemeRect(); let mapContext = this.mapView.getContext(); mapContext.clearRect( 0, 0, this.mapView.getWidth(), this.mapView.getHeight() ); mapContext.drawImage( cacheView.getCanvas(), scaledSchemeRect.leftOffset, scaledSchemeRect.topOffset, scaledSchemeRect.width, scaledSchemeRect.height ); let rectBoundingRect = this.getRectBoundingRect(scaledSchemeRect); this.drawRect(rectBoundingRect); return true; } /** * Draw rect * @param boundingRect */ protected drawRect(boundingRect: BoundingRect): void { let mapContext = this.mapView.getContext(); mapContext.lineWidth = 1; mapContext.strokeStyle = '#000'; mapContext.strokeRect( boundingRect.left, boundingRect.top, boundingRect.right - boundingRect.left, boundingRect.bottom - boundingRect.top ); let rectBackgroundWidth = this.mapView.getWidth() * 2; let rectBackgroundHeight = this.mapView.getHeight() * 2; let backgroundColor = 'rgba(0, 0, 0, 0.1)'; mapContext.fillStyle = backgroundColor; mapContext.strokeStyle = backgroundColor; mapContext.lineWidth = 0; mapContext.fillRect( 0, 0, boundingRect.left, rectBackgroundHeight ); mapContext.fillRect( boundingRect.left, 0, boundingRect.right - boundingRect.left, boundingRect.top ); mapContext.fillRect( boundingRect.right, 0, rectBackgroundWidth, rectBackgroundHeight ); mapContext.fillRect( boundingRect.left, boundingRect.bottom, boundingRect.right - boundingRect.left, rectBackgroundHeight ); } /** * Set mapCanvas * @param value */ public setMapCanvas(value: HTMLCanvasElement): void { this.mapCanvas = value; this.mapView = new View(this.mapCanvas); this.bindEvents(); Tools.disableElementSelection(this.mapCanvas); } /** * Resize map view */ public resize(): void { if (this.mapView) { this.mapView.resize(); } } /** * Bind events */ protected bindEvents(): void { // mouse events this.mapCanvas.addEventListener('mousedown', (e: MouseEvent) => { this.onMouseDown(e); }); this.mapCanvas.addEventListener('mouseup', (e: MouseEvent) => { this.onMouseUp(e); }); this.mapCanvas.addEventListener('mousemove', (e: MouseEvent) => { this.onMouseMove(e); }); this.mapCanvas.addEventListener('mouseout', (e: MouseEvent) => { this.onMouseOut(e); }); this.mapCanvas.addEventListener('click', (e: MouseEvent) => { this.onClick(e); }); // wheel this.mapCanvas.addEventListener('mousewheel', (e: MouseWheelEvent) => { this.onMouseWheel(e); }); // for FF this.mapCanvas.addEventListener('DOMMouseScroll', (e: MouseWheelEvent) => { this.onMouseWheel(e); }); } /** * Zoom by wheel * @param e */ protected onMouseWheel(e: MouseWheelEvent): void { let delta = e.wheelDelta ? e.wheelDelta / 40 : e.detail ? -e.detail : 0; if (delta) { let eventCoordinates = this.getCoordinatesFromEvent(e); this.scrollByCoordinates(eventCoordinates); this.scheme.getZoomManager().zoomToCenter(delta); } return e.preventDefault() && false; } /** * Mouse down * @param e */ protected onMouseDown(e: MouseEvent | TouchEvent): void { this.leftButtonDown = true; this.setLastClientPositionFromEvent(e); } /** * Mouse out * @param e */ protected onMouseOut(e: MouseEvent): void { this.setLastClientPositionFromEvent(e); this.leftButtonDown = false; this.isDragging = false; } /** * Set cursor style * @param {string} cursor * @returns {SchemeDesigner} */ public setCursorStyle(cursor: string): this { this.mapCanvas.style.cursor = cursor; return this; } /** * Mouse up * @param e */ protected onMouseUp(e: MouseEvent | TouchEvent): void { this.leftButtonDown = false; this.setLastClientPositionFromEvent(e); if (this.isDragging) { let eventCoordinates = this.getCoordinatesFromEvent(e); this.scrollByCoordinates(eventCoordinates); this.setCursorStyle('default'); } // defer for prevent trigger click on mouseUp setTimeout(() => {this.isDragging = false; }, 1); } /** * On mouse move * @param e */ protected onMouseMove(e: MouseEvent | TouchEvent): void { if (this.leftButtonDown) { let newCoordinates = this.getCoordinatesFromEvent(e); let deltaX = Math.abs(newCoordinates.x - this.getLastClientX()); let deltaY = Math.abs(newCoordinates.y - this.getLastClientY()); // 1 - is click with offset - mis drag if (deltaX > 1 || deltaY > 1) { this.isDragging = true; this.setCursorStyle('move'); } } if (this.isDragging) { let eventCoordinates = this.getCoordinatesFromEvent(e); this.scrollByCoordinates(eventCoordinates); } } /** * Set last client position * @param e */ protected setLastClientPositionFromEvent(e: MouseEvent | TouchEvent): void { let coordinates = this.getCoordinatesFromEvent(e); this.setLastClientPosition(coordinates); } /** * Set last client position * @param coordinates */ protected setLastClientPosition(coordinates: Coordinates): void { this.lastClientPosition = coordinates; } /** * Get last client x * @returns {number} */ protected getLastClientX(): number { return this.lastClientPosition.x; } /** * Get last client y * @returns {number} */ protected getLastClientY(): number { return this.lastClientPosition.y; } /** * Get real scheme coordinates * @param coordinates * @returns {{x: number, y: number}} */ protected getRealCoordinates(coordinates: Coordinates): Coordinates { let scaledSchemeRect = this.getScaledSchemeRect(); let schemeScale = this.scheme.getZoomManager().getScale(); let boundingRect = this.scheme.getStorageManager().getObjectsBoundingRect(); let rectBoundingRect = this.getRectBoundingRect(scaledSchemeRect); let rectWidth = rectBoundingRect.right - rectBoundingRect.left; let rectHeight = rectBoundingRect.bottom - rectBoundingRect.top; let realX = (coordinates.x - scaledSchemeRect.leftOffset - (rectWidth / 2)) / scaledSchemeRect.scaleFactor; let realY = (coordinates.y - scaledSchemeRect.topOffset - (rectHeight / 2)) / scaledSchemeRect.scaleFactor; // process scheme scale let x = (realX - boundingRect.left) * schemeScale; let y = (realY - boundingRect.top) * schemeScale; return { x: x, y: y }; } /** * Scroll by coordinates * @param coordinates */ protected scrollByCoordinates(coordinates: Coordinates): void { let realCoordinates = this.getRealCoordinates(coordinates); this.scheme.getScrollManager().scroll(-realCoordinates.x, -realCoordinates.y); } /** * On click * @param e */ protected onClick(e: MouseEvent): void { if (!this.isDragging) { let eventCoordinates = this.getCoordinatesFromEvent(e); this.scrollByCoordinates(eventCoordinates); } } /** * Get coordinates from event * @param e * @returns {number[]} */ protected getCoordinatesFromEvent(e: MouseEvent | TouchEvent): Coordinates { let clientRect = this.mapCanvas.getBoundingClientRect(); let x = Tools.getPointer(e, 'clientX') - clientRect.left; let y = Tools.getPointer(e, 'clientY') - clientRect.top; return {x, y}; } } }
the_stack
import React from 'react' import { NextPage } from 'next' // import { UsersService } from '../services/users' import { OpenPaymentsButton, Logo, Decor, Phone, Browser, Footer } from '../components' import { useRouter } from 'next/router' type sectionProps = { header ?: string } const Section: React.FC<sectionProps> = (props) => { return ( <div className="flex flex-col text-left"> <div className="mb-8 md:font-light text-2xl sm:text-4xl text-gray"> {props.header} </div> {props.children} </div> ) } const Divider: React.FC = () => { return ( <div className="border-b border-gray border-opacity-12 my-20"/> ) } const Card: React.FC = (props) => { let className = 'p-8 sm:p-16 bg-white elevation-2 rounded w-full' return ( <div className={className}> {props.children} </div> ) } type colourBoxProps = { colour: string name: string padding?: string } const ColourBox: React.FC<colourBoxProps> = (props) => { return ( <div className={`w-full lg:w-2/12 flex flex-col ${props.padding}`}> <div className={`bg-${props.colour} flex content-center h-12 sm:h-16 mb-2 rounded-md`}/> <div className="text-base text-gray mb-4"> {props.name} </div> </div> ) } const Home: NextPage = () => { const router = useRouter() return ( <div className="relative overflow-hidden w-full"> <Decor/> <div className="container mx-auto flex flex-col text-left justify-center px-16 md:px-32 py-16"> <div className="text-lg sm:text-xl md:text-3xl my-4"> Brand guidelines </div> <div className="md:font-light text-3xl md:text-5xl text-primary"> Representing the <br className="sm:hidden"/> Open Payments brand </div> <div className="text-base flex mt-6"> <a className="focus:outline-none hover:text-orange-other text-primary align-middle flex flex-row" href="/Open_Payments_Brand_Assets.zip" download> <div>Download all assets </div><i className={`material-icons ml-2`}>get_app</i> </a> </div> </div> <div className="container mx-auto flex flex-col text-left justify-center py-12 px-4 sm:px-12"> <Card> <Section header="Logo"> <div className="text-sm text-gray-light mb-16"> Do not use the Open Payments mark or any variant of the Open Payments mark in conjunction with the overall name of your application, product, service, or website. Do not alter or use the Open Payments mark in a way that may be confusing or misleading, and never use Open Payments branding as the most prominent element on your page. </div> <div className="flex flex-col lg:flex-row"> <div className="w-full lg:w-1/2 flex flex-col pr-0 lg:pr-8"> <div className="flex content-center h-48 sm:h-56 mb-4 p-8 border border-gray border-opacity-12 rounded-md"> <img className="mx-auto self-center max-w-full" src="/Open_Payments_standard_logo.svg"/> </div> <div className="text-lg sm:text-xl text-gray mb-16 lg:mb-0"> Standard lockup<br/> <p className="text-sm text-gray-light mt-4"> The standard lockup can be used in slide decks and blog posts. <br/> Whenever possible, the logo should be represented as a horizontal lockup with a full color logomark and #1E3250 or solid white logotype. </p> </div> </div> <div className="w-full lg:w-1/2 flex flex-col pl-0 lg:pl-8"> <div className="flex content-center h-48 sm:h-56 mb-4 p-8 border border-gray border-opacity-12 rounded-md"> <img className="mx-auto self-center max-h-full" src="/Open_Payments_logomark.svg"/> </div> <div className="text-lg sm:text-xl text-gray"> Logomark<br/> <p className="text-sm text-gray-light mt-4"> When there is limited vertical and horizontal space, the logomark can be used by itself without the logotype. </p> </div> </div> </div> </Section> <Divider/> <Section header="Colours"> <div className="flex flex-row lg:flex-col"> <div className="flex flex-col lg:flex-row w-full"> <ColourBox colour="red" name="#CE6564" padding="px-2 sm:px-4"/> <ColourBox colour="orange" name="#F47F5F" padding="px-2 sm:px-4"/> <ColourBox colour="green" name="#6D995C" padding="px-2 sm:px-4"/> <ColourBox colour="cyan" name="#459789" padding="px-2 sm:px-4"/> <ColourBox colour="teal" name="#51797D" padding="px-2 sm:px-4"/> <ColourBox colour="purple" name="#845578" padding="px-2 sm:px-4"/> </div> <div className="flex flex-col lg:flex-row w-full"> <ColourBox colour="red-light" name="#F59297" padding="px-2 sm:px-4"/> <ColourBox colour="orange-light" name="#FCC9B3" padding="px-2 sm:px-4"/> <ColourBox colour="green-light" name="#7FC78C" padding="px-2 sm:px-4"/> <ColourBox colour="cyan-light" name="#8FD1C1" padding="px-2 sm:px-4"/> <ColourBox colour="teal-light" name="#9EC7D0" padding="px-2 sm:px-4"/> <ColourBox colour="purple-light" name="#978AA4" padding="px-2 sm:px-4"/> </div> </div> <div className="text-lg sm:text-xl text-gray mb-16"> Logo<br/> <p className="text-sm text-gray-light mt-4"> The Open Payments logo consists of 6 base colours, each with a light secondary variant. </p> </div> <div className="flex flex-row lg:hidden"> <div className="flex flex-col lg:flex-row w-full"> <ColourBox colour="primary" name="#1E3250" padding="px-2 sm:px-4"/> </div> <div className="flex flex-col lg:flex-row w-full"> <ColourBox colour="orange-other" name="#FABD84" padding="px-2 sm:px-4"/> </div> </div> <div className="hidden flex-row lg:flex"> <div className="flex flex-col lg:flex-row w-full"> <ColourBox colour="primary" name="#1E3250" padding="px-2 sm:px-4"/> <ColourBox colour="orange-other" name="#FABD84" padding="px-2 sm:px-4"/> </div> </div> <div className="text-lg sm:text-xl text-gray"> Emphasis<br/> <p className="text-sm text-gray-light mt-4"> There are two auxilary colours which are used for emphasis or text. </p> </div> </Section> <Divider/> <Section header="Payment button"> <div className="text-sm text-gray-light"> These guidelines are to be used as a reference point when implementing an Open Payments payment button within your app or website. The Open Payments payment button must always use the Open Payments specification when making payments. <br/><br/> <div className="mb-16"> All Open Payments payment buttons within your app or website must adhere to our brand guidelines, which include, but are not limited to, the following requirements: </div> <div className="flex flex-col lg:flex-row mb-16"> <div className="w-full lg:w-1/3 flex flex-col pr-0 lg:pr-8"> <div className="flex content-center h-48 sm:h-56 mb-4 p-8 border border-gray border-opacity-12 rounded-md"> <img className="mx-auto self-center max-w-full" src="/Specification.svg"/> </div> <div className="text-lg sm:text-xl text-gray mb-16 lg:mb-0"> Specification<br/> <p className="text-sm text-gray-light mt-4"> Open Payments logo size 24&nbsp;dp.<br/> Minimum width 90&nbsp;dp, and minimum height 48&nbsp;dp.<br/> Minimum <span className="text-teal-light font-bold">8&nbsp;dp margin</span> on all sides of the button.<br/> Minimum <span className="text-orange-light font-bold">8&nbsp;dp padding</span> between elements inside the button.<br/> Content must be vertically centered. </p> </div> </div> <div className="w-full lg:w-1/3 flex flex-col px-0 lg:px-8"> <div className="flex content-center h-48 sm:h-56 mb-4 border border-gray border-opacity-12 rounded-md"> <div className="flex content-center w-full h-full rounded-l-md text-white bg-cyan-light"> <OpenPaymentsButton verb="Pay" className="mx-auto self-center rounded-md text-black bg-white elevation-3"/> </div> <div className="flex content-center w-full h-full rounded-md text-white"> <OpenPaymentsButton verb="Pay" className="mx-auto self-center rounded-md text-white bg-black elevation-3"/> </div> </div> <div className="text-lg sm:text-xl text-gray mb-16 lg:mb-0"> Contrast<br/> <p className="text-sm text-gray-light mt-4"> The button colour must contrast with the background colour of the surrounding area.<br/> Use white buttons on dark or colourful backgrounds.<br/> Use black buttons on white or light background. </p> </div> </div> <div className="w-full lg:w-1/3 flex flex-col pl-0 lg:pl-8"> <div className="flex content-center h-48 sm:h-56 mb-4 border border-gray border-opacity-12 rounded-md"> <div className="flex content-center w-full h-full text-black border-r border-gray border-opacity-12"> <span className="w-full text-right mr-2 self-center text-md"> Rubik<br/> Regular<br/> 20 </span> </div> <div className="flex content-center w-full h-full text-black"> <span className=" ml-2 self-center text-xl">Button</span> </div> </div> <div className="text-lg sm:text-xl text-gray"> Text<br/> <p className="text-sm text-gray-light mt-4"> The text on the button must be a single, title case, verb. For example, Pay, Tip, Donate, Subscribe, Buy, etc.<br/> The text should always be to the right of the logo. </p> </div> </div> </div> <div className="mb-16"> Although Open Payments payment buttons must adhere to the above brand guidelines, specific implementations may vary to fit into the branding or style of your app or website, which can include: </div> </div> <div className="flex flex-col lg:flex-row"> <div className="w-full lg:w-1/3 flex flex-col pr-0 lg:pr-8"> <div className="flex content-center h-48 sm:h-56 bg-cyan-light rounded-full mb-4"> <OpenPaymentsButton verb="Donate" className="w-8/12 mx-auto self-center rounded-full text-black bg-white elevation-3"/> </div> <div className="text-lg sm:text-xl text-gray mb-16 lg:mb-0"> Shape<br/> <p className="text-sm text-gray-light mt-4"> Variations in the button's corner radius and shape, to match other elements on the page. Note the larger width and corner radius. </p> </div> </div> <div className="w-full lg:w-1/3 flex flex-col px-0 lg:px-8"> <div className="flex content-center h-48 sm:h-56 mb-4 border border-gray border-opacity-12 rounded-md"> <OpenPaymentsButton verb="Tip" className="mx-auto self-center rounded-md text-white bg-black elevation-8"/> </div> <div className="text-lg sm:text-xl text-gray mb-16 lg:mb-0"> Elevation<br/> <p className="text-sm text-gray-light mt-4"> Variations in the elevation or shadow of the button. Note the higher elevation. </p> </div> </div> <div className="w-full lg:w-1/3 flex flex-col pl-0 lg:pl-8"> <div className="flex content-center h-48 sm:h-56 bg-cyan-light rounded-md mb-4"> <OpenPaymentsButton verb="Subscribe" className="mx-auto self-center rounded-md text-black bg-white elevation-1 hover:elevation-6 focus:elevation-24"/> </div> <div className="text-lg sm:text-xl text-gray"> State<br/> <p className="text-sm text-gray-light mt-4"> Variations specific states of the button, such as active, hover, or focus. Note the change in elevation with the various states. </p> </div> </div> </div> </Section> <Divider/> <Section header="Pay mark"> <div className="text-sm text-gray-light"> The Open Payments pay mark should be used when displaying Open Payments as a payment option in a payment flow. <div className="flex flex-col lg:flex-row my-16"> <div className="w-full lg:w-1/2 flex flex-col pr-0 lg:pr-8"> <div className="flex content-center h-48 sm:h-56 mb-4 border border-gray border-opacity-12 rounded-md"> <img className="mx-auto self-center w-1/2 sm:w-1/4 " src="/Open_Payments_mark.svg"/> </div> <div className="text-lg sm:text-xl text-gray mb-16 lg:mb-0"> Mark<br/> <p className="text-sm text-gray-light mt-4"> Do not change the color or weight of the mark's outline or alter the mark in any way. Use only the mark provided by Open Payments. </p> </div> </div> <div className="w-full lg:w-1/2 flex flex-col pl-0 lg:pl-8"> <div className="flex flex-col p-4 justify-center h-48 sm:h-56 mb-4 border border-gray border-opacity-12 rounded-md"> <div className="flex"> <div className="text-primary align-middle h-12 flex flex-row justify-between" > <div className="flex flex-row"> <img className="m-2 w-2/12 sm:1/12" src="/Open_Payments_mark.svg"/> <div className="text-xs my-auto">Open Payments</div> </div> <i className={`self-center material-icons`}>navigate_next</i> </div> </div> <div className="border-b border-gray border-opacity-12"/> <div className="flex"> <div className="text-primary align-middle h-12 flex flex-row justify-between" > <div className="flex flex-row"> <img className="m-2 w-2/12 sm:1/12" src="/Rafiki Mark.svg"/> <div className="text-xs my-auto">Generic Pay</div> </div> <i className={`self-center material-icons`}>navigate_next</i> </div> </div> <div className="border-b border-gray border-opacity-12"/> <div className="flex"> <div className="text-primary align-middle h-12 flex flex-row justify-between" > <div className="flex flex-row"> <img className="m-2 w-2/12 sm:1/12" src="/CARD Mark.svg"/> <div className="text-xs my-auto">**** 4242</div> </div> <i className={`self-center material-icons`}>navigate_next</i> </div> </div> </div> <div className="text-lg sm:text-xl text-gray"> Size<br/> <p className="text-sm text-gray-light mt-4"> If needed, adjust the height of the mark to match other brand identities displayed in your payment flow. Always maintain the minimum clear space of 8&nbsp;dp on all sides of the mark. </p> </div> </div> </div> </div> </Section> {/* <Divider/> <Section header="In text"> <div className="text-sm text-gray-light"> Do not use the Open Payments mark or any variant of the Open Payments mark in conjunction with the overall name of your application, product, service, or website. Do not alter or use the Open Payments mark in a way that may be confusing or misleading, and never use Open Payments branding as the most prominent element on your page. </div> <div className="flex flex-col lg:flex-row"> <div className="w-full lg:w-1/2 flex flex-col pr-0 lg:pr-8"> <div className="flex content-center h-48 sm:h-56"> <img className="mx-auto self-center" src="/Standard lockup.png"/> </div> <div className="text-lg sm:text-xl text-gray"> Standard lockup<br/> <p className="text-sm text-gray-light mt-4"> The standard lockup can be used in slide decks and blog posts. <br/> Whenever possible, the logo should be represented as a horizontal lockup with a full color logomark and #1E3250 or solid white logotype. </p> </div> </div> <div className="w-full lg:w-1/2 flex flex-col pl-0 lg:pl-8"> <div className="flex content-center h-48 sm:h-56"> <Logo className="w-1/2 sm:w-1/4 mx-auto self-center"/> </div> <div className="text-lg sm:text-xl text-gray"> Logomark<br/> <p className="text-sm text-gray-light mt-4"> When there is limited vertical and horizontal space, the logomark can be used by itself without the logotype. </p> </div> </div> </div> </Section> */} </Card> </div> <Footer bg="red"> <div className="flex flex-col items-center justify-center text-white wrap"> <div className="flex flex-row items-start justify-center w-full"> <div className="flex flex-col w-card"> <div className="text-lg font-medium mb-4">Protocol</div> <a className="text-base md:opacity-60 md:hover:opacity-100 mb-1" href="https://docs.openpayments.dev"> Specification </a> <a className="text-base md:opacity-60 md:hover:opacity-100 mb-1" href="https://openpayments.dev/brand-guidelines"> Brand guidelines </a> </div> <div className="flex flex-col w-card"> <div className="text-lg font-medium mb-4">Community</div> <a className="text-base md:opacity-60 md:hover:opacity-100 mb-1" href="https://communityinviter.com/apps/interledger/interledger-working-groups-slack"> Slack </a> <a className="text-base md:opacity-60 md:hover:opacity-100 mb-4" href="https://github.com/adrianhopebailie/open-payments"> Github </a> </div> </div> <div className="w-full text-center sm:text-right text-xs"> Copyright &copy; 2019 - {new Date().getFullYear()} Interledger Foundation </div> </div> </Footer> </div> ) } export default Home
the_stack
import { CloudErrorMapper, BaseResourceMapper } from "@azure/ms-rest-azure-js"; import * as msRest from "@azure/ms-rest-js"; export const CloudError = CloudErrorMapper; export const BaseResource = BaseResourceMapper; export const CreatorProperties: msRest.CompositeMapper = { serializedName: "CreatorProperties", type: { name: "Composite", className: "CreatorProperties", modelProperties: { provisioningState: { readOnly: true, serializedName: "provisioningState", type: { name: "String" } }, storageUnits: { required: true, serializedName: "storageUnits", constraints: { InclusiveMaximum: 100, InclusiveMinimum: 1 }, type: { name: "Number" } } } } }; export const Creator: msRest.CompositeMapper = { serializedName: "Creator", type: { name: "Composite", className: "Creator", modelProperties: { properties: { required: true, serializedName: "properties", type: { name: "Composite", className: "CreatorProperties" } } } } }; export const Sku: msRest.CompositeMapper = { serializedName: "Sku", type: { name: "Composite", className: "Sku", modelProperties: { name: { required: true, serializedName: "name", type: { name: "String" } }, tier: { readOnly: true, serializedName: "tier", type: { name: "String" } } } } }; export const SystemData: msRest.CompositeMapper = { serializedName: "systemData", type: { name: "Composite", className: "SystemData", modelProperties: { createdBy: { serializedName: "createdBy", type: { name: "String" } }, createdByType: { serializedName: "createdByType", type: { name: "String" } }, createdAt: { serializedName: "createdAt", type: { name: "DateTime" } }, lastModifiedBy: { serializedName: "lastModifiedBy", type: { name: "String" } }, lastModifiedByType: { serializedName: "lastModifiedByType", type: { name: "String" } }, lastModifiedAt: { serializedName: "lastModifiedAt", type: { name: "DateTime" } } } } }; export const MapsAccountProperties: msRest.CompositeMapper = { serializedName: "MapsAccountProperties", type: { name: "Composite", className: "MapsAccountProperties", modelProperties: { uniqueId: { readOnly: true, serializedName: "uniqueId", type: { name: "String" } }, disableLocalAuth: { serializedName: "disableLocalAuth", defaultValue: false, type: { name: "Boolean" } }, provisioningState: { readOnly: true, serializedName: "provisioningState", type: { name: "String" } } } } }; export const MapsAccount: msRest.CompositeMapper = { serializedName: "MapsAccount", type: { name: "Composite", className: "MapsAccount", modelProperties: { sku: { required: true, serializedName: "sku", type: { name: "Composite", className: "Sku" } }, kind: { serializedName: "kind", defaultValue: "Gen1", type: { name: "String" } }, systemData: { readOnly: true, serializedName: "systemData", type: { name: "Composite", className: "SystemData" } }, properties: { serializedName: "properties", type: { name: "Composite", className: "MapsAccountProperties" } } } } }; export const MapsAccountUpdateParameters: msRest.CompositeMapper = { serializedName: "MapsAccountUpdateParameters", type: { name: "Composite", className: "MapsAccountUpdateParameters", modelProperties: { tags: { serializedName: "tags", type: { name: "Dictionary", value: { type: { name: "String" } } } }, kind: { serializedName: "kind", defaultValue: "Gen1", type: { name: "String" } }, sku: { serializedName: "sku", type: { name: "Composite", className: "Sku" } }, uniqueId: { readOnly: true, serializedName: "properties.uniqueId", type: { name: "String" } }, disableLocalAuth: { serializedName: "properties.disableLocalAuth", defaultValue: false, type: { name: "Boolean" } }, provisioningState: { readOnly: true, serializedName: "properties.provisioningState", type: { name: "String" } } } } }; export const CreatorUpdateParameters: msRest.CompositeMapper = { serializedName: "CreatorUpdateParameters", type: { name: "Composite", className: "CreatorUpdateParameters", modelProperties: { tags: { serializedName: "tags", type: { name: "Dictionary", value: { type: { name: "String" } } } }, provisioningState: { readOnly: true, serializedName: "properties.provisioningState", type: { name: "String" } }, storageUnits: { required: true, serializedName: "properties.storageUnits", constraints: { InclusiveMaximum: 100, InclusiveMinimum: 1 }, type: { name: "Number" } } } } }; export const MapsKeySpecification: msRest.CompositeMapper = { serializedName: "MapsKeySpecification", type: { name: "Composite", className: "MapsKeySpecification", modelProperties: { keyType: { required: true, serializedName: "keyType", type: { name: "String" } } } } }; export const MapsAccountKeys: msRest.CompositeMapper = { serializedName: "MapsAccountKeys", type: { name: "Composite", className: "MapsAccountKeys", modelProperties: { primaryKeyLastUpdated: { readOnly: true, serializedName: "primaryKeyLastUpdated", type: { name: "String" } }, primaryKey: { readOnly: true, serializedName: "primaryKey", type: { name: "String" } }, secondaryKey: { readOnly: true, serializedName: "secondaryKey", type: { name: "String" } }, secondaryKeyLastUpdated: { readOnly: true, serializedName: "secondaryKeyLastUpdated", type: { name: "String" } } } } }; export const OperationDisplay: msRest.CompositeMapper = { serializedName: "OperationDisplay", type: { name: "Composite", className: "OperationDisplay", modelProperties: { provider: { serializedName: "provider", type: { name: "String" } }, resource: { serializedName: "resource", type: { name: "String" } }, operation: { serializedName: "operation", type: { name: "String" } }, description: { serializedName: "description", type: { name: "String" } } } } }; export const Dimension: msRest.CompositeMapper = { serializedName: "Dimension", type: { name: "Composite", className: "Dimension", modelProperties: { name: { serializedName: "name", type: { name: "String" } }, displayName: { serializedName: "displayName", type: { name: "String" } } } } }; export const MetricSpecification: msRest.CompositeMapper = { serializedName: "MetricSpecification", type: { name: "Composite", className: "MetricSpecification", modelProperties: { name: { serializedName: "name", type: { name: "String" } }, displayName: { serializedName: "displayName", type: { name: "String" } }, displayDescription: { serializedName: "displayDescription", type: { name: "String" } }, unit: { serializedName: "unit", type: { name: "String" } }, dimensions: { serializedName: "dimensions", type: { name: "Sequence", element: { type: { name: "Composite", className: "Dimension" } } } }, aggregationType: { serializedName: "aggregationType", type: { name: "String" } }, fillGapWithZero: { serializedName: "fillGapWithZero", type: { name: "Boolean" } }, category: { serializedName: "category", type: { name: "String" } }, resourceIdDimensionNameOverride: { serializedName: "resourceIdDimensionNameOverride", type: { name: "String" } } } } }; export const ServiceSpecification: msRest.CompositeMapper = { serializedName: "ServiceSpecification", type: { name: "Composite", className: "ServiceSpecification", modelProperties: { metricSpecifications: { serializedName: "metricSpecifications", type: { name: "Sequence", element: { type: { name: "Composite", className: "MetricSpecification" } } } } } } }; export const OperationDetail: msRest.CompositeMapper = { serializedName: "OperationDetail", type: { name: "Composite", className: "OperationDetail", modelProperties: { name: { serializedName: "name", type: { name: "String" } }, isDataAction: { serializedName: "isDataAction", type: { name: "Boolean" } }, display: { serializedName: "display", type: { name: "Composite", className: "OperationDisplay" } }, origin: { serializedName: "origin", type: { name: "String" } }, serviceSpecification: { serializedName: "properties.serviceSpecification", type: { name: "Composite", className: "ServiceSpecification" } } } } }; export const Resource: msRest.CompositeMapper = { serializedName: "Resource", type: { name: "Composite", className: "Resource", modelProperties: { id: { readOnly: true, serializedName: "id", type: { name: "String" } }, name: { readOnly: true, serializedName: "name", type: { name: "String" } }, type: { readOnly: true, serializedName: "type", type: { name: "String" } } } } }; export const ProxyResource: msRest.CompositeMapper = { serializedName: "ProxyResource", type: { name: "Composite", className: "ProxyResource", modelProperties: { ...Resource.type.modelProperties } } }; export const AzureEntityResource: msRest.CompositeMapper = { serializedName: "AzureEntityResource", type: { name: "Composite", className: "AzureEntityResource", modelProperties: { ...Resource.type.modelProperties, etag: { readOnly: true, serializedName: "etag", type: { name: "String" } } } } }; export const TrackedResource: msRest.CompositeMapper = { serializedName: "TrackedResource", type: { name: "Composite", className: "TrackedResource", modelProperties: { ...Resource.type.modelProperties, tags: { serializedName: "tags", type: { name: "Dictionary", value: { type: { name: "String" } } } }, location: { required: true, serializedName: "location", type: { name: "String" } } } } }; export const ErrorAdditionalInfo: msRest.CompositeMapper = { serializedName: "ErrorAdditionalInfo", type: { name: "Composite", className: "ErrorAdditionalInfo", modelProperties: { type: { readOnly: true, serializedName: "type", type: { name: "String" } }, info: { readOnly: true, serializedName: "info", type: { name: "Object" } } } } }; export const ErrorDetail: msRest.CompositeMapper = { serializedName: "ErrorDetail", type: { name: "Composite", className: "ErrorDetail", modelProperties: { code: { readOnly: true, serializedName: "code", type: { name: "String" } }, message: { readOnly: true, serializedName: "message", type: { name: "String" } }, target: { readOnly: true, serializedName: "target", type: { name: "String" } }, details: { readOnly: true, serializedName: "details", type: { name: "Sequence", element: { type: { name: "Composite", className: "ErrorDetail" } } } }, additionalInfo: { readOnly: true, serializedName: "additionalInfo", type: { name: "Sequence", element: { type: { name: "Composite", className: "ErrorAdditionalInfo" } } } } } } }; export const ErrorResponse: msRest.CompositeMapper = { serializedName: "ErrorResponse", type: { name: "Composite", className: "ErrorResponse", modelProperties: { error: { serializedName: "error", type: { name: "Composite", className: "ErrorDetail" } } } } }; export const MapsAccounts: msRest.CompositeMapper = { serializedName: "MapsAccounts", type: { name: "Composite", className: "MapsAccounts", modelProperties: { value: { readOnly: true, serializedName: "", type: { name: "Sequence", element: { type: { name: "Composite", className: "MapsAccount" } } } }, nextLink: { serializedName: "nextLink", type: { name: "String" } } } } }; export const MapsOperations: msRest.CompositeMapper = { serializedName: "MapsOperations", type: { name: "Composite", className: "MapsOperations", modelProperties: { value: { readOnly: true, serializedName: "", type: { name: "Sequence", element: { type: { name: "Composite", className: "OperationDetail" } } } }, nextLink: { serializedName: "nextLink", type: { name: "String" } } } } }; export const CreatorList: msRest.CompositeMapper = { serializedName: "CreatorList", type: { name: "Composite", className: "CreatorList", modelProperties: { value: { readOnly: true, serializedName: "", type: { name: "Sequence", element: { type: { name: "Composite", className: "Creator" } } } }, nextLink: { serializedName: "nextLink", type: { name: "String" } } } } };
the_stack
import { Scanner, createScanner, CHAR_SP as SPACE, CHAR_LF as NEW_LINE } from './scanner' import { SourceLocation, Position, createLocation, createPosition } from './location' import { TokenizeOptions } from './options' import { createCompileError, CompileErrorCodes } from './errors' export const enum TokenTypes { Text, // 0 Pipe, BraceLeft, BraceRight, Modulo, Named, // 5 List, Literal, LinkedAlias, LinkedDot, LinkedDelimiter, // 10 LinkedKey, LinkedModifier, InvalidPlace, EOF } const enum TokenChars { Pipe = '|', BraceLeft = '{', BraceRight = '}', Modulo = '%', LinkedAlias = '@', LinkedDot = '.', LinkedDelimiter = ':' } const EOF = undefined const LITERAL_DELIMITER = "'" export const ERROR_DOMAIN = 'tokenizer' export interface Token { type: TokenTypes value?: string loc?: SourceLocation } export interface TokenizeContext { currentType: TokenTypes offset: number startLoc: Position endLoc: Position lastType: TokenTypes lastOffset: number lastStartLoc: Position lastEndLoc: Position braceNest: number inLinked: boolean text: string } export interface Tokenizer { currentPosition(): Position currentOffset(): number context(): TokenizeContext nextToken(): Token } export function createTokenizer( source: string, options: TokenizeOptions = {} ): Tokenizer { const location = options.location !== false const _scnr = createScanner(source) const currentOffset = (): number => _scnr.index() const currentPosition = (): Position => createPosition(_scnr.line(), _scnr.column(), _scnr.index()) const _initLoc = currentPosition() const _initOffset = currentOffset() const _context: TokenizeContext = { currentType: TokenTypes.EOF, offset: _initOffset, startLoc: _initLoc, endLoc: _initLoc, lastType: TokenTypes.EOF, lastOffset: _initOffset, lastStartLoc: _initLoc, lastEndLoc: _initLoc, braceNest: 0, inLinked: false, text: '' } const context = (): TokenizeContext => _context const { onError } = options function emitError( code: CompileErrorCodes, pos: Position, offset: number, ...args: unknown[] ): void { const ctx = context() pos.column += offset pos.offset += offset if (onError) { const loc = createLocation(ctx.startLoc, pos) const err = createCompileError(code, loc, { domain: ERROR_DOMAIN, args }) onError(err) } } function getToken( context: TokenizeContext, type: TokenTypes, value?: string ): Token { context.endLoc = currentPosition() context.currentType = type const token = { type } as Token if (location) { token.loc = createLocation(context.startLoc, context.endLoc) } if (value != null) { token.value = value } return token } const getEndToken = (context: TokenizeContext): Token => getToken(context, TokenTypes.EOF) function eat(scnr: Scanner, ch: string): string { if (scnr.currentChar() === ch) { scnr.next() return ch } else { emitError(CompileErrorCodes.EXPECTED_TOKEN, currentPosition(), 0, ch) return '' } } function peekSpaces(scnr: Scanner): string { let buf = '' while (scnr.currentPeek() === SPACE || scnr.currentPeek() === NEW_LINE) { buf += scnr.currentPeek() scnr.peek() } return buf } function skipSpaces(scnr: Scanner): string { const buf = peekSpaces(scnr) scnr.skipToPeek() return buf } function isIdentifierStart(ch: string): boolean { if (ch === EOF) { return false } const cc = ch.charCodeAt(0) return ( (cc >= 97 && cc <= 122) || // a-z (cc >= 65 && cc <= 90) || // A-Z cc === 95 // _ ) } function isNumberStart(ch: string): boolean { if (ch === EOF) { return false } const cc = ch.charCodeAt(0) return cc >= 48 && cc <= 57 // 0-9 } function isNamedIdentifierStart( scnr: Scanner, context: TokenizeContext ): boolean { const { currentType } = context if (currentType !== TokenTypes.BraceLeft) { return false } peekSpaces(scnr) const ret = isIdentifierStart(scnr.currentPeek()) scnr.resetPeek() return ret } function isListIdentifierStart( scnr: Scanner, context: TokenizeContext ): boolean { const { currentType } = context if (currentType !== TokenTypes.BraceLeft) { return false } peekSpaces(scnr) const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek() const ret = isNumberStart(ch) scnr.resetPeek() return ret } function isLiteralStart(scnr: Scanner, context: TokenizeContext): boolean { const { currentType } = context if (currentType !== TokenTypes.BraceLeft) { return false } peekSpaces(scnr) const ret = scnr.currentPeek() === LITERAL_DELIMITER scnr.resetPeek() return ret } function isLinkedDotStart(scnr: Scanner, context: TokenizeContext): boolean { const { currentType } = context if (currentType !== TokenTypes.LinkedAlias) { return false } peekSpaces(scnr) const ret = scnr.currentPeek() === TokenChars.LinkedDot scnr.resetPeek() return ret } function isLinkedModifierStart( scnr: Scanner, context: TokenizeContext ): boolean { const { currentType } = context if (currentType !== TokenTypes.LinkedDot) { return false } peekSpaces(scnr) const ret = isIdentifierStart(scnr.currentPeek()) scnr.resetPeek() return ret } function isLinkedDelimiterStart( scnr: Scanner, context: TokenizeContext ): boolean { const { currentType } = context if ( !( currentType === TokenTypes.LinkedAlias || currentType === TokenTypes.LinkedModifier ) ) { return false } peekSpaces(scnr) const ret = scnr.currentPeek() === TokenChars.LinkedDelimiter scnr.resetPeek() return ret } function isLinkedReferStart( scnr: Scanner, context: TokenizeContext ): boolean { const { currentType } = context if (currentType !== TokenTypes.LinkedDelimiter) { return false } const fn = (): boolean => { const ch = scnr.currentPeek() if (ch === TokenChars.BraceLeft) { return isIdentifierStart(scnr.peek()) } else if ( ch === TokenChars.LinkedAlias || ch === TokenChars.Modulo || ch === TokenChars.Pipe || ch === TokenChars.LinkedDelimiter || ch === TokenChars.LinkedDot || ch === SPACE || !ch ) { return false } else if (ch === NEW_LINE) { scnr.peek() return fn() } else { // other characters return isIdentifierStart(ch) } } const ret = fn() scnr.resetPeek() return ret } function isPluralStart(scnr: Scanner): boolean { peekSpaces(scnr) const ret = scnr.currentPeek() === TokenChars.Pipe scnr.resetPeek() return ret } function isTextStart(scnr: Scanner, reset = true): boolean { const fn = (hasSpace = false, prev = '', detectModulo = false): boolean => { const ch = scnr.currentPeek() if (ch === TokenChars.BraceLeft) { return prev === TokenChars.Modulo ? false : hasSpace } else if (ch === TokenChars.LinkedAlias || !ch) { return prev === TokenChars.Modulo ? true : hasSpace } else if (ch === TokenChars.Modulo) { scnr.peek() return fn(hasSpace, TokenChars.Modulo, true) } else if (ch === TokenChars.Pipe) { return prev === TokenChars.Modulo || detectModulo ? true : !(prev === SPACE || prev === NEW_LINE) } else if (ch === SPACE) { scnr.peek() return fn(true, SPACE, detectModulo) } else if (ch === NEW_LINE) { scnr.peek() return fn(true, NEW_LINE, detectModulo) } else { return true } } const ret = fn() reset && scnr.resetPeek() return ret } function takeChar( scnr: Scanner, fn: (ch: string) => boolean ): string | undefined | null { const ch = scnr.currentChar() if (ch === EOF) { return EOF } if (fn(ch)) { scnr.next() return ch } return null } function takeIdentifierChar(scnr: Scanner): string | undefined | null { const closure = (ch: string) => { const cc = ch.charCodeAt(0) return ( (cc >= 97 && cc <= 122) || // a-z (cc >= 65 && cc <= 90) || // A-Z (cc >= 48 && cc <= 57) || // 0-9 cc === 95 || // _ cc === 36 // $ ) } return takeChar(scnr, closure) } function takeDigit(scnr: Scanner): string | undefined | null { const closure = (ch: string) => { const cc = ch.charCodeAt(0) return cc >= 48 && cc <= 57 // 0-9 } return takeChar(scnr, closure) } function takeHexDigit(scnr: Scanner): string | undefined | null { const closure = (ch: string) => { const cc = ch.charCodeAt(0) return ( (cc >= 48 && cc <= 57) || // 0-9 (cc >= 65 && cc <= 70) || // A-F (cc >= 97 && cc <= 102) ) // a-f } return takeChar(scnr, closure) } function getDigits(scnr: Scanner): string { let ch: string | undefined | null = '' let num = '' while ((ch = takeDigit(scnr))) { num += ch } return num } function readText(scnr: Scanner): string { let buf = '' while (true) { const ch = scnr.currentChar() if ( ch === TokenChars.BraceLeft || ch === TokenChars.BraceRight || ch === TokenChars.LinkedAlias || ch === TokenChars.Pipe || !ch ) { break } else if (ch === TokenChars.Modulo) { if (isTextStart(scnr)) { buf += ch scnr.next() } else { break } } else if (ch === SPACE || ch === NEW_LINE) { if (isTextStart(scnr)) { buf += ch scnr.next() } else if (isPluralStart(scnr)) { break } else { buf += ch scnr.next() } } else { buf += ch scnr.next() } } return buf } function readNamedIdentifier(scnr: Scanner): string { skipSpaces(scnr) let ch: string | undefined | null = '' let name = '' while ((ch = takeIdentifierChar(scnr))) { name += ch } if (scnr.currentChar() === EOF) { emitError( CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0 ) } return name } function readListIdentifier(scnr: Scanner): string { skipSpaces(scnr) let value = '' if (scnr.currentChar() === '-') { scnr.next() value += `-${getDigits(scnr)}` } else { value += getDigits(scnr) } if (scnr.currentChar() === EOF) { emitError( CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0 ) } return value } function readLiteral(scnr: Scanner): string { skipSpaces(scnr) eat(scnr, `\'`) let ch: string | undefined | null = '' let literal = '' const fn = (x: string) => x !== LITERAL_DELIMITER && x !== NEW_LINE while ((ch = takeChar(scnr, fn))) { if (ch === '\\') { literal += readEscapeSequence(scnr) } else { literal += ch } } const current = scnr.currentChar() if (current === NEW_LINE || current === EOF) { emitError( CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER, currentPosition(), 0 ) // TODO: Is it correct really? if (current === NEW_LINE) { scnr.next() eat(scnr, `\'`) } return literal } eat(scnr, `\'`) return literal } function readEscapeSequence(scnr: Scanner): string { const ch = scnr.currentChar() switch (ch) { case '\\': case `\'`: scnr.next() return `\\${ch}` case 'u': return readUnicodeEscapeSequence(scnr, ch, 4) case 'U': return readUnicodeEscapeSequence(scnr, ch, 6) default: emitError( CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE, currentPosition(), 0, ch ) return '' } } function readUnicodeEscapeSequence( scnr: Scanner, unicode: string, digits: number ): string { eat(scnr, unicode) let sequence = '' for (let i = 0; i < digits; i++) { const ch = takeHexDigit(scnr) if (!ch) { emitError( CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}` ) break } sequence += ch } return `\\${unicode}${sequence}` } function readInvalidIdentifier(scnr: Scanner): string { skipSpaces(scnr) let ch: string | undefined | null = '' let identifiers = '' const closure = (ch: string) => ch !== TokenChars.BraceLeft && ch !== TokenChars.BraceRight && ch !== SPACE && ch !== NEW_LINE while ((ch = takeChar(scnr, closure))) { identifiers += ch } return identifiers } function readLinkedModifier(scnr: Scanner): string { let ch: string | undefined | null = '' let name = '' while ((ch = takeIdentifierChar(scnr))) { name += ch } return name } function readLinkedRefer(scnr: Scanner): string { const fn = (detect = false, buf: string): string => { const ch = scnr.currentChar() if ( ch === TokenChars.BraceLeft || ch === TokenChars.Modulo || ch === TokenChars.LinkedAlias || ch === TokenChars.Pipe || !ch ) { return buf } else if (ch === SPACE) { return buf } else if (ch === NEW_LINE) { buf += ch scnr.next() return fn(detect, buf) } else { buf += ch scnr.next() return fn(true, buf) } } return fn(false, '') } function readPlural(scnr: Scanner): string { skipSpaces(scnr) const plural = eat(scnr, TokenChars.Pipe) skipSpaces(scnr) return plural } // TODO: We need refactoring of token parsing ... function readTokenInPlaceholder( scnr: Scanner, context: TokenizeContext ): Token | null { let token = null const ch = scnr.currentChar() switch (ch) { case TokenChars.BraceLeft: if (context.braceNest >= 1) { emitError( CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER, currentPosition(), 0 ) } scnr.next() token = getToken(context, TokenTypes.BraceLeft, TokenChars.BraceLeft) skipSpaces(scnr) context.braceNest++ return token case TokenChars.BraceRight: if ( context.braceNest > 0 && context.currentType === TokenTypes.BraceLeft ) { emitError(CompileErrorCodes.EMPTY_PLACEHOLDER, currentPosition(), 0) } scnr.next() token = getToken(context, TokenTypes.BraceRight, TokenChars.BraceRight) context.braceNest-- context.braceNest > 0 && skipSpaces(scnr) if (context.inLinked && context.braceNest === 0) { context.inLinked = false } return token case TokenChars.LinkedAlias: if (context.braceNest > 0) { emitError( CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0 ) } token = readTokenInLinked(scnr, context) || getEndToken(context) context.braceNest = 0 return token default: let validNamedIdentifier = true let validListIdentifier = true let validLiteral = true if (isPluralStart(scnr)) { if (context.braceNest > 0) { emitError( CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0 ) } token = getToken(context, TokenTypes.Pipe, readPlural(scnr)) // reset context.braceNest = 0 context.inLinked = false return token } if ( context.braceNest > 0 && (context.currentType === TokenTypes.Named || context.currentType === TokenTypes.List || context.currentType === TokenTypes.Literal) ) { emitError( CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0 ) context.braceNest = 0 return readToken(scnr, context) } if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) { token = getToken(context, TokenTypes.Named, readNamedIdentifier(scnr)) skipSpaces(scnr) return token } if ((validListIdentifier = isListIdentifierStart(scnr, context))) { token = getToken(context, TokenTypes.List, readListIdentifier(scnr)) skipSpaces(scnr) return token } if ((validLiteral = isLiteralStart(scnr, context))) { token = getToken(context, TokenTypes.Literal, readLiteral(scnr)) skipSpaces(scnr) return token } if (!validNamedIdentifier && !validListIdentifier && !validLiteral) { // TODO: we should be re-designed invalid cases, when we will extend message syntax near the future ... token = getToken( context, TokenTypes.InvalidPlace, readInvalidIdentifier(scnr) ) emitError( CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER, currentPosition(), 0, token.value ) skipSpaces(scnr) return token } break } return token } // TODO: We need refactoring of token parsing ... function readTokenInLinked( scnr: Scanner, context: TokenizeContext ): Token | null { const { currentType } = context let token = null const ch = scnr.currentChar() if ( (currentType === TokenTypes.LinkedAlias || currentType === TokenTypes.LinkedDot || currentType === TokenTypes.LinkedModifier || currentType === TokenTypes.LinkedDelimiter) && (ch === NEW_LINE || ch === SPACE) ) { emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0) } switch (ch) { case TokenChars.LinkedAlias: scnr.next() token = getToken( context, TokenTypes.LinkedAlias, TokenChars.LinkedAlias ) context.inLinked = true return token case TokenChars.LinkedDot: skipSpaces(scnr) scnr.next() return getToken(context, TokenTypes.LinkedDot, TokenChars.LinkedDot) case TokenChars.LinkedDelimiter: skipSpaces(scnr) scnr.next() return getToken( context, TokenTypes.LinkedDelimiter, TokenChars.LinkedDelimiter ) default: if (isPluralStart(scnr)) { token = getToken(context, TokenTypes.Pipe, readPlural(scnr)) // reset context.braceNest = 0 context.inLinked = false return token } if ( isLinkedDotStart(scnr, context) || isLinkedDelimiterStart(scnr, context) ) { skipSpaces(scnr) return readTokenInLinked(scnr, context) } if (isLinkedModifierStart(scnr, context)) { skipSpaces(scnr) return getToken( context, TokenTypes.LinkedModifier, readLinkedModifier(scnr) ) } if (isLinkedReferStart(scnr, context)) { skipSpaces(scnr) if (ch === TokenChars.BraceLeft) { // scan the placeholder return readTokenInPlaceholder(scnr, context) || token } else { return getToken( context, TokenTypes.LinkedKey, readLinkedRefer(scnr) ) } } if (currentType === TokenTypes.LinkedAlias) { emitError( CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0 ) } context.braceNest = 0 context.inLinked = false return readToken(scnr, context) } } // TODO: We need refactoring of token parsing ... function readToken(scnr: Scanner, context: TokenizeContext): Token { let token = { type: TokenTypes.EOF } if (context.braceNest > 0) { return readTokenInPlaceholder(scnr, context) || getEndToken(context) } if (context.inLinked) { return readTokenInLinked(scnr, context) || getEndToken(context) } const ch = scnr.currentChar() switch (ch) { case TokenChars.BraceLeft: return readTokenInPlaceholder(scnr, context) || getEndToken(context) case TokenChars.BraceRight: emitError( CompileErrorCodes.UNBALANCED_CLOSING_BRACE, currentPosition(), 0 ) scnr.next() return getToken(context, TokenTypes.BraceRight, TokenChars.BraceRight) case TokenChars.LinkedAlias: return readTokenInLinked(scnr, context) || getEndToken(context) default: if (isPluralStart(scnr)) { token = getToken(context, TokenTypes.Pipe, readPlural(scnr)) // reset context.braceNest = 0 context.inLinked = false return token } if (isTextStart(scnr)) { return getToken(context, TokenTypes.Text, readText(scnr)) } if (ch === TokenChars.Modulo) { scnr.next() return getToken(context, TokenTypes.Modulo, TokenChars.Modulo) } break } return token } function nextToken(): Token { const { currentType, offset, startLoc, endLoc } = _context _context.lastType = currentType _context.lastOffset = offset _context.lastStartLoc = startLoc _context.lastEndLoc = endLoc _context.offset = currentOffset() _context.startLoc = currentPosition() if (_scnr.currentChar() === EOF) { return getToken(_context, TokenTypes.EOF) } return readToken(_scnr, _context) } return { nextToken, currentOffset, currentPosition, context } } export function parse(source: string, options: TokenizeOptions = {}): Token[] { const tokens = [] as Token[] const tokenizer = createTokenizer(source, options) let token: Token | null = null do { token = tokenizer.nextToken() tokens.push(token) } while (token.type !== TokenTypes.EOF) return tokens }
the_stack
import { GraphQLResolveInfo, GraphQLSchema } from 'graphql' import { IResolvers } from 'graphql-tools/dist/Interfaces' import { Options } from 'graphql-binding' import { makePrismaBindingClass, BasePrismaOptions } from 'prisma-binding' export interface Query { grocers: <T = Grocer[]>( args: { where?: GrocerWhereInput orderBy?: GrocerOrderByInput skip?: Int after?: String before?: String first?: Int last?: Int }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> customers: <T = Customer[]>( args: { where?: CustomerWhereInput orderBy?: CustomerOrderByInput skip?: Int after?: String before?: String first?: Int last?: Int }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> basketItems: <T = BasketItem[]>( args: { where?: BasketItemWhereInput orderBy?: BasketItemOrderByInput skip?: Int after?: String before?: String first?: Int last?: Int }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> products: <T = Product[]>( args: { where?: ProductWhereInput orderBy?: ProductOrderByInput skip?: Int after?: String before?: String first?: Int last?: Int }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> grocer: <T = Grocer | null>( args: { where: GrocerWhereUniqueInput }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> customer: <T = Customer | null>( args: { where: CustomerWhereUniqueInput }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> basketItem: <T = BasketItem | null>( args: { where: BasketItemWhereUniqueInput }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> product: <T = Product | null>( args: { where: ProductWhereUniqueInput }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> grocersConnection: <T = GrocerConnection>( args: { where?: GrocerWhereInput orderBy?: GrocerOrderByInput skip?: Int after?: String before?: String first?: Int last?: Int }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> customersConnection: <T = CustomerConnection>( args: { where?: CustomerWhereInput orderBy?: CustomerOrderByInput skip?: Int after?: String before?: String first?: Int last?: Int }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> basketItemsConnection: <T = BasketItemConnection>( args: { where?: BasketItemWhereInput orderBy?: BasketItemOrderByInput skip?: Int after?: String before?: String first?: Int last?: Int }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> productsConnection: <T = ProductConnection>( args: { where?: ProductWhereInput orderBy?: ProductOrderByInput skip?: Int after?: String before?: String first?: Int last?: Int }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> node: <T = Node | null>( args: { id: ID_Output }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> } export interface Mutation { createGrocer: <T = Grocer>( args: { data: GrocerCreateInput }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> createCustomer: <T = Customer>( args: { data: CustomerCreateInput }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> createBasketItem: <T = BasketItem>( args: { data: BasketItemCreateInput }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> createProduct: <T = Product>( args: { data: ProductCreateInput }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> updateGrocer: <T = Grocer | null>( args: { data: GrocerUpdateInput; where: GrocerWhereUniqueInput }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> updateCustomer: <T = Customer | null>( args: { data: CustomerUpdateInput; where: CustomerWhereUniqueInput }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> updateBasketItem: <T = BasketItem | null>( args: { data: BasketItemUpdateInput; where: BasketItemWhereUniqueInput }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> updateProduct: <T = Product | null>( args: { data: ProductUpdateInput; where: ProductWhereUniqueInput }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> deleteGrocer: <T = Grocer | null>( args: { where: GrocerWhereUniqueInput }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> deleteCustomer: <T = Customer | null>( args: { where: CustomerWhereUniqueInput }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> deleteBasketItem: <T = BasketItem | null>( args: { where: BasketItemWhereUniqueInput }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> deleteProduct: <T = Product | null>( args: { where: ProductWhereUniqueInput }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> upsertGrocer: <T = Grocer>( args: { where: GrocerWhereUniqueInput create: GrocerCreateInput update: GrocerUpdateInput }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> upsertCustomer: <T = Customer>( args: { where: CustomerWhereUniqueInput create: CustomerCreateInput update: CustomerUpdateInput }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> upsertBasketItem: <T = BasketItem>( args: { where: BasketItemWhereUniqueInput create: BasketItemCreateInput update: BasketItemUpdateInput }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> upsertProduct: <T = Product>( args: { where: ProductWhereUniqueInput create: ProductCreateInput update: ProductUpdateInput }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> updateManyGrocers: <T = BatchPayload>( args: { data: GrocerUpdateInput; where?: GrocerWhereInput }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> updateManyCustomers: <T = BatchPayload>( args: { data: CustomerUpdateInput; where?: CustomerWhereInput }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> updateManyBasketItems: <T = BatchPayload>( args: { data: BasketItemUpdateInput; where?: BasketItemWhereInput }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> updateManyProducts: <T = BatchPayload>( args: { data: ProductUpdateInput; where?: ProductWhereInput }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> deleteManyGrocers: <T = BatchPayload>( args: { where?: GrocerWhereInput }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> deleteManyCustomers: <T = BatchPayload>( args: { where?: CustomerWhereInput }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> deleteManyBasketItems: <T = BatchPayload>( args: { where?: BasketItemWhereInput }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> deleteManyProducts: <T = BatchPayload>( args: { where?: ProductWhereInput }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<T> } export interface Subscription { grocer: <T = GrocerSubscriptionPayload | null>( args: { where?: GrocerSubscriptionWhereInput }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<AsyncIterator<T>> customer: <T = CustomerSubscriptionPayload | null>( args: { where?: CustomerSubscriptionWhereInput }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<AsyncIterator<T>> basketItem: <T = BasketItemSubscriptionPayload | null>( args: { where?: BasketItemSubscriptionWhereInput }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<AsyncIterator<T>> product: <T = ProductSubscriptionPayload | null>( args: { where?: ProductSubscriptionWhereInput }, info?: GraphQLResolveInfo | string, options?: Options, ) => Promise<AsyncIterator<T>> } export interface Exists { Grocer: (where?: GrocerWhereInput) => Promise<boolean> Customer: (where?: CustomerWhereInput) => Promise<boolean> BasketItem: (where?: BasketItemWhereInput) => Promise<boolean> Product: (where?: ProductWhereInput) => Promise<boolean> } export interface Prisma { query: Query mutation: Mutation subscription: Subscription exists: Exists request: <T = any>( query: string, variables?: { [key: string]: any }, ) => Promise<T> delegate( operation: 'query' | 'mutation', fieldName: string, args: { [key: string]: any }, infoOrQuery?: GraphQLResolveInfo | string, options?: Options, ): Promise<any> delegateSubscription( fieldName: string, args?: { [key: string]: any }, infoOrQuery?: GraphQLResolveInfo | string, options?: Options, ): Promise<AsyncIterator<any>> getAbstractResolvers(filterSchema?: GraphQLSchema | string): IResolvers } export interface BindingConstructor<T> { new (options: BasePrismaOptions): T } /** * Type Defs */ const typeDefs = `type AggregateBasketItem { count: Int! } type AggregateCustomer { count: Int! } type AggregateGrocer { count: Int! } type AggregateProduct { count: Int! } type BasketItem implements Node { id: ID! customer(where: CustomerWhereInput): Customer! product(where: ProductWhereInput): Product! quantity: Int! } """A connection to a list of items.""" type BasketItemConnection { """Information to aid in pagination.""" pageInfo: PageInfo! """A list of edges.""" edges: [BasketItemEdge]! aggregate: AggregateBasketItem! } input BasketItemCreateInput { quantity: Int! customer: CustomerCreateOneWithoutBasketInput! product: ProductCreateOneInput! } input BasketItemCreateManyWithoutCustomerInput { create: [BasketItemCreateWithoutCustomerInput!] connect: [BasketItemWhereUniqueInput!] } input BasketItemCreateWithoutCustomerInput { quantity: Int! product: ProductCreateOneInput! } """An edge in a connection.""" type BasketItemEdge { """The item at the end of the edge.""" node: BasketItem! """A cursor for use in pagination.""" cursor: String! } enum BasketItemOrderByInput { id_ASC id_DESC quantity_ASC quantity_DESC updatedAt_ASC updatedAt_DESC createdAt_ASC createdAt_DESC } type BasketItemPreviousValues { id: ID! quantity: Int! } type BasketItemSubscriptionPayload { mutation: MutationType! node: BasketItem updatedFields: [String!] previousValues: BasketItemPreviousValues } input BasketItemSubscriptionWhereInput { """Logical AND on all given filters.""" AND: [BasketItemSubscriptionWhereInput!] """Logical OR on all given filters.""" OR: [BasketItemSubscriptionWhereInput!] """Logical NOT on all given filters combined by AND.""" NOT: [BasketItemSubscriptionWhereInput!] """ The subscription event gets dispatched when it's listed in mutation_in """ mutation_in: [MutationType!] """ The subscription event gets only dispatched when one of the updated fields names is included in this list """ updatedFields_contains: String """ The subscription event gets only dispatched when all of the field names included in this list have been updated """ updatedFields_contains_every: [String!] """ The subscription event gets only dispatched when some of the field names included in this list have been updated """ updatedFields_contains_some: [String!] node: BasketItemWhereInput } input BasketItemUpdateInput { quantity: Int customer: CustomerUpdateOneWithoutBasketInput product: ProductUpdateOneInput } input BasketItemUpdateManyWithoutCustomerInput { create: [BasketItemCreateWithoutCustomerInput!] connect: [BasketItemWhereUniqueInput!] disconnect: [BasketItemWhereUniqueInput!] delete: [BasketItemWhereUniqueInput!] update: [BasketItemUpdateWithWhereUniqueWithoutCustomerInput!] upsert: [BasketItemUpsertWithWhereUniqueWithoutCustomerInput!] } input BasketItemUpdateWithoutCustomerDataInput { quantity: Int product: ProductUpdateOneInput } input BasketItemUpdateWithWhereUniqueWithoutCustomerInput { where: BasketItemWhereUniqueInput! data: BasketItemUpdateWithoutCustomerDataInput! } input BasketItemUpsertWithWhereUniqueWithoutCustomerInput { where: BasketItemWhereUniqueInput! update: BasketItemUpdateWithoutCustomerDataInput! create: BasketItemCreateWithoutCustomerInput! } input BasketItemWhereInput { """Logical AND on all given filters.""" AND: [BasketItemWhereInput!] """Logical OR on all given filters.""" OR: [BasketItemWhereInput!] """Logical NOT on all given filters combined by AND.""" NOT: [BasketItemWhereInput!] id: ID """All values that are not equal to given value.""" id_not: ID """All values that are contained in given list.""" id_in: [ID!] """All values that are not contained in given list.""" id_not_in: [ID!] """All values less than the given value.""" id_lt: ID """All values less than or equal the given value.""" id_lte: ID """All values greater than the given value.""" id_gt: ID """All values greater than or equal the given value.""" id_gte: ID """All values containing the given string.""" id_contains: ID """All values not containing the given string.""" id_not_contains: ID """All values starting with the given string.""" id_starts_with: ID """All values not starting with the given string.""" id_not_starts_with: ID """All values ending with the given string.""" id_ends_with: ID """All values not ending with the given string.""" id_not_ends_with: ID quantity: Int """All values that are not equal to given value.""" quantity_not: Int """All values that are contained in given list.""" quantity_in: [Int!] """All values that are not contained in given list.""" quantity_not_in: [Int!] """All values less than the given value.""" quantity_lt: Int """All values less than or equal the given value.""" quantity_lte: Int """All values greater than the given value.""" quantity_gt: Int """All values greater than or equal the given value.""" quantity_gte: Int customer: CustomerWhereInput product: ProductWhereInput } input BasketItemWhereUniqueInput { id: ID } type BatchPayload { """The number of nodes that have been affected by the Batch operation.""" count: Long! } type Customer implements Node { id: ID! createdAt: DateTime! updatedAt: DateTime! email: String! basket(where: BasketItemWhereInput, orderBy: BasketItemOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): [BasketItem!] } """A connection to a list of items.""" type CustomerConnection { """Information to aid in pagination.""" pageInfo: PageInfo! """A list of edges.""" edges: [CustomerEdge]! aggregate: AggregateCustomer! } input CustomerCreateInput { email: String! basket: BasketItemCreateManyWithoutCustomerInput } input CustomerCreateOneWithoutBasketInput { create: CustomerCreateWithoutBasketInput connect: CustomerWhereUniqueInput } input CustomerCreateWithoutBasketInput { email: String! } """An edge in a connection.""" type CustomerEdge { """The item at the end of the edge.""" node: Customer! """A cursor for use in pagination.""" cursor: String! } enum CustomerOrderByInput { id_ASC id_DESC createdAt_ASC createdAt_DESC updatedAt_ASC updatedAt_DESC email_ASC email_DESC } type CustomerPreviousValues { id: ID! createdAt: DateTime! updatedAt: DateTime! email: String! } type CustomerSubscriptionPayload { mutation: MutationType! node: Customer updatedFields: [String!] previousValues: CustomerPreviousValues } input CustomerSubscriptionWhereInput { """Logical AND on all given filters.""" AND: [CustomerSubscriptionWhereInput!] """Logical OR on all given filters.""" OR: [CustomerSubscriptionWhereInput!] """Logical NOT on all given filters combined by AND.""" NOT: [CustomerSubscriptionWhereInput!] """ The subscription event gets dispatched when it's listed in mutation_in """ mutation_in: [MutationType!] """ The subscription event gets only dispatched when one of the updated fields names is included in this list """ updatedFields_contains: String """ The subscription event gets only dispatched when all of the field names included in this list have been updated """ updatedFields_contains_every: [String!] """ The subscription event gets only dispatched when some of the field names included in this list have been updated """ updatedFields_contains_some: [String!] node: CustomerWhereInput } input CustomerUpdateInput { email: String basket: BasketItemUpdateManyWithoutCustomerInput } input CustomerUpdateOneWithoutBasketInput { create: CustomerCreateWithoutBasketInput connect: CustomerWhereUniqueInput delete: Boolean update: CustomerUpdateWithoutBasketDataInput upsert: CustomerUpsertWithoutBasketInput } input CustomerUpdateWithoutBasketDataInput { email: String } input CustomerUpsertWithoutBasketInput { update: CustomerUpdateWithoutBasketDataInput! create: CustomerCreateWithoutBasketInput! } input CustomerWhereInput { """Logical AND on all given filters.""" AND: [CustomerWhereInput!] """Logical OR on all given filters.""" OR: [CustomerWhereInput!] """Logical NOT on all given filters combined by AND.""" NOT: [CustomerWhereInput!] id: ID """All values that are not equal to given value.""" id_not: ID """All values that are contained in given list.""" id_in: [ID!] """All values that are not contained in given list.""" id_not_in: [ID!] """All values less than the given value.""" id_lt: ID """All values less than or equal the given value.""" id_lte: ID """All values greater than the given value.""" id_gt: ID """All values greater than or equal the given value.""" id_gte: ID """All values containing the given string.""" id_contains: ID """All values not containing the given string.""" id_not_contains: ID """All values starting with the given string.""" id_starts_with: ID """All values not starting with the given string.""" id_not_starts_with: ID """All values ending with the given string.""" id_ends_with: ID """All values not ending with the given string.""" id_not_ends_with: ID createdAt: DateTime """All values that are not equal to given value.""" createdAt_not: DateTime """All values that are contained in given list.""" createdAt_in: [DateTime!] """All values that are not contained in given list.""" createdAt_not_in: [DateTime!] """All values less than the given value.""" createdAt_lt: DateTime """All values less than or equal the given value.""" createdAt_lte: DateTime """All values greater than the given value.""" createdAt_gt: DateTime """All values greater than or equal the given value.""" createdAt_gte: DateTime updatedAt: DateTime """All values that are not equal to given value.""" updatedAt_not: DateTime """All values that are contained in given list.""" updatedAt_in: [DateTime!] """All values that are not contained in given list.""" updatedAt_not_in: [DateTime!] """All values less than the given value.""" updatedAt_lt: DateTime """All values less than or equal the given value.""" updatedAt_lte: DateTime """All values greater than the given value.""" updatedAt_gt: DateTime """All values greater than or equal the given value.""" updatedAt_gte: DateTime email: String """All values that are not equal to given value.""" email_not: String """All values that are contained in given list.""" email_in: [String!] """All values that are not contained in given list.""" email_not_in: [String!] """All values less than the given value.""" email_lt: String """All values less than or equal the given value.""" email_lte: String """All values greater than the given value.""" email_gt: String """All values greater than or equal the given value.""" email_gte: String """All values containing the given string.""" email_contains: String """All values not containing the given string.""" email_not_contains: String """All values starting with the given string.""" email_starts_with: String """All values not starting with the given string.""" email_not_starts_with: String """All values ending with the given string.""" email_ends_with: String """All values not ending with the given string.""" email_not_ends_with: String basket_every: BasketItemWhereInput basket_some: BasketItemWhereInput basket_none: BasketItemWhereInput } input CustomerWhereUniqueInput { id: ID email: String } scalar DateTime type Grocer implements Node { id: ID! createdAt: DateTime! updatedAt: DateTime! email: String! } """A connection to a list of items.""" type GrocerConnection { """Information to aid in pagination.""" pageInfo: PageInfo! """A list of edges.""" edges: [GrocerEdge]! aggregate: AggregateGrocer! } input GrocerCreateInput { email: String! } """An edge in a connection.""" type GrocerEdge { """The item at the end of the edge.""" node: Grocer! """A cursor for use in pagination.""" cursor: String! } enum GrocerOrderByInput { id_ASC id_DESC createdAt_ASC createdAt_DESC updatedAt_ASC updatedAt_DESC email_ASC email_DESC } type GrocerPreviousValues { id: ID! createdAt: DateTime! updatedAt: DateTime! email: String! } type GrocerSubscriptionPayload { mutation: MutationType! node: Grocer updatedFields: [String!] previousValues: GrocerPreviousValues } input GrocerSubscriptionWhereInput { """Logical AND on all given filters.""" AND: [GrocerSubscriptionWhereInput!] """Logical OR on all given filters.""" OR: [GrocerSubscriptionWhereInput!] """Logical NOT on all given filters combined by AND.""" NOT: [GrocerSubscriptionWhereInput!] """ The subscription event gets dispatched when it's listed in mutation_in """ mutation_in: [MutationType!] """ The subscription event gets only dispatched when one of the updated fields names is included in this list """ updatedFields_contains: String """ The subscription event gets only dispatched when all of the field names included in this list have been updated """ updatedFields_contains_every: [String!] """ The subscription event gets only dispatched when some of the field names included in this list have been updated """ updatedFields_contains_some: [String!] node: GrocerWhereInput } input GrocerUpdateInput { email: String } input GrocerWhereInput { """Logical AND on all given filters.""" AND: [GrocerWhereInput!] """Logical OR on all given filters.""" OR: [GrocerWhereInput!] """Logical NOT on all given filters combined by AND.""" NOT: [GrocerWhereInput!] id: ID """All values that are not equal to given value.""" id_not: ID """All values that are contained in given list.""" id_in: [ID!] """All values that are not contained in given list.""" id_not_in: [ID!] """All values less than the given value.""" id_lt: ID """All values less than or equal the given value.""" id_lte: ID """All values greater than the given value.""" id_gt: ID """All values greater than or equal the given value.""" id_gte: ID """All values containing the given string.""" id_contains: ID """All values not containing the given string.""" id_not_contains: ID """All values starting with the given string.""" id_starts_with: ID """All values not starting with the given string.""" id_not_starts_with: ID """All values ending with the given string.""" id_ends_with: ID """All values not ending with the given string.""" id_not_ends_with: ID createdAt: DateTime """All values that are not equal to given value.""" createdAt_not: DateTime """All values that are contained in given list.""" createdAt_in: [DateTime!] """All values that are not contained in given list.""" createdAt_not_in: [DateTime!] """All values less than the given value.""" createdAt_lt: DateTime """All values less than or equal the given value.""" createdAt_lte: DateTime """All values greater than the given value.""" createdAt_gt: DateTime """All values greater than or equal the given value.""" createdAt_gte: DateTime updatedAt: DateTime """All values that are not equal to given value.""" updatedAt_not: DateTime """All values that are contained in given list.""" updatedAt_in: [DateTime!] """All values that are not contained in given list.""" updatedAt_not_in: [DateTime!] """All values less than the given value.""" updatedAt_lt: DateTime """All values less than or equal the given value.""" updatedAt_lte: DateTime """All values greater than the given value.""" updatedAt_gt: DateTime """All values greater than or equal the given value.""" updatedAt_gte: DateTime email: String """All values that are not equal to given value.""" email_not: String """All values that are contained in given list.""" email_in: [String!] """All values that are not contained in given list.""" email_not_in: [String!] """All values less than the given value.""" email_lt: String """All values less than or equal the given value.""" email_lte: String """All values greater than the given value.""" email_gt: String """All values greater than or equal the given value.""" email_gte: String """All values containing the given string.""" email_contains: String """All values not containing the given string.""" email_not_contains: String """All values starting with the given string.""" email_starts_with: String """All values not starting with the given string.""" email_not_starts_with: String """All values ending with the given string.""" email_ends_with: String """All values not ending with the given string.""" email_not_ends_with: String } input GrocerWhereUniqueInput { id: ID email: String } """ The \`Long\` scalar type represents non-fractional signed whole numeric values. Long can represent values between -(2^63) and 2^63 - 1. """ scalar Long type Mutation { createGrocer(data: GrocerCreateInput!): Grocer! createCustomer(data: CustomerCreateInput!): Customer! createBasketItem(data: BasketItemCreateInput!): BasketItem! createProduct(data: ProductCreateInput!): Product! updateGrocer(data: GrocerUpdateInput!, where: GrocerWhereUniqueInput!): Grocer updateCustomer(data: CustomerUpdateInput!, where: CustomerWhereUniqueInput!): Customer updateBasketItem(data: BasketItemUpdateInput!, where: BasketItemWhereUniqueInput!): BasketItem updateProduct(data: ProductUpdateInput!, where: ProductWhereUniqueInput!): Product deleteGrocer(where: GrocerWhereUniqueInput!): Grocer deleteCustomer(where: CustomerWhereUniqueInput!): Customer deleteBasketItem(where: BasketItemWhereUniqueInput!): BasketItem deleteProduct(where: ProductWhereUniqueInput!): Product upsertGrocer(where: GrocerWhereUniqueInput!, create: GrocerCreateInput!, update: GrocerUpdateInput!): Grocer! upsertCustomer(where: CustomerWhereUniqueInput!, create: CustomerCreateInput!, update: CustomerUpdateInput!): Customer! upsertBasketItem(where: BasketItemWhereUniqueInput!, create: BasketItemCreateInput!, update: BasketItemUpdateInput!): BasketItem! upsertProduct(where: ProductWhereUniqueInput!, create: ProductCreateInput!, update: ProductUpdateInput!): Product! updateManyGrocers(data: GrocerUpdateInput!, where: GrocerWhereInput): BatchPayload! updateManyCustomers(data: CustomerUpdateInput!, where: CustomerWhereInput): BatchPayload! updateManyBasketItems(data: BasketItemUpdateInput!, where: BasketItemWhereInput): BatchPayload! updateManyProducts(data: ProductUpdateInput!, where: ProductWhereInput): BatchPayload! deleteManyGrocers(where: GrocerWhereInput): BatchPayload! deleteManyCustomers(where: CustomerWhereInput): BatchPayload! deleteManyBasketItems(where: BasketItemWhereInput): BatchPayload! deleteManyProducts(where: ProductWhereInput): BatchPayload! } enum MutationType { CREATED UPDATED DELETED } """An object with an ID""" interface Node { """The id of the object.""" id: ID! } """Information about pagination in a connection.""" type PageInfo { """When paginating forwards, are there more items?""" hasNextPage: Boolean! """When paginating backwards, are there more items?""" hasPreviousPage: Boolean! """When paginating backwards, the cursor to continue.""" startCursor: String """When paginating forwards, the cursor to continue.""" endCursor: String } type Product implements Node { id: ID! createdAt: DateTime! updatedAt: DateTime! name: String! description: String! price: Int! } """A connection to a list of items.""" type ProductConnection { """Information to aid in pagination.""" pageInfo: PageInfo! """A list of edges.""" edges: [ProductEdge]! aggregate: AggregateProduct! } input ProductCreateInput { name: String! description: String! price: Int! } input ProductCreateOneInput { create: ProductCreateInput connect: ProductWhereUniqueInput } """An edge in a connection.""" type ProductEdge { """The item at the end of the edge.""" node: Product! """A cursor for use in pagination.""" cursor: String! } enum ProductOrderByInput { id_ASC id_DESC createdAt_ASC createdAt_DESC updatedAt_ASC updatedAt_DESC name_ASC name_DESC description_ASC description_DESC price_ASC price_DESC } type ProductPreviousValues { id: ID! createdAt: DateTime! updatedAt: DateTime! name: String! description: String! price: Int! } type ProductSubscriptionPayload { mutation: MutationType! node: Product updatedFields: [String!] previousValues: ProductPreviousValues } input ProductSubscriptionWhereInput { """Logical AND on all given filters.""" AND: [ProductSubscriptionWhereInput!] """Logical OR on all given filters.""" OR: [ProductSubscriptionWhereInput!] """Logical NOT on all given filters combined by AND.""" NOT: [ProductSubscriptionWhereInput!] """ The subscription event gets dispatched when it's listed in mutation_in """ mutation_in: [MutationType!] """ The subscription event gets only dispatched when one of the updated fields names is included in this list """ updatedFields_contains: String """ The subscription event gets only dispatched when all of the field names included in this list have been updated """ updatedFields_contains_every: [String!] """ The subscription event gets only dispatched when some of the field names included in this list have been updated """ updatedFields_contains_some: [String!] node: ProductWhereInput } input ProductUpdateDataInput { name: String description: String price: Int } input ProductUpdateInput { name: String description: String price: Int } input ProductUpdateOneInput { create: ProductCreateInput connect: ProductWhereUniqueInput delete: Boolean update: ProductUpdateDataInput upsert: ProductUpsertNestedInput } input ProductUpsertNestedInput { update: ProductUpdateDataInput! create: ProductCreateInput! } input ProductWhereInput { """Logical AND on all given filters.""" AND: [ProductWhereInput!] """Logical OR on all given filters.""" OR: [ProductWhereInput!] """Logical NOT on all given filters combined by AND.""" NOT: [ProductWhereInput!] id: ID """All values that are not equal to given value.""" id_not: ID """All values that are contained in given list.""" id_in: [ID!] """All values that are not contained in given list.""" id_not_in: [ID!] """All values less than the given value.""" id_lt: ID """All values less than or equal the given value.""" id_lte: ID """All values greater than the given value.""" id_gt: ID """All values greater than or equal the given value.""" id_gte: ID """All values containing the given string.""" id_contains: ID """All values not containing the given string.""" id_not_contains: ID """All values starting with the given string.""" id_starts_with: ID """All values not starting with the given string.""" id_not_starts_with: ID """All values ending with the given string.""" id_ends_with: ID """All values not ending with the given string.""" id_not_ends_with: ID createdAt: DateTime """All values that are not equal to given value.""" createdAt_not: DateTime """All values that are contained in given list.""" createdAt_in: [DateTime!] """All values that are not contained in given list.""" createdAt_not_in: [DateTime!] """All values less than the given value.""" createdAt_lt: DateTime """All values less than or equal the given value.""" createdAt_lte: DateTime """All values greater than the given value.""" createdAt_gt: DateTime """All values greater than or equal the given value.""" createdAt_gte: DateTime updatedAt: DateTime """All values that are not equal to given value.""" updatedAt_not: DateTime """All values that are contained in given list.""" updatedAt_in: [DateTime!] """All values that are not contained in given list.""" updatedAt_not_in: [DateTime!] """All values less than the given value.""" updatedAt_lt: DateTime """All values less than or equal the given value.""" updatedAt_lte: DateTime """All values greater than the given value.""" updatedAt_gt: DateTime """All values greater than or equal the given value.""" updatedAt_gte: DateTime name: String """All values that are not equal to given value.""" name_not: String """All values that are contained in given list.""" name_in: [String!] """All values that are not contained in given list.""" name_not_in: [String!] """All values less than the given value.""" name_lt: String """All values less than or equal the given value.""" name_lte: String """All values greater than the given value.""" name_gt: String """All values greater than or equal the given value.""" name_gte: String """All values containing the given string.""" name_contains: String """All values not containing the given string.""" name_not_contains: String """All values starting with the given string.""" name_starts_with: String """All values not starting with the given string.""" name_not_starts_with: String """All values ending with the given string.""" name_ends_with: String """All values not ending with the given string.""" name_not_ends_with: String description: String """All values that are not equal to given value.""" description_not: String """All values that are contained in given list.""" description_in: [String!] """All values that are not contained in given list.""" description_not_in: [String!] """All values less than the given value.""" description_lt: String """All values less than or equal the given value.""" description_lte: String """All values greater than the given value.""" description_gt: String """All values greater than or equal the given value.""" description_gte: String """All values containing the given string.""" description_contains: String """All values not containing the given string.""" description_not_contains: String """All values starting with the given string.""" description_starts_with: String """All values not starting with the given string.""" description_not_starts_with: String """All values ending with the given string.""" description_ends_with: String """All values not ending with the given string.""" description_not_ends_with: String price: Int """All values that are not equal to given value.""" price_not: Int """All values that are contained in given list.""" price_in: [Int!] """All values that are not contained in given list.""" price_not_in: [Int!] """All values less than the given value.""" price_lt: Int """All values less than or equal the given value.""" price_lte: Int """All values greater than the given value.""" price_gt: Int """All values greater than or equal the given value.""" price_gte: Int } input ProductWhereUniqueInput { id: ID } type Query { grocers(where: GrocerWhereInput, orderBy: GrocerOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): [Grocer]! customers(where: CustomerWhereInput, orderBy: CustomerOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): [Customer]! basketItems(where: BasketItemWhereInput, orderBy: BasketItemOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): [BasketItem]! products(where: ProductWhereInput, orderBy: ProductOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): [Product]! grocer(where: GrocerWhereUniqueInput!): Grocer customer(where: CustomerWhereUniqueInput!): Customer basketItem(where: BasketItemWhereUniqueInput!): BasketItem product(where: ProductWhereUniqueInput!): Product grocersConnection(where: GrocerWhereInput, orderBy: GrocerOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): GrocerConnection! customersConnection(where: CustomerWhereInput, orderBy: CustomerOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): CustomerConnection! basketItemsConnection(where: BasketItemWhereInput, orderBy: BasketItemOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): BasketItemConnection! productsConnection(where: ProductWhereInput, orderBy: ProductOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): ProductConnection! """Fetches an object given its ID""" node( """The ID of an object""" id: ID! ): Node } type Subscription { grocer(where: GrocerSubscriptionWhereInput): GrocerSubscriptionPayload customer(where: CustomerSubscriptionWhereInput): CustomerSubscriptionPayload basketItem(where: BasketItemSubscriptionWhereInput): BasketItemSubscriptionPayload product(where: ProductSubscriptionWhereInput): ProductSubscriptionPayload } ` export const Prisma = makePrismaBindingClass<BindingConstructor<Prisma>>({ typeDefs, }) /** * Types */ export type CustomerOrderByInput = | 'id_ASC' | 'id_DESC' | 'createdAt_ASC' | 'createdAt_DESC' | 'updatedAt_ASC' | 'updatedAt_DESC' | 'email_ASC' | 'email_DESC' export type BasketItemOrderByInput = | 'id_ASC' | 'id_DESC' | 'quantity_ASC' | 'quantity_DESC' | 'updatedAt_ASC' | 'updatedAt_DESC' | 'createdAt_ASC' | 'createdAt_DESC' export type GrocerOrderByInput = | 'id_ASC' | 'id_DESC' | 'createdAt_ASC' | 'createdAt_DESC' | 'updatedAt_ASC' | 'updatedAt_DESC' | 'email_ASC' | 'email_DESC' export type ProductOrderByInput = | 'id_ASC' | 'id_DESC' | 'createdAt_ASC' | 'createdAt_DESC' | 'updatedAt_ASC' | 'updatedAt_DESC' | 'name_ASC' | 'name_DESC' | 'description_ASC' | 'description_DESC' | 'price_ASC' | 'price_DESC' export type MutationType = 'CREATED' | 'UPDATED' | 'DELETED' export interface CustomerCreateInput { email: String basket?: BasketItemCreateManyWithoutCustomerInput } export interface GrocerWhereInput { AND?: GrocerWhereInput[] | GrocerWhereInput OR?: GrocerWhereInput[] | GrocerWhereInput NOT?: GrocerWhereInput[] | GrocerWhereInput id?: ID_Input id_not?: ID_Input id_in?: ID_Input[] | ID_Input id_not_in?: ID_Input[] | ID_Input id_lt?: ID_Input id_lte?: ID_Input id_gt?: ID_Input id_gte?: ID_Input id_contains?: ID_Input id_not_contains?: ID_Input id_starts_with?: ID_Input id_not_starts_with?: ID_Input id_ends_with?: ID_Input id_not_ends_with?: ID_Input createdAt?: DateTime createdAt_not?: DateTime createdAt_in?: DateTime[] | DateTime createdAt_not_in?: DateTime[] | DateTime createdAt_lt?: DateTime createdAt_lte?: DateTime createdAt_gt?: DateTime createdAt_gte?: DateTime updatedAt?: DateTime updatedAt_not?: DateTime updatedAt_in?: DateTime[] | DateTime updatedAt_not_in?: DateTime[] | DateTime updatedAt_lt?: DateTime updatedAt_lte?: DateTime updatedAt_gt?: DateTime updatedAt_gte?: DateTime email?: String email_not?: String email_in?: String[] | String email_not_in?: String[] | String email_lt?: String email_lte?: String email_gt?: String email_gte?: String email_contains?: String email_not_contains?: String email_starts_with?: String email_not_starts_with?: String email_ends_with?: String email_not_ends_with?: String } export interface BasketItemUpsertWithWhereUniqueWithoutCustomerInput { where: BasketItemWhereUniqueInput update: BasketItemUpdateWithoutCustomerDataInput create: BasketItemCreateWithoutCustomerInput } export interface CustomerWhereInput { AND?: CustomerWhereInput[] | CustomerWhereInput OR?: CustomerWhereInput[] | CustomerWhereInput NOT?: CustomerWhereInput[] | CustomerWhereInput id?: ID_Input id_not?: ID_Input id_in?: ID_Input[] | ID_Input id_not_in?: ID_Input[] | ID_Input id_lt?: ID_Input id_lte?: ID_Input id_gt?: ID_Input id_gte?: ID_Input id_contains?: ID_Input id_not_contains?: ID_Input id_starts_with?: ID_Input id_not_starts_with?: ID_Input id_ends_with?: ID_Input id_not_ends_with?: ID_Input createdAt?: DateTime createdAt_not?: DateTime createdAt_in?: DateTime[] | DateTime createdAt_not_in?: DateTime[] | DateTime createdAt_lt?: DateTime createdAt_lte?: DateTime createdAt_gt?: DateTime createdAt_gte?: DateTime updatedAt?: DateTime updatedAt_not?: DateTime updatedAt_in?: DateTime[] | DateTime updatedAt_not_in?: DateTime[] | DateTime updatedAt_lt?: DateTime updatedAt_lte?: DateTime updatedAt_gt?: DateTime updatedAt_gte?: DateTime email?: String email_not?: String email_in?: String[] | String email_not_in?: String[] | String email_lt?: String email_lte?: String email_gt?: String email_gte?: String email_contains?: String email_not_contains?: String email_starts_with?: String email_not_starts_with?: String email_ends_with?: String email_not_ends_with?: String basket_every?: BasketItemWhereInput basket_some?: BasketItemWhereInput basket_none?: BasketItemWhereInput } export interface ProductUpsertNestedInput { update: ProductUpdateDataInput create: ProductCreateInput } export interface ProductCreateInput { name: String description: String price: Int } export interface ProductUpdateDataInput { name?: String description?: String price?: Int } export interface ProductWhereInput { AND?: ProductWhereInput[] | ProductWhereInput OR?: ProductWhereInput[] | ProductWhereInput NOT?: ProductWhereInput[] | ProductWhereInput id?: ID_Input id_not?: ID_Input id_in?: ID_Input[] | ID_Input id_not_in?: ID_Input[] | ID_Input id_lt?: ID_Input id_lte?: ID_Input id_gt?: ID_Input id_gte?: ID_Input id_contains?: ID_Input id_not_contains?: ID_Input id_starts_with?: ID_Input id_not_starts_with?: ID_Input id_ends_with?: ID_Input id_not_ends_with?: ID_Input createdAt?: DateTime createdAt_not?: DateTime createdAt_in?: DateTime[] | DateTime createdAt_not_in?: DateTime[] | DateTime createdAt_lt?: DateTime createdAt_lte?: DateTime createdAt_gt?: DateTime createdAt_gte?: DateTime updatedAt?: DateTime updatedAt_not?: DateTime updatedAt_in?: DateTime[] | DateTime updatedAt_not_in?: DateTime[] | DateTime updatedAt_lt?: DateTime updatedAt_lte?: DateTime updatedAt_gt?: DateTime updatedAt_gte?: DateTime name?: String name_not?: String name_in?: String[] | String name_not_in?: String[] | String name_lt?: String name_lte?: String name_gt?: String name_gte?: String name_contains?: String name_not_contains?: String name_starts_with?: String name_not_starts_with?: String name_ends_with?: String name_not_ends_with?: String description?: String description_not?: String description_in?: String[] | String description_not_in?: String[] | String description_lt?: String description_lte?: String description_gt?: String description_gte?: String description_contains?: String description_not_contains?: String description_starts_with?: String description_not_starts_with?: String description_ends_with?: String description_not_ends_with?: String price?: Int price_not?: Int price_in?: Int[] | Int price_not_in?: Int[] | Int price_lt?: Int price_lte?: Int price_gt?: Int price_gte?: Int } export interface ProductUpdateOneInput { create?: ProductCreateInput connect?: ProductWhereUniqueInput delete?: Boolean update?: ProductUpdateDataInput upsert?: ProductUpsertNestedInput } export interface BasketItemSubscriptionWhereInput { AND?: BasketItemSubscriptionWhereInput[] | BasketItemSubscriptionWhereInput OR?: BasketItemSubscriptionWhereInput[] | BasketItemSubscriptionWhereInput NOT?: BasketItemSubscriptionWhereInput[] | BasketItemSubscriptionWhereInput mutation_in?: MutationType[] | MutationType updatedFields_contains?: String updatedFields_contains_every?: String[] | String updatedFields_contains_some?: String[] | String node?: BasketItemWhereInput } export interface BasketItemUpdateWithoutCustomerDataInput { quantity?: Int product?: ProductUpdateOneInput } export interface GrocerSubscriptionWhereInput { AND?: GrocerSubscriptionWhereInput[] | GrocerSubscriptionWhereInput OR?: GrocerSubscriptionWhereInput[] | GrocerSubscriptionWhereInput NOT?: GrocerSubscriptionWhereInput[] | GrocerSubscriptionWhereInput mutation_in?: MutationType[] | MutationType updatedFields_contains?: String updatedFields_contains_every?: String[] | String updatedFields_contains_some?: String[] | String node?: GrocerWhereInput } export interface BasketItemUpdateWithWhereUniqueWithoutCustomerInput { where: BasketItemWhereUniqueInput data: BasketItemUpdateWithoutCustomerDataInput } export interface CustomerUpsertWithoutBasketInput { update: CustomerUpdateWithoutBasketDataInput create: CustomerCreateWithoutBasketInput } export interface BasketItemUpdateManyWithoutCustomerInput { create?: | BasketItemCreateWithoutCustomerInput[] | BasketItemCreateWithoutCustomerInput connect?: BasketItemWhereUniqueInput[] | BasketItemWhereUniqueInput disconnect?: BasketItemWhereUniqueInput[] | BasketItemWhereUniqueInput delete?: BasketItemWhereUniqueInput[] | BasketItemWhereUniqueInput update?: | BasketItemUpdateWithWhereUniqueWithoutCustomerInput[] | BasketItemUpdateWithWhereUniqueWithoutCustomerInput upsert?: | BasketItemUpsertWithWhereUniqueWithoutCustomerInput[] | BasketItemUpsertWithWhereUniqueWithoutCustomerInput } export interface CustomerWhereUniqueInput { id?: ID_Input email?: String } export interface CustomerUpdateInput { email?: String basket?: BasketItemUpdateManyWithoutCustomerInput } export interface ProductWhereUniqueInput { id?: ID_Input } export interface GrocerUpdateInput { email?: String } export interface CustomerUpdateOneWithoutBasketInput { create?: CustomerCreateWithoutBasketInput connect?: CustomerWhereUniqueInput delete?: Boolean update?: CustomerUpdateWithoutBasketDataInput upsert?: CustomerUpsertWithoutBasketInput } export interface CustomerCreateWithoutBasketInput { email: String } export interface BasketItemWhereInput { AND?: BasketItemWhereInput[] | BasketItemWhereInput OR?: BasketItemWhereInput[] | BasketItemWhereInput NOT?: BasketItemWhereInput[] | BasketItemWhereInput id?: ID_Input id_not?: ID_Input id_in?: ID_Input[] | ID_Input id_not_in?: ID_Input[] | ID_Input id_lt?: ID_Input id_lte?: ID_Input id_gt?: ID_Input id_gte?: ID_Input id_contains?: ID_Input id_not_contains?: ID_Input id_starts_with?: ID_Input id_not_starts_with?: ID_Input id_ends_with?: ID_Input id_not_ends_with?: ID_Input quantity?: Int quantity_not?: Int quantity_in?: Int[] | Int quantity_not_in?: Int[] | Int quantity_lt?: Int quantity_lte?: Int quantity_gt?: Int quantity_gte?: Int customer?: CustomerWhereInput product?: ProductWhereInput } export interface CustomerCreateOneWithoutBasketInput { create?: CustomerCreateWithoutBasketInput connect?: CustomerWhereUniqueInput } export interface CustomerSubscriptionWhereInput { AND?: CustomerSubscriptionWhereInput[] | CustomerSubscriptionWhereInput OR?: CustomerSubscriptionWhereInput[] | CustomerSubscriptionWhereInput NOT?: CustomerSubscriptionWhereInput[] | CustomerSubscriptionWhereInput mutation_in?: MutationType[] | MutationType updatedFields_contains?: String updatedFields_contains_every?: String[] | String updatedFields_contains_some?: String[] | String node?: CustomerWhereInput } export interface GrocerCreateInput { email: String } export interface GrocerWhereUniqueInput { id?: ID_Input email?: String } export interface CustomerUpdateWithoutBasketDataInput { email?: String } export interface ProductCreateOneInput { create?: ProductCreateInput connect?: ProductWhereUniqueInput } export interface BasketItemCreateWithoutCustomerInput { quantity: Int product: ProductCreateOneInput } export interface BasketItemCreateManyWithoutCustomerInput { create?: | BasketItemCreateWithoutCustomerInput[] | BasketItemCreateWithoutCustomerInput connect?: BasketItemWhereUniqueInput[] | BasketItemWhereUniqueInput } export interface BasketItemCreateInput { quantity: Int customer: CustomerCreateOneWithoutBasketInput product: ProductCreateOneInput } export interface BasketItemUpdateInput { quantity?: Int customer?: CustomerUpdateOneWithoutBasketInput product?: ProductUpdateOneInput } export interface BasketItemWhereUniqueInput { id?: ID_Input } export interface ProductUpdateInput { name?: String description?: String price?: Int } export interface ProductSubscriptionWhereInput { AND?: ProductSubscriptionWhereInput[] | ProductSubscriptionWhereInput OR?: ProductSubscriptionWhereInput[] | ProductSubscriptionWhereInput NOT?: ProductSubscriptionWhereInput[] | ProductSubscriptionWhereInput mutation_in?: MutationType[] | MutationType updatedFields_contains?: String updatedFields_contains_every?: String[] | String updatedFields_contains_some?: String[] | String node?: ProductWhereInput } /* * An object with an ID */ export interface Node { id: ID_Output } export interface Product extends Node { id: ID_Output createdAt: DateTime updatedAt: DateTime name: String description: String price: Int } export interface ProductPreviousValues { id: ID_Output createdAt: DateTime updatedAt: DateTime name: String description: String price: Int } export interface BatchPayload { count: Long } /* * An edge in a connection. */ export interface ProductEdge { node: Product cursor: String } export interface AggregateProduct { count: Int } export interface Customer extends Node { id: ID_Output createdAt: DateTime updatedAt: DateTime email: String basket?: BasketItem[] } /* * A connection to a list of items. */ export interface ProductConnection { pageInfo: PageInfo edges: ProductEdge[] aggregate: AggregateProduct } export interface AggregateBasketItem { count: Int } /* * An edge in a connection. */ export interface BasketItemEdge { node: BasketItem cursor: String } export interface AggregateCustomer { count: Int } export interface BasketItem extends Node { id: ID_Output customer: Customer product: Product quantity: Int } /* * A connection to a list of items. */ export interface CustomerConnection { pageInfo: PageInfo edges: CustomerEdge[] aggregate: AggregateCustomer } export interface BasketItemPreviousValues { id: ID_Output quantity: Int } /* * An edge in a connection. */ export interface GrocerEdge { node: Grocer cursor: String } export interface GrocerSubscriptionPayload { mutation: MutationType node?: Grocer updatedFields?: String[] previousValues?: GrocerPreviousValues } /* * Information about pagination in a connection. */ export interface PageInfo { hasNextPage: Boolean hasPreviousPage: Boolean startCursor?: String endCursor?: String } export interface Grocer extends Node { id: ID_Output createdAt: DateTime updatedAt: DateTime email: String } export interface CustomerPreviousValues { id: ID_Output createdAt: DateTime updatedAt: DateTime email: String } export interface CustomerSubscriptionPayload { mutation: MutationType node?: Customer updatedFields?: String[] previousValues?: CustomerPreviousValues } export interface BasketItemSubscriptionPayload { mutation: MutationType node?: BasketItem updatedFields?: String[] previousValues?: BasketItemPreviousValues } export interface GrocerPreviousValues { id: ID_Output createdAt: DateTime updatedAt: DateTime email: String } /* * A connection to a list of items. */ export interface BasketItemConnection { pageInfo: PageInfo edges: BasketItemEdge[] aggregate: AggregateBasketItem } /* * A connection to a list of items. */ export interface GrocerConnection { pageInfo: PageInfo edges: GrocerEdge[] aggregate: AggregateGrocer } export interface ProductSubscriptionPayload { mutation: MutationType node?: Product updatedFields?: String[] previousValues?: ProductPreviousValues } export interface AggregateGrocer { count: Int } /* * An edge in a connection. */ export interface CustomerEdge { node: Customer cursor: String } /* The `Long` scalar type represents non-fractional signed whole numeric values. Long can represent values between -(2^63) and 2^63 - 1. */ export type Long = string /* The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as `"4"`) or integer (such as `4`) input value will be accepted as an ID. */ export type ID_Input = string | number export type ID_Output = string /* The `Boolean` scalar type represents `true` or `false`. */ export type Boolean = boolean /* The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text. */ export type String = string export type DateTime = Date | string /* The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1. */ export type Int = number
the_stack
import { Category, toolbar } from './annotations'; import CategoricalColumn from './CategoricalColumn'; import Column, { widthChanged, labelChanged, metaDataChanged, dirty, dirtyHeader, dirtyValues, dirtyCaches, rendererTypeChanged, groupRendererChanged, summaryRendererChanged, visibilityChanged, DEFAULT_COLOR, } from './Column'; import type { ICategoricalColumn, ICategory, ICategoricalColorMappingFunction } from './ICategoricalColumn'; import type { IDataRow, IGroup, IValueColumnDesc, ITypeFactory } from './interfaces'; import { colorPool, integrateDefaults } from './internal'; import { missingGroup } from './missing'; import type { dataLoaded } from './ValueColumn'; import ValueColumn from './ValueColumn'; import type { IEventListener } from '../internal'; import { DEFAULT_CATEGORICAL_COLOR_FUNCTION } from './CategoricalColorMappingFunction'; export interface ICategoryNode extends ICategory { children: Readonly<ICategoryNode>[]; } export interface IPartialCategoryNode extends Partial<ICategory> { children: IPartialCategoryNode[]; } export interface IHierarchyDesc { hierarchy: IPartialCategoryNode; hierarchySeparator?: string; } export declare type IHierarchyColumnDesc = IHierarchyDesc & IValueColumnDesc<string>; export interface ICategoryInternalNode extends ICategory { path: string; children: Readonly<ICategoryInternalNode>[]; } export interface ICutOffNode { node: Readonly<ICategoryInternalNode>; maxDepth: number; } /** * emitted when the color mapping property changes * @asMemberOf HierarchyColumn * @event */ export declare function colorMappingChanged_HC( previous: ICategoricalColorMappingFunction, current: ICategoricalColorMappingFunction ): void; /** * emitted when the cut off property changes * @asMemberOf HierarchyColumn * @event */ export declare function cutOffChanged(previous: ICutOffNode, current: ICutOffNode): void; /** * column for hierarchical categorical values */ @toolbar('rename', 'clone', 'sort', 'sortBy', 'cutoff', 'group', 'groupBy', 'colorMappedCategorical') @Category('categorical') export default class HierarchyColumn extends ValueColumn<string> implements ICategoricalColumn { static readonly EVENT_CUTOFF_CHANGED = 'cutOffChanged'; static readonly EVENT_COLOR_MAPPING_CHANGED = 'colorMappingChanged'; private readonly hierarchySeparator: string; readonly hierarchy: Readonly<ICategoryInternalNode>; private currentNode: Readonly<ICategoryInternalNode>; private currentMaxDepth = Number.POSITIVE_INFINITY; private currentLeaves: Readonly<ICategoryInternalNode>[] = []; private readonly currentLeavesNameCache = new Map<string, Readonly<ICategoryInternalNode>>(); private readonly currentLeavesPathCache = new Map<string, Readonly<ICategoryInternalNode>>(); private colorMapping: ICategoricalColorMappingFunction; constructor(id: string, desc: Readonly<IHierarchyColumnDesc>) { super( id, integrateDefaults(desc, { renderer: 'categorical', }) ); this.hierarchySeparator = desc.hierarchySeparator || '.'; this.hierarchy = this.initHierarchy(desc.hierarchy); this.currentNode = this.hierarchy; this.currentLeaves = computeLeaves(this.currentNode, this.currentMaxDepth); this.updateCaches(); this.colorMapping = DEFAULT_CATEGORICAL_COLOR_FUNCTION; } private initHierarchy(root: IPartialCategoryNode) { const colors = colorPool(); const s = this.hierarchySeparator; const add = (prefix: string, node: IPartialCategoryNode): ICategoryInternalNode => { const name = node.name == null ? String(node.value) : node.name; const children = (node.children || []).map((child: IPartialCategoryNode | string): ICategoryInternalNode => { if (typeof child === 'string') { const path = prefix + child; return { path, name: child, label: path, color: colors(), value: 0, children: [], }; } const r = add(`${prefix}${name}${s}`, child); if (!r.color) { //hack to inject the next color (r as any).color = colors(); } return r; }); const path = prefix + name; const label = node.label ? node.label : path; return { path, name, children, label, color: node.color!, value: 0 }; }; return add('', root); } get categories() { return this.currentLeaves; } protected createEventList() { return super .createEventList() .concat([HierarchyColumn.EVENT_COLOR_MAPPING_CHANGED, HierarchyColumn.EVENT_CUTOFF_CHANGED]); } on(type: typeof HierarchyColumn.EVENT_CUTOFF_CHANGED, listener: typeof cutOffChanged | null): this; on(type: typeof HierarchyColumn.EVENT_COLOR_MAPPING_CHANGED, listener: typeof colorMappingChanged_HC | null): this; on(type: typeof ValueColumn.EVENT_DATA_LOADED, listener: typeof dataLoaded | null): this; on(type: typeof Column.EVENT_WIDTH_CHANGED, listener: typeof widthChanged | null): this; on(type: typeof Column.EVENT_LABEL_CHANGED, listener: typeof labelChanged | null): this; on(type: typeof Column.EVENT_METADATA_CHANGED, listener: typeof metaDataChanged | null): this; on(type: typeof Column.EVENT_DIRTY, listener: typeof dirty | null): this; on(type: typeof Column.EVENT_DIRTY_HEADER, listener: typeof dirtyHeader | null): this; on(type: typeof Column.EVENT_DIRTY_VALUES, listener: typeof dirtyValues | null): this; on(type: typeof Column.EVENT_DIRTY_CACHES, listener: typeof dirtyCaches | null): this; on(type: typeof Column.EVENT_RENDERER_TYPE_CHANGED, listener: typeof rendererTypeChanged | null): this; on(type: typeof Column.EVENT_GROUP_RENDERER_TYPE_CHANGED, listener: typeof groupRendererChanged | null): this; on(type: typeof Column.EVENT_SUMMARY_RENDERER_TYPE_CHANGED, listener: typeof summaryRendererChanged | null): this; on(type: typeof Column.EVENT_VISIBILITY_CHANGED, listener: typeof visibilityChanged | null): this; on(type: string | string[], listener: IEventListener | null): this; // required for correct typings in *.d.ts on(type: string | string[], listener: IEventListener | null): this { return super.on(type as any, listener); } dump(toDescRef: (desc: any) => any): any { const r = super.dump(toDescRef); r.colorMapping = this.colorMapping.toJSON(); if (isFinite(this.currentMaxDepth)) { r.maxDepth = this.currentMaxDepth; } if (this.currentNode !== this.hierarchy) { r.cutOffNode = this.currentNode.path; } return r; } restore(dump: any, factory: ITypeFactory) { super.restore(dump, factory); this.colorMapping = factory.categoricalColorMappingFunction(dump.colorMapping, this.categories); if (typeof dump.maxDepth !== 'undefined') { this.currentMaxDepth = dump.maxDepth; } if (typeof dump.cutOffNode !== 'undefined') { const path = dump.cutOffNode.split(this.hierarchySeparator); let node: Readonly<ICategoryInternalNode> | null = this.hierarchy; const findName = (act: string) => { return (d: { name: string }) => d.name === act; }; let act = path.shift(); while (act && node) { if (node.name !== act) { node = null; break; } const next = path.shift(); if (!next) { break; } act = next; node = node.children.find(findName(act)) || null; } this.currentNode = node || this.hierarchy; } if (typeof dump.maxDepth !== 'undefined' || typeof dump.cutOffNode !== 'undefined') { this.currentLeaves = computeLeaves(this.currentNode, this.currentMaxDepth); this.updateCaches(); } } getColorMapping() { return this.colorMapping.clone(); } setColorMapping(mapping: ICategoricalColorMappingFunction) { if (this.colorMapping.eq(mapping)) { return; } this.fire( [ CategoricalColumn.EVENT_COLOR_MAPPING_CHANGED, Column.EVENT_DIRTY_VALUES, Column.EVENT_DIRTY_HEADER, Column.EVENT_DIRTY, ], this.colorMapping.clone(), (this.colorMapping = mapping) ); } getCutOff(): ICutOffNode { return { node: this.currentNode, maxDepth: this.currentMaxDepth, }; } setCutOff(value: ICutOffNode) { const maxDepth = value.maxDepth == null ? Number.POSITIVE_INFINITY : value.maxDepth; if (this.currentNode === value.node && this.currentMaxDepth === maxDepth) { return; } const bak = this.getCutOff(); this.currentNode = value.node; this.currentMaxDepth = maxDepth; this.currentLeaves = computeLeaves(value.node, maxDepth); this.updateCaches(); this.fire( [HierarchyColumn.EVENT_CUTOFF_CHANGED, Column.EVENT_DIRTY_HEADER, Column.EVENT_DIRTY_VALUES, Column.EVENT_DIRTY], bak, this.getCutOff() ); } getCategory(row: IDataRow) { let v = super.getValue(row); if (v == null || v === '') { return null; } v = v.trim(); if (this.currentLeavesNameCache.has(v)) { return this.currentLeavesNameCache.get(v)!; } if (this.currentLeavesPathCache.has(v)) { return this.currentLeavesPathCache.get(v)!; } return ( this.currentLeaves.find((n) => { //direct hit or is a child of it return n.path === v || n.name === v || v!.startsWith(n.path + this.hierarchySeparator); }) || null ); } get dataLength() { return this.currentLeaves.length; } get labels() { return this.currentLeaves.map((d) => d.label); } getValue(row: IDataRow) { const v = this.getCategory(row); return v ? v.name : null; } getCategories(row: IDataRow) { return [this.getCategory(row)]; } iterCategory(row: IDataRow) { return [this.getCategory(row)]; } getLabel(row: IDataRow) { return CategoricalColumn.prototype.getLabel.call(this, row); } getColor(row: IDataRow) { return CategoricalColumn.prototype.getColor.call(this, row); } getLabels(row: IDataRow) { return CategoricalColumn.prototype.getLabels.call(this, row); } getValues(row: IDataRow) { return CategoricalColumn.prototype.getValues.call(this, row); } getMap(row: IDataRow) { return CategoricalColumn.prototype.getMap.call(this, row); } getMapLabel(row: IDataRow) { return CategoricalColumn.prototype.getMapLabel.call(this, row); } getSet(row: IDataRow) { return CategoricalColumn.prototype.getSet.call(this, row); } toCompareValue(row: IDataRow) { return CategoricalColumn.prototype.toCompareValue.call(this, row); } toCompareValueType() { return CategoricalColumn.prototype.toCompareValueType.call(this); } group(row: IDataRow): IGroup { const base = this.getCategory(row); if (!base) { return Object.assign({}, missingGroup); } return { name: base.label, color: base.color }; } private updateCaches() { this.currentLeavesPathCache.clear(); this.currentLeavesNameCache.clear(); this.currentLeaves.forEach((n) => { this.currentLeavesPathCache.set(n.path, n); this.currentLeavesNameCache.set(n.name, n); }); } } function computeLeaves(node: ICategoryInternalNode, maxDepth = Number.POSITIVE_INFINITY) { const leaves: ICategoryInternalNode[] = []; //depth first const visit = (node: ICategoryInternalNode, depth: number) => { //hit or end if (depth >= maxDepth || node.children.length === 0) { leaves.push(node); } else { // go down node.children.forEach((c) => visit(c, depth + 1)); } }; visit(node, 0); return leaves; } export function resolveInnerNodes(node: ICategoryInternalNode) { //breath first const queue: ICategoryInternalNode[] = [node]; let index = 0; while (index < queue.length) { const next = queue[index++]; for (const n of next.children) { queue.push(n); } } return queue; } export function isHierarchical(categories: (string | Partial<ICategory>)[]) { if (categories.length === 0 || typeof categories[0] === 'string') { return false; } // check if any has a given parent name return categories.some((c) => (c as any).parent != null); } export function deriveHierarchy(categories: (Partial<ICategory> & { parent: string | null })[]) { const lookup = new Map<string, ICategoryNode>(); categories.forEach((c) => { const p = c.parent || ''; // set and fill up proxy const item = Object.assign( { children: [], label: c.name!, name: c.name!, color: DEFAULT_COLOR, value: 0, } as ICategoryNode, lookup.get(c.name!) || {}, c ); lookup.set(c.name!, item); if (!lookup.has(p)) { // create proxy lookup.set(p, { name: p, children: [], label: p, value: 0, color: DEFAULT_COLOR }); } lookup.get(p)!.children.push(item); }); const root = lookup.get('')!; console.assert(root !== undefined, 'hierarchy with no root'); if (root.children.length === 1) { return root.children[0]; } return root; }
the_stack
export type DflowId = string; export type DflowNewItem<Item> = Omit<Item, "id"> & { id?: DflowId }; export type DflowNodeKind = string; export type DflowNodeMetadata = { label?: string; isAsync?: boolean; isConstant?: boolean; }; export type DflowPinKind = "input" | "output"; export type DflowPinType = | "string" | "number" | "boolean" | "null" | "object" | "array" | "DflowId" | "DflowGraph" | "DflowType"; export type DflowRunStatus = "waiting" | "success" | "failure"; // Inspiration from https://github.com/sindresorhus/type-fest/blob/main/source/basic.d.ts export type DflowObject = { [Key in string]?: DflowValue }; export type DflowArray = Array<DflowValue>; export type DflowValue = | string | number | boolean | null | undefined | DflowArray | DflowObject | DflowSerializedGraph; export type DflowNodesCatalog = Record<DflowNodeKind, typeof DflowNode>; export type DflowSerializedItem = { id: DflowId; name?: string; }; export type DflowSerializedNode = DflowSerializedItem & { kind: DflowNodeKind; inputs?: DflowSerializedInput[]; outputs?: DflowSerializedOutput[]; }; export type DflowSerializedPin = DflowSerializedItem & { types?: DflowPinType[]; }; export type DflowSerializedInput = DflowSerializedPin; export type DflowSerializedOutput = DflowSerializedPin & { data?: DflowValue; }; export type DflowSerializedPinPath = [nodeId: DflowId, pinId: DflowId]; export type DflowSerializedEdge = DflowSerializedItem & { source: DflowSerializedPinPath; target: DflowSerializedPinPath; }; export type DflowSerializedGraph = DflowSerializedItem & { nodes: DflowSerializedNode[]; edges: DflowSerializedEdge[]; }; export type DflowNewGraph = DflowNewItem<DflowSerializedGraph>; export type DflowNewEdge = DflowNewItem<DflowSerializedEdge>; export type DflowNewInput = DflowNewItem<DflowSerializedInput>; export type DflowNewOutput = DflowNewItem<DflowSerializedOutput>; export type DflowNewNode = DflowNewItem<DflowSerializedNode>; export type DflowNodeConnections = { sourceId: DflowId; targetId: DflowId }[]; const _missingString = (stringName: string) => `${stringName} must be a string`; const _missingMethod = ( methodName: string, nodeKind: string, ) => (`unimplemented method ${methodName} nodeKind=${nodeKind}`); const _missingNumber = (numberName: string) => `${numberName} must be a number`; const _missingPin = (nodeId: DflowId, kind: DflowPinKind) => `${kind} pin not found nodeId=${nodeId}`; const _missingPinAtPosition = ( nodeId: DflowId, kind: DflowPinKind, position: number, ) => `${_missingPin(nodeId, kind)} position=${position}`; const _missingPinById = (nodeId: DflowId, kind: DflowPinKind, pinId: DflowId) => `${_missingPin(nodeId, kind)} pinId=${pinId}`; export class DflowData { static isArray(data: DflowValue) { return Array.isArray(data); } static isBoolean(data: DflowValue) { return typeof data === "boolean"; } static isDflowGraph(data: DflowValue) { return typeof data === "object" && data !== null && !Array.isArray(data) && Array.isArray(data.nodes) && Array.isArray(data.edges) && DflowGraph.isDflowGraph(data as DflowSerializedGraph); } static isDflowId(data: DflowValue) { return DflowData.isStringNotEmpty(data); } static isDflowType(data: DflowValue) { return typeof data === "string" && DflowPin.types.includes(data); } static isObject(data: DflowValue) { return !DflowData.isUndefined(data) && !DflowData.isNull(data) && !DflowData.isArray(data) && typeof data === "object"; } static isNull(data: DflowValue) { return data === null; } static isNumber(data: DflowValue) { return typeof data === "number"; } static isString(data: DflowValue) { return typeof data === "string"; } static isStringNotEmpty(data: DflowValue) { return DflowData.isString(data) && (data as string).length > 0; } static isUndefined(data: DflowValue) { return typeof data === "undefined"; } static validate(data: DflowValue, types: DflowPinType[]) { if (types.length === 0) { return true; } return types.some((pinType) => { switch (pinType) { case "array": return DflowData.isArray(data); case "boolean": return DflowData.isBoolean(data); case "null": return DflowData.isNull(data); case "number": return DflowData.isNumber(data); case "object": return DflowData.isObject(data); case "string": return DflowData.isString(data); case "DflowGraph": return DflowData.isDflowGraph(data); case "DflowId": return DflowData.isDflowId(data); case "DflowType": return DflowData.isDflowType(data); default: return false; } }, true); } } export class DflowItem { readonly id: DflowId; name?: string; static isDflowItem({ id, name }: DflowSerializedItem) { return DflowData.isDflowId(id) && (DflowData.isUndefined(name) || DflowData.isStringNotEmpty(name)); } constructor({ id, name }: DflowSerializedPin) { this.id = id; this.name = name; } toJSON() { return JSON.stringify(this.toObject()); } toObject(): DflowSerializedItem { const obj = { id: this.id } as DflowSerializedItem; if (typeof this.name === "string") { obj.name = this.name; } return obj; } } export class DflowPin extends DflowItem { readonly kind: DflowPinKind; readonly types: DflowPinType[]; static types = [ "string", "number", "boolean", "null", "object", "array", "DflowId", "DflowGraph", "DflowType", ]; static isDflowPin({ types = [], ...item }: DflowSerializedPin) { return DflowItem.isDflowItem(item) && (types.every((pinType) => DflowPin.isDflowPinType(pinType))); } static isDflowPinType(pinType: DflowPinType) { DflowPin.types.includes(pinType); } constructor(kind: DflowPinKind, { types = [], ...pin }: DflowSerializedPin) { super(pin); this.kind = kind; this.types = types; } get hasTypeAny() { return this.types.length === 0; } get hasTypeDflowId() { return this.hasTypeAny || this.types.includes("DflowId"); } get hasTypeDflowGraph() { return this.hasTypeAny || this.types.includes("DflowGraph"); } get hasTypeDflowType() { return this.hasTypeAny || this.types.includes("DflowType"); } get hasTypeString() { return this.hasTypeAny || this.types.includes("string"); } get hasTypeNumber() { return this.hasTypeAny || this.types.includes("number"); } get hasTypeBoolean() { return this.hasTypeAny || this.types.includes("boolean"); } get hasTypeNull() { return this.hasTypeAny || this.types.includes("null"); } get hasTypeObject() { return this.hasTypeAny || this.types.includes("object"); } get hasTypeArray() { return this.hasTypeAny || this.types.includes("array"); } addType(pinType: DflowPinType) { this.types.push(pinType); } removeType(pinType: DflowPinType) { this.types.splice(this.types.indexOf(pinType), 1); } } export class DflowInput extends DflowPin { #source?: DflowOutput; static isDflowInput({ id, types }: DflowSerializedInput) { return DflowPin.isDflowPin({ id, types }); } constructor(pin: DflowSerializedInput) { super("input", pin); } get data(): DflowValue { return this.#source?.data; } get isConnected() { return typeof this.#source === "undefined"; } connectTo(pin: DflowOutput) { const { hasTypeAny: targetHasTypeAny, types: targetTypes } = this; const { types: sourceTypes } = pin; if ( targetHasTypeAny || ( targetTypes.some((pinType) => sourceTypes.includes(pinType)) ) ) { this.#source = pin; } else { throw new Error( `mismatching pinTypes, source has types [${sourceTypes.join()}] and target has types [${targetTypes.join()}]`, ); } } disconnect() { this.#source = undefined; } toObject(): DflowSerializedInput { const obj = { id: this.id } as DflowSerializedInput; if (this.types.length > 0) { obj.types = this.types; } return obj; } } export class DflowOutput extends DflowPin { #data?: DflowValue; static isDflowOutput({ id, data, types = [] }: DflowSerializedOutput) { return DflowPin.isDflowPin({ id, types }) && DflowData.validate(data, types); } constructor({ data, ...pin }: DflowSerializedOutput) { super("output", pin); this.#data = data; } clear() { this.#data = undefined; } get data(): DflowValue { return this.#data; } set data(data: DflowValue) { switch (true) { case DflowData.isUndefined(data): this.clear(); break; case this.hasTypeAny: case DflowData.isDflowGraph(data) && this.hasTypeDflowGraph: case DflowData.isDflowId(data) && this.hasTypeDflowId: case DflowData.isString(data) && this.hasTypeString: case DflowData.isNumber(data) && this.hasTypeNumber: case DflowData.isBoolean(data) && this.hasTypeBoolean: case DflowData.isNull(data) && this.hasTypeNull: case DflowData.isObject(data) && this.hasTypeObject: case DflowData.isArray(data) && this.hasTypeArray: { this.#data = data; break; } default: { throw new Error( `could not set data pinTypes=${ JSON.stringify(this.types) } typeof=${typeof data}`, ); } } } toObject(): DflowSerializedOutput { const obj = { ...super.toObject() } as DflowSerializedOutput; if (!DflowData.isUndefined(this.#data)) { obj.data = this.#data; } if (this.types.length > 0) { obj.types = this.types; } return obj; } } export class DflowNode extends DflowItem { readonly #inputs: Map<DflowId, DflowInput> = new Map(); readonly #outputs: Map<DflowId, DflowOutput> = new Map(); readonly #inputPosition: DflowId[] = []; readonly #outputPosition: DflowId[] = []; readonly #label?: string; readonly kind: string; readonly meta: DflowNodeMetadata; readonly host: DflowHost; static Task = class DflowNodeUnary extends DflowNode { task(): DflowValue { throw new Error(_missingMethod("task", this.kind)); } run() { for (const { data, types } of this.inputs) { if (DflowData.isUndefined(data) || !DflowData.validate(data, types)) { this.output(0).clear(); return; } } this.output(0).data = this.task(); } }; static kind: string; static isAsync?: DflowNodeMetadata["isAsync"]; static isConstant?: DflowNodeMetadata["isConstant"]; static label?: DflowNodeMetadata["label"]; static inputs?: DflowNewInput[]; static outputs?: DflowNewOutput[]; static generateInputIds(pins: DflowNewInput[] = []) { return pins.map((pin, i) => ({ ...pin, id: `i${i}` })); } static generateOutputIds(pins: DflowNewOutput[] = []) { return pins.map((pin, i) => ({ ...pin, id: `o${i}` })); } static in( types: DflowPinType[] = [], rest?: Omit<DflowNewInput, "types">, ): DflowNewInput[] { return [{ types, ...rest }]; } static ins(num: number, types: DflowPinType[] = []): DflowNewOutput[] { return Array(num).fill(DflowNode.in(types)).flat(); } static out( types: DflowPinType[] = [], rest?: Omit<DflowNewOutput, "types">, ): DflowNewOutput[] { return [{ types, ...rest }]; } static outs(num: number, types: DflowPinType[] = []): DflowNewOutput[] { return Array(num).fill(DflowNode.out(types)).flat(); } static outputNumber(obj: Omit<DflowNewOutput, "types">): DflowNewOutput { return { ...obj, types: ["number"] }; } static isDflowNode( { kind, inputs = [], outputs = [], ...item }: DflowSerializedNode, ) { return DflowItem.isDflowItem(item) && DflowData.isStringNotEmpty(kind) && // Check inputs. (inputs.every((input) => DflowInput.isDflowInput(input))) && // Check outputs. (outputs.every((output) => DflowOutput.isDflowOutput(output))); } constructor( { kind, inputs = [], outputs = [], ...item }: DflowSerializedNode, host: DflowHost, { isAsync = false, isConstant = false, label }: DflowNodeMetadata = {}, ) { super(item); this.#label = label; this.host = host; this.kind = kind; // Metadata. this.meta = { isAsync, isConstant }; // Inputs. for (const pin of inputs) { this.newInput(pin); } // Outputs. for (const pin of outputs) { this.newOutput(pin); } // Finally, call the onCreate() hook. this.onCreate(); } get label() { return this.#label || this.kind; } get inputs() { return this.#inputs.values(); } get outputs() { return this.#outputs.values(); } get numInputs() { return this.#inputs.size; } get numOutputs() { return this.#outputs.size; } generateInputId(i = this.numInputs): DflowId { const id = `i${i}`; return this.#inputs.has(id) ? this.generateInputId(i + 1) : id; } generateOutputId(i = this.numOutputs): DflowId { const id = `o${i}`; return this.#outputs.has(id) ? this.generateOutputId(i + 1) : id; } getInputById(pinId: DflowId): DflowInput { if (typeof pinId !== "string") { throw new TypeError(_missingString("inputId")); } const pin = this.#inputs.get(pinId); if (pin instanceof DflowInput) { return pin; } else { throw new Error(_missingPinById(this.id, "input", pinId)); } } input(position: number): DflowInput { if (typeof position !== "number") { throw new TypeError(_missingNumber("position")); } const pinId = this.#inputPosition[position]; if (DflowData.isUndefined(pinId)) { throw new Error(_missingPinAtPosition(this.id, "input", position)); } return this.getInputById(pinId); } getOutputById(pinId: DflowId): DflowOutput { if (typeof pinId !== "string") { throw new TypeError(_missingString("outputId")); } const pin = this.#outputs.get(pinId); if (pin instanceof DflowOutput) { return pin; } else { throw new Error(_missingPinById(this.id, "output", pinId)); } } output(position: number): DflowOutput { if (typeof position !== "number") { throw new TypeError(_missingNumber("position")); } const pinId = this.#outputPosition[position]; if (DflowData.isUndefined(pinId)) { throw new Error(_missingPinAtPosition(this.id, "output", position)); } return this.getOutputById(pinId); } deleteInput(pinId: DflowId) { this.host.deleteEdgesConnectedToPin([this.id, pinId]); this.#inputs.delete(pinId); this.#inputPosition.splice(this.#inputPosition.indexOf(pinId), 1); } deleteOutput(pinId: DflowId) { this.host.deleteEdgesConnectedToPin([this.id, pinId]); this.#outputs.delete(pinId); this.#outputPosition.splice(this.#outputPosition.indexOf(pinId), 1); } /** The `onBeforeConnectInput()` method is a hook run just before edge creation when a node output is connected to another node input. */ onBeforeConnectInput(_sourceNode: DflowNode, _sourcePosition: number) {} /** The `onCreate()` method is a hook run after node instance is created. */ onCreate() {} newInput(obj: DflowNewInput): DflowInput { const id = DflowData.isDflowId(obj.id) ? obj.id as DflowId : this.generateInputId(); const pin = new DflowInput({ ...obj, id }); this.#inputs.set(id, pin); this.#inputPosition.push(id); return pin; } newOutput(obj: DflowNewOutput): DflowOutput { const id = DflowData.isDflowId(obj.id) ? obj.id as DflowId : this.generateOutputId(); const pin = new DflowOutput({ ...obj, id }); this.#outputs.set(id, pin); this.#outputPosition.push(id); return pin; } run(): void { throw new Error( `${this.constructor.name} does not implement a run() method`, ); } toObject(): DflowSerializedNode { const obj = { ...super.toObject(), kind: this.kind, } as DflowSerializedNode; const inputs = []; const outputs = []; for (const input of this.inputs) { inputs.push(input.toObject()); } if (inputs.length > 0) { obj.inputs = inputs; } for (const output of this.outputs) { outputs.push(output.toObject()); } if (outputs.length > 0) { obj.outputs = outputs; } return obj; } } export class DflowUnknownNode extends DflowNode { static kind = "Unknown"; constructor(obj: DflowSerializedNode, host: DflowHost) { super({ ...obj, kind: DflowUnknownNode.kind }, host); } run() {} } export class DflowEdge extends DflowItem { readonly source: DflowSerializedPinPath; readonly target: DflowSerializedPinPath; static isDflowEdge( { source, target, ...item }: DflowSerializedEdge, graph: DflowSerializedGraph, ) { return DflowItem.isDflowItem(item) && // Check source. (Array.isArray(source) && source.length === 2 && graph.nodes.find(( { id, outputs = [] }, ) => (id === source[0] && outputs.find(({ id }) => id === source[1])) )) && // Check target. (Array.isArray(target) && target.length === 2 && graph.nodes.find(( { id, inputs = [] }, ) => (id === target[0] && inputs.find(({ id }) => id === target[1])))); } constructor({ source, target, ...item }: DflowSerializedEdge) { super(item); // 1. Read source and target. const [sourceNodeId, sourcePinId] = source; const [targetNodeId, targetPinId] = target; // 2. Check their types. if (typeof sourceNodeId !== "string") { throw new TypeError(_missingString("sourceNodeId")); } if (typeof sourcePinId !== "string") { throw new TypeError(_missingString("sourcePinId")); } if (typeof targetNodeId !== "string") { throw new TypeError(_missingString("targetNodeId")); } if (typeof targetPinId !== "string") { throw new TypeError(_missingString("targetPinId")); } // 3. Store in memory. this.source = source; this.target = target; } toObject(): DflowSerializedEdge { return { ...super.toObject(), source: this.source, target: this.target, }; } } export class DflowGraph extends DflowItem { #runStatus: DflowRunStatus = "success"; readonly #nodes: Map<DflowId, DflowNode> = new Map(); readonly #edges: Map<DflowId, DflowEdge> = new Map(); static isDflowGraph(graph: DflowSerializedGraph): boolean { return graph.nodes.every((node) => DflowNode.isDflowNode(node)) && graph.edges.every((edge) => DflowEdge.isDflowEdge(edge, graph)); } static childrenOfNodeId( nodeId: DflowId, nodeConnections: { sourceId: DflowId; targetId: DflowId }[], ) { return nodeConnections .filter(({ sourceId }) => nodeId === sourceId) .map(({ targetId }) => targetId); } static parentsOfNodeId( nodeId: DflowId, nodeConnections: { sourceId: DflowId; targetId: DflowId }[], ) { return nodeConnections .filter(({ targetId }) => nodeId === targetId) .map(({ sourceId }) => sourceId); } static levelOfNodeId(nodeId: DflowId, nodeConnections: DflowNodeConnections) { const parentsNodeIds = DflowGraph.parentsOfNodeId( nodeId, nodeConnections, ); // 1. A node with no parent as level zero. if (parentsNodeIds.length === 0) { return 0; } // 2. Otherwise its level is the max level of its parents plus one. let maxLevel = 0; for (const parentNodeId of parentsNodeIds) { const level = DflowGraph.levelOfNodeId(parentNodeId, nodeConnections); maxLevel = Math.max(level, maxLevel); } return maxLevel + 1; } static ancestorsOfNodeId( nodeId: DflowId, nodeConnections: DflowNodeConnections, ): DflowId[] { const parentsNodeIds = DflowGraph.parentsOfNodeId( nodeId, nodeConnections, ); if (parentsNodeIds.length === 0) { return []; } else { return parentsNodeIds.reduce<DflowId[]>( (accumulator, parentNodeId, index, array) => { const ancestors = DflowGraph.ancestorsOfNodeId( parentNodeId, nodeConnections, ); const result = accumulator.concat(ancestors); // On last iteration, remove duplicates return index === array.length - 1 ? Array.from(new Set(array.concat(result))) : result; }, [], ); } } static sort( nodeIds: DflowId[], nodeConnections: DflowNodeConnections, ): DflowId[] { const levelOf: Record<DflowId, number> = {}; for (const nodeId of nodeIds) { levelOf[nodeId] = DflowGraph.levelOfNodeId(nodeId, nodeConnections); } return nodeIds.slice().sort((a, b) => (levelOf[a] <= levelOf[b] ? -1 : 1)); } get edges() { return this.#edges.values(); } get nodes() { return this.#nodes.values(); } get nodeConnections(): DflowNodeConnections { return [...this.#edges.values()].map((edge) => ({ sourceId: edge.source[0], targetId: edge.target[0], })); } get edgeIds() { return [...this.#edges.keys()]; } get nodeIds() { return [...this.#nodes.keys()]; } get numEdges() { return this.#edges.size; } get numNodes() { return this.#nodes.size; } get runStatusIsSuccess() { return this.#runStatus === "success"; } get runStatusIsWaiting() { return this.#runStatus === "waiting"; } get runStatusIsFailure() { return this.#runStatus === "failure"; } addEdge(edge: DflowEdge) { if (this.#edges.has(edge.id)) { throw new Error(`cannot overwrite edge, id=${edge.id}`); } else { this.#edges.set(edge.id, edge); } } addNode(node: DflowNode) { if (this.#nodes.has(node.id)) { throw new Error(`cannot overwrite node, id=${node.id}`); } else { this.#nodes.set(node.id, node); } } clear() { this.#nodes.clear(); this.#edges.clear(); } deleteEdge(edgeId: DflowId) { this.#edges.delete(edgeId); } deleteNode(nodeId: DflowId) { this.#nodes.delete(nodeId); } getNodeById(nodeId: DflowId): DflowNode { if (typeof nodeId !== "string") { throw new TypeError(_missingString("nodeId")); } const node = this.#nodes.get(nodeId); if (node instanceof DflowNode) { return node; } else { throw new Error(`DflowNode not found, id=${nodeId}`); } } getEdgeById(edgeId: DflowId): DflowEdge { if (typeof edgeId !== "string") { throw new TypeError(_missingString("edgeId")); } const edge = this.#edges.get(edgeId); if (edge instanceof DflowEdge) { return edge; } else { throw new Error(`DflowEdge not found, id=${edgeId}`); } } generateEdgeId(i = this.numEdges): DflowId { const id = `e${i}`; return this.#edges.has(id) ? this.generateEdgeId(i + 1) : id; } generateNodeId(i = this.numNodes): DflowId { const id = `n${i}`; return this.#nodes.has(id) ? this.generateNodeId(i + 1) : id; } nodeIdsInsideFunctions() { const ancestorsOfReturnNodes = []; // Find all "return" nodes and get their ancestors. for (const node of this.nodes) { if (node.kind === "return") { ancestorsOfReturnNodes.push( DflowGraph.ancestorsOfNodeId(node.id, this.nodeConnections), ); } } // Flatten and deduplicate results. return Array.from(new Set(ancestorsOfReturnNodes.flat())); } async run() { // Set runStatus to waiting if there was some unhandled error in a previous run. if (this.runStatusIsSuccess) { this.#runStatus = "waiting"; } // Get nodeIds // 1. filtered by nodes inside functions // 2. sorted by graph hierarchy const nodeIdsExcluded = this.nodeIdsInsideFunctions(); const nodeIds = DflowGraph.sort( this.nodeIds.filter((nodeId) => !nodeIdsExcluded.includes(nodeId)), this.nodeConnections, ); for (const nodeId of nodeIds) { const node = this.#nodes.get(nodeId) as DflowNode; try { if (node.meta.isConstant === false) { if (node.meta.isAsync) { await node.run(); } else { node.run(); } } } catch (error) { console.error(error); this.#runStatus = "failure"; } } // Set runStatus to success if there was no error. if (this.runStatusIsWaiting) { this.#runStatus = "success"; } } toObject(): DflowSerializedGraph { const obj = { ...super.toObject(), nodes: [], edges: [], } as DflowSerializedGraph; for (const node of this.nodes) { obj.nodes.push(node.toObject()); } for (const edge of this.edges) { obj.edges.push(edge.toObject()); } return obj; } } export class DflowHost { readonly #graph; readonly #nodesCatalog: DflowNodesCatalog; constructor(nodesCatalog: DflowNodesCatalog = {}) { this.#nodesCatalog = nodesCatalog; this.#graph = new DflowGraph({ id: "g1" }); } get edges() { return this.#graph.edges; } get nodes() { return this.#graph.nodes; } get numEdges() { return this.#graph.numEdges; } get numNodes() { return this.#graph.numNodes; } get nodeKinds() { return Object.keys(this.#nodesCatalog); } get runStatusIsSuccess() { return this.#graph.runStatusIsSuccess; } get runStatusIsWaiting() { return this.#graph.runStatusIsWaiting; } get runStatusIsFailure() { return this.#graph.runStatusIsFailure; } clearGraph() { this.#graph.clear(); } connect(sourceNode: DflowNode, sourcePosition = 0) { return { to: (targetNode: DflowNode, targetPosition = 0) => { const edgeId = this.#graph.generateEdgeId(); const sourcePin = sourceNode.output(sourcePosition); const targetPin = targetNode.input(targetPosition); // Hook. targetNode.onBeforeConnectInput(sourceNode, sourcePosition); this.newEdge({ id: edgeId, source: [sourceNode.id, sourcePin.id], target: [targetNode.id, targetPin.id], }); }, }; } deleteEdge(edgeId: DflowId) { if (typeof edgeId !== "string") { throw new TypeError(_missingString("edgeId")); } const edge = this.#graph.getEdgeById(edgeId); if (edge instanceof DflowEdge) { // 1. Cleanup target pin. const [targetNodeId, targetPinId] = edge.target; const targetNode = this.getNodeById(targetNodeId); const targetPin = targetNode.getInputById(targetPinId); targetPin.disconnect(); // 2. Delete edge. this.#graph.deleteEdge(edgeId); } else { throw new Error(`DflowEdge not found, id=${edgeId}`); } } deleteNode(nodeId: DflowId) { if (typeof nodeId !== "string") { throw new TypeError(_missingString("nodeId")); } const node = this.getNodeById(nodeId); if (node instanceof DflowNode) { // 1. Delete all edges connected to node. for (const edge of this.#graph.edges) { const { source: [sourceNodeId], target: [targetNodeId], } = edge; if (sourceNodeId === node.id || targetNodeId === node.id) { this.deleteEdge(edge.id); } } // 2. Delete node. this.#graph.deleteNode(nodeId); } else { throw new Error(`DflowNode not found, id=${nodeId}`); } } deleteEdgesConnectedToPin([nodeId, pinId]: DflowSerializedPinPath) { for (const edge of this.edges) { const [sourceNodeId, sourcePinId] = edge.source; const [targetNodeId, targetPinId] = edge.target; if ( (sourceNodeId === nodeId && sourcePinId === pinId) || (targetNodeId === nodeId && targetPinId === pinId) ) { this.deleteEdge(edge.id); } } } async executeFunction(functionId: DflowId, args: DflowArray) { // Get all return nodes connected to function node. const nodeConnections = this.#graph.nodeConnections; const childrenNodeIds = DflowGraph.childrenOfNodeId( functionId, nodeConnections, ); const returnNodeIds = []; for (const childrenNodeId of childrenNodeIds) { const node = this.getNodeById(childrenNodeId); if (node.kind === "return") { returnNodeIds.push(node.id); } } // Get all nodes inside function. const nodeIdsInsideFunction = returnNodeIds.reduce<DflowId[]>( (accumulator, returnNodeId, index, array) => { const ancestors = DflowGraph.ancestorsOfNodeId( returnNodeId, nodeConnections, ); const result = accumulator.concat(ancestors); // On last iteration, remove duplicates return index === array.length ? Array.from(new Set(result)) : result; }, [], ); // 1. get nodeIds sorted by graph hierarchy // 2. if it is an argument node, inject input data // 3. if if is a return node, output data // 4. otherwise run node const nodeIds = DflowGraph.sort( nodeIdsInsideFunction, nodeConnections, ); for (const nodeId of nodeIds) { const node = this.getNodeById(nodeId); try { switch (node.kind) { case "argument": { const argumentPosition = 0; node.output(0).data = args[argumentPosition]; break; } case "return": { return node.input(1).data; } default: { if (node.meta.isConstant === false) { if (node.meta.isAsync) { await node.run(); } else { node.run(); } } } } } catch (error) { console.error(error); } } } getEdgeById(edgeId: DflowId) { return this.#graph.getEdgeById(edgeId); } getNodeById(nodeId: DflowId) { return this.#graph.getNodeById(nodeId); } newNode(obj: DflowNewNode): DflowNode { const NodeClass = this.#nodesCatalog[obj.kind] ?? DflowUnknownNode; const id = DflowData.isDflowId(obj.id) ? obj.id as DflowId : this.#graph.generateNodeId(); const meta = { isAsync: NodeClass.isAsync, isConstant: NodeClass.isConstant, label: NodeClass.label, }; const inputs = Array.isArray(obj.inputs) ? obj.inputs : DflowNode.generateInputIds(NodeClass.inputs); const outputs = Array.isArray(obj.outputs) ? obj.outputs : DflowNode.generateOutputIds(NodeClass.outputs); const node = new NodeClass({ ...obj, id, inputs, outputs }, this, meta); this.#graph.addNode(node); return node; } newEdge(obj: DflowNewEdge): DflowEdge { const id = DflowData.isDflowId(obj.id) ? obj.id as DflowId : this.#graph.generateEdgeId(); const edge = new DflowEdge({ ...obj, id }); this.#graph.addEdge(edge); const [sourceNodeId, sourcePinId] = edge.source; const [targetNodeId, targetPinId] = edge.target; const sourceNode = this.#graph.getNodeById(sourceNodeId); const targetNode = this.#graph.getNodeById(targetNodeId); const sourcePin = sourceNode.getOutputById(sourcePinId); const targetPin = targetNode.getInputById(targetPinId); targetPin.connectTo(sourcePin); return edge; } newInput(nodeId: DflowId, obj: DflowNewInput): DflowInput { const node = this.#graph.getNodeById(nodeId); return node.newInput(obj); } newOutput(nodeId: DflowId, obj: DflowNewOutput): DflowOutput { const node = this.#graph.getNodeById(nodeId); return node.newOutput(obj); } toJSON() { return this.#graph.toJSON(); } toObject() { return this.#graph.toObject(); } async run() { await this.#graph.run(); } }
the_stack
import { ConnectionStatusType } from "../Common/Constants"; export interface DatabaseAccount { id: string; name: string; location: string; type: string; kind: string; properties: DatabaseAccountExtendedProperties; } export interface DatabaseAccountExtendedProperties { documentEndpoint?: string; disableLocalAuth?: boolean; tableEndpoint?: string; gremlinEndpoint?: string; cassandraEndpoint?: string; configurationOverrides?: ConfigurationOverrides; capabilities?: Capability[]; enableMultipleWriteLocations?: boolean; mongoEndpoint?: string; readLocations?: DatabaseAccountResponseLocation[]; writeLocations?: DatabaseAccountResponseLocation[]; enableFreeTier?: boolean; enableAnalyticalStorage?: boolean; isVirtualNetworkFilterEnabled?: boolean; ipRules?: IpRule[]; privateEndpointConnections?: unknown[]; } export interface DatabaseAccountResponseLocation { documentEndpoint: string; failoverPriority: number; id: string; locationId: string; locationName: string; provisioningState: string; } export interface IpRule { ipAddressOrRange: string; } export interface ConfigurationOverrides { EnableBsonSchema: string; } export interface Capability { name: string; description: string; } export interface AccessInputMetadata { accountName: string; apiEndpoint: string; apiKind: number; documentEndpoint: string; expiryTimestamp: string; mongoEndpoint?: string; } export enum ApiKind { SQL = 0, MongoDB, Table, Cassandra, Graph, MongoDBCompute, } export interface GenerateTokenResponse { readWrite: string; read: string; } export interface Subscription { uniqueDisplayName: string; displayName: string; subscriptionId: string; tenantId: string; state: string; subscriptionPolicies: SubscriptionPolicies; authorizationSource: string; } export interface SubscriptionPolicies { locationPlacementId: string; quotaId: string; spendingLimit?: string; } export interface Resource { _rid: string; _self: string; _etag: string; _ts: number | string; id: string; } export interface IType { name: string; code: number; } export interface IDataField { dataType: IType; hasNulls: boolean; isArray: boolean; schemaType: IType; name: string; path: string; maxRepetitionLevel: number; maxDefinitionLevel: number; } export interface ISchema { id: string; accountName: string; resource: string; fields: IDataField[]; } export interface ISchemaRequest { id: string; subscriptionId: string; resourceGroup: string; accountName: string; resource: string; status: string; } export interface Collection extends Resource { // Only in Mongo collections loaded via ARM shardKey?: { [key: string]: string; }; defaultTtl?: number; indexingPolicy?: IndexingPolicy; partitionKey?: PartitionKey; statistics?: Statistic[]; uniqueKeyPolicy?: UniqueKeyPolicy; conflictResolutionPolicy?: ConflictResolutionPolicy; changeFeedPolicy?: ChangeFeedPolicy; analyticalStorageTtl?: number; geospatialConfig?: GeospatialConfig; schema?: ISchema; requestSchema?: () => void; } export interface Database extends Resource { collections?: Collection[]; } export interface DocumentId extends Resource {} export interface ConflictId extends Resource { resourceId?: string; resourceType?: string; operationType?: string; content?: string; } export interface AuthHeaders { "x-ms-date": string; authorization: string; } export interface KeyResource { Token: string; } export interface IndexingPolicy { automatic: boolean; indexingMode: "consistent" | "lazy" | "none"; includedPaths: any; excludedPaths: any; compositeIndexes?: any; spatialIndexes?: any; } export interface PartitionKey { paths: string[]; kind: "Hash" | "Range" | "MultiHash"; version: number; systemKey?: boolean; } export interface Statistic { documentCount: number; id: string; partitionKeys: any[]; sizeInKB: number; } export interface QueryPreparationTimes { queryCompilationTime: any; logicalPlanBuildTime: any; physicalPlanBuildTime: any; queryOptimizationTime: any; } export interface RuntimeExecutionTimes { queryEngineExecutionTime: any; systemFunctionExecutionTime: any; userDefinedFunctionExecutionTime: any; } export interface QueryMetrics { clientSideMetrics: any; documentLoadTime: any; documentWriteTime: any; indexHitDocumentCount: number; indexLookupTime: any; outputDocumentCount: number; outputDocumentSize: number; queryPreparationTimes: QueryPreparationTimes; retrievedDocumentCount: number; retrievedDocumentSize: number; runtimeExecutionTimes: RuntimeExecutionTimes; totalQueryExecutionTime: any; vmExecutionTime: any; } export interface Offer { id: string; autoscaleMaxThroughput: number | undefined; manualThroughput: number | undefined; minimumThroughput: number | undefined; offerDefinition?: SDKOfferDefinition; offerReplacePending: boolean; } export interface SDKOfferDefinition extends Resource { offerVersion?: string; offerType?: string; content?: { offerThroughput: number; offerIsRUPerMinuteThroughputEnabled?: boolean; collectionThroughputInfo?: OfferThroughputInfo; offerAutopilotSettings?: AutoPilotOfferSettings; }; resource?: string; offerResourceId?: string; } export interface OfferThroughputInfo { minimumRUForCollection: number; numPhysicalPartitions: number; } export interface UniqueKeyPolicy { uniqueKeys: UniqueKey[]; } export interface UniqueKey { paths: string[]; } export interface CreateDatabaseAndCollectionRequest { databaseId: string; collectionId: string; offerThroughput: number; databaseLevelThroughput: boolean; partitionKey?: PartitionKey; indexingPolicy?: IndexingPolicy; uniqueKeyPolicy?: UniqueKeyPolicy; autoPilot?: AutoPilotCreationSettings; analyticalStorageTtl?: number; } export interface AutoPilotCreationSettings { maxThroughput?: number; } export interface Query { id: string; resourceId: string; queryName: string; query: string; } export interface AutoPilotOfferSettings { maximumTierThroughput?: number; maxThroughput?: number; targetMaxThroughput?: number; } export interface CreateDatabaseParams { autoPilotMaxThroughput?: number; databaseId: string; databaseLevelThroughput?: boolean; offerThroughput?: number; } export interface CreateCollectionParams { createNewDatabase: boolean; collectionId: string; databaseId: string; databaseLevelThroughput: boolean; offerThroughput: number; analyticalStorageTtl?: number; autoPilotMaxThroughput?: number; indexingPolicy?: IndexingPolicy; partitionKey?: PartitionKey; uniqueKeyPolicy?: UniqueKeyPolicy; createMongoWildcardIndex?: boolean; } export interface ReadDatabaseOfferParams { databaseId: string; databaseResourceId?: string; offerId?: string; } export interface ReadCollectionOfferParams { collectionId: string; databaseId: string; collectionResourceId?: string; offerId?: string; } export interface UpdateOfferParams { currentOffer: Offer; databaseId: string; autopilotThroughput: number; manualThroughput: number; collectionId?: string; migrateToAutoPilot?: boolean; migrateToManual?: boolean; } export interface Notification { id: string; kind: string; accountName: string; action: any; buttonValue?: any; collectionName?: string; databaseName?: string; description: string; endDateUtc: number; seenAtUtc: number; state: string; type: string; updatedAtUtc: string; } export enum ConflictResolutionMode { Custom = "Custom", LastWriterWins = "LastWriterWins", } /** * Represents the conflict resolution policy configuration for specifying how to resolve conflicts * in case writes from different regions result in conflicts on documents in the collection in the Azure Cosmos DB service. */ export interface ConflictResolutionPolicy { /** * Gets or sets the ConflictResolutionMode in the Azure Cosmos DB service. By default it is ConflictResolutionMode.LastWriterWins. */ mode?: keyof typeof ConflictResolutionMode; /** * Gets or sets the path which is present in each document in the Azure Cosmos DB service for last writer wins conflict-resolution. * This path must be present in each document and must be an integer value. * In case of a conflict occuring on a document, the document with the higher integer value in the specified path will be picked. * If the path is unspecified, by default the timestamp path will be used. * * This value should only be set when using ConflictResolutionMode.LastWriterWins. * * ```typescript * conflictResolutionPolicy.ConflictResolutionPath = "/name/first"; * ``` * */ conflictResolutionPath?: string; /** * Gets or sets the StoredProcedure which is used for conflict resolution in the Azure Cosmos DB service. * This stored procedure may be created after the Container is created and can be changed as required. * * 1. This value should only be set when using ConflictResolutionMode.Custom. * 2. In case the stored procedure fails or throws an exception, the conflict resolution will default to registering conflicts in the conflicts feed. * * ```typescript * conflictResolutionPolicy.ConflictResolutionProcedure = "resolveConflict" * ``` */ conflictResolutionProcedure?: string; } export interface ChangeFeedPolicy { retentionDuration: number; } export interface GeospatialConfig { type: string; } export interface RegionEndpoint { name: string; documentAccountEndpoint: string; } export interface Tenant { displayName: string; id: string; tenantId: string; countryCode: string; domains: Array<string>; } export interface AccountKeys { primaryMasterKey: string; secondaryMasterKey: string; primaryReadonlyMasterKey: string; secondaryReadonlyMasterKey: string; } export interface OperationStatus { status: string; id?: string; name?: string; // operationId properties?: any; error?: { code: string; message: string }; } export interface NotebookWorkspaceConnectionInfo { authToken: string; notebookServerEndpoint: string; } export interface NotebookWorkspaceFeedResponse { value: NotebookWorkspace[]; } export interface NotebookWorkspace { id: string; name: string; properties: { status: string; notebookServerEndpoint: string; }; } export interface NotebookConfigurationEndpoints { path: string; endpoints: NotebookConfigurationEndpointInfo[]; } export interface NotebookConfigurationEndpointInfo { type: string; endpoint: string; username: string; password: string; token: string; } export interface SparkClusterConnectionInfo { userName: string; password: string; endpoints: SparkClusterEndpoint[]; } export interface SparkClusterEndpoint { kind: SparkClusterEndpointKind; endpoint: string; } export enum SparkClusterEndpointKind { SparkUI = "SparkUI", HistoryServerUI = "HistoryServerUI", Livy = "Livy", } export interface RpParameters { db: string; offerThroughput?: number; st: Boolean; sid: string; rg: string; dba: string; partitionKeyVersion?: number; } export interface MongoParameters extends RpParameters { pk?: string; resourceUrl?: string; coll?: string; cd?: Boolean; is?: Boolean; rid?: string; rtype?: string; isAutoPilot?: Boolean; autoPilotThroughput?: string; analyticalStorageTtl?: number; } export interface MemoryUsageInfo { freeKB: number; totalKB: number; } export interface ContainerConnectionInfo { status: ConnectionStatusType; //need to add ram and rom info }
the_stack
import arreq from 'array-equal'; import $ from 'jquery'; import Vue from 'vue/dist/vue'; import { VueContext } from 'vue-context' import 'vue-context/dist/css/vue-context.css'; import './proof-trace.css'; import './menu.css'; class ProofTrace { data: Data root: Data.NodeEntry nodeIndex: { byId: JSONMap<Data.NodeId, Data.NodeEntry> childrenById: JSONMap<Data.NodeId, Data.NodeEntry[]> subtreeSizeById: JSONMap<Data.NodeId, number> statusById: JSONMap<Data.NodeId, Data.StatusEntry> viewById: JSONMap<Data.NodeId, View.Node> } view: Vue constructor(data: ProofTrace.Data) { this.data = data; this.root = this.data.nodes[0]; this.createIndex(); this.createView(); } createIndex() { this.nodeIndex = { byId: new JSONMap(), childrenById: new JSONMap(), subtreeSizeById: new JSONMap(), statusById: new JSONMap(), viewById: new JSONMap() }; // Build byId for (let node of this.data.nodes) { if (!this.nodeIndex.byId.get(node.id)) this.nodeIndex.byId.set(node.id, node); } // Build childrenById for (let node of this.data.nodes) { if (node.id.length >= 1) { var parent = node.id.slice(1); this.addChild(parent, node); } } // Build statusById for (let entry of this.data.statuses) { var id = entry.at; this.nodeIndex.statusById.set(id, entry); } for (let node of this.data.nodes.sort((a, b) => b.id.length - a.id.length)) { if (!this.nodeIndex.statusById.get(node.id)) { let children = (this.nodeIndex.childrenById.get(node.id) || []) .map(c => this.nodeIndex.statusById.get(c.id)); if (children.length) { switch (node.tag) { case Data.NodeType.OrNode: if (children.some(x => x && x.status.tag === 'Succeeded')) this.nodeIndex.statusById.set(node.id, {at: node.id, status: {tag: 'Succeeded', from: '*'}}); break; case Data.NodeType.AndNode: if (children.length == node.nChildren && children.every(x => x && x.status.tag === 'Succeeded')) this.nodeIndex.statusById.set(node.id, {at: node.id, status: {tag: 'Succeeded', from: '*'}}); break; } } } } // Build subtreeSizeById var sz = this.nodeIndex.subtreeSizeById; for (let node of this.data.nodes.sort((a, b) => b.id.length - a.id.length)) { let children = (this.nodeIndex.childrenById.get(node.id) || []); sz.set(node.id, 1 + children.map(u => sz.get(u.id) || 1) .reduce((x,y) => x + y, 0)); } } addChild(parent: Data.NodeId, child: Data.NodeEntry) { var m = this.nodeIndex.childrenById; // Note: nodes can re-occur if they were suspended during the search var l = m.get(parent) || []; if (!l.some(u => arreq(u.id, child.id))) m.set(parent, l.concat([child])); } children(node: Data.NodeEntry) { function lex2(a1: number[], a2: number[]) { let n = Math.min(2, a1.length, a2.length); for (let i = n - 1; i >= 0; i--) { if (a1[i] < a2[i]) return -1; else if (a1[i] > a2[i]) return 1; } return 0; } function byId2(u1: Data.NodeEntry, u2: Data.NodeEntry) { return lex2(u1.id, u2.id); } return (this.nodeIndex.childrenById.get(node.id) || []) .sort(byId2); // modifies the list but that's ok } createView() { this.view = new (Vue.component('proof-trace-pane'))(); this.view.root = this.createNode(this.root); this.expandNode(this.view.root); this.expandNode(this.view.root.children[0]); this.view.$mount(); this.view.$on('action', (ev: View.ActionEvent) => this.viewAction(ev)); } getStatus(node: Data.NodeEntry): Data.GoalStatusEntry { var entry = this.nodeIndex.statusById.get(node.id); return entry && entry.status; } getSubtreeSize(node: Data.NodeEntry): number { return this.nodeIndex.subtreeSizeById.get(node.id) || 1; } createNode(node: Data.NodeEntry): View.Node { var v = {value: node, children: undefined, focus: false, expanded: false, status: this.getStatus(node), numDescendants: this.getSubtreeSize(node)}; this.nodeIndex.viewById.set(node.id, v); return v; } expandNode(nodeView: View.Node, focus: boolean = false) { nodeView.focus = focus; nodeView.expanded = true; nodeView.children = this.children(nodeView.value) .map(node => this.createNode(node)); } expandOrNode(nodeView: View.Node, focus: boolean = false) { this.expandNode(nodeView, focus); for (let c of nodeView.children) { if (c.value.tag == Data.NodeType.AndNode) { this.expandOrNode(c, focus); } } } expandById(node: Data.NodeId, focus: boolean = false) { var view = this.nodeIndex.viewById.get(node); if (view) this.expandNode(view, focus); } expandByIds(nodes: Data.NodeId[]) { var sorted = nodes.slice().sort((a, b) => a.length - b.length); for (let node of sorted) this.expandById(node); } expandBranch(tip: Data.NodeId, focus: boolean = false) { var prefixes = tip.slice(1).map((_,i,u) => u.slice(-(i + 1))); for (let pfx of prefixes) this.expandById(pfx); // @todo focus tip } expandAll(nodeView: View.Node = this.view.root) { this.expandNode(nodeView); for (let c of nodeView.children) this.expandAll(c); } viewAction(ev: View.ActionEvent) { switch (ev.type) { case 'expand': this.expandOrNode(ev.target, true); break; case 'expandAll': this.expandAll(ev.target); break; case 'copyNodeId': this.copyJson(ev.target.value.id); break; } } copyJson(o: any) { navigator.clipboard.writeText(JSON.stringify(o)); } } namespace ProofTrace { export type Data = { nodes: Data.NodeEntry[], statuses: Data.StatusEntry[] }; export namespace Data { export type NodeEntry = { id: NodeId tag: NodeType pp: string goal: GoalEntry nChildren: number }; export type NodeId = number[]; export enum NodeType { AndNode = 'AndNode', OrNode = 'OrNode' }; export type GoalEntry = { id: string pre: string, post: string, sketch: string, programVars: [string, string][] existentials: [string, string][] ghosts: [string, string][] }; export type Environment = Map<string, {type: string, of: string}>; export type StatusEntry = { at: NodeId status: GoalStatusEntry }; export type GoalStatusEntry = {tag: "Succeeded" | "Failed", from?: string | string[]}; export function parse(traceText: string): Data { var entries = traceText.split('\n\n').filter(x => x).map(ln => JSON.parse(ln)); var nodes = [], statuses = []; for (let e of entries) { if (e.tag) nodes.push(e); else if (e.status) statuses.push(e); } return {nodes, statuses}; } export function envOfGoal(goal: GoalEntry) { var d: Environment = new Map; function intro(vs: [string, string][], of: string) { for (let [type, name] of vs) d.set(name, {type, of}); } intro(goal.programVars, 'programVars'); intro(goal.existentials, 'existentials'); intro(goal.ghosts, 'ghosts'); return d; } } // ========= // View Part // ========= export namespace View { export type Node = { value: Data.NodeEntry children: Node[] numDescendants: number status: Data.GoalStatusEntry focus: boolean expanded: boolean }; export type ActionEvent = { type: "expand" | "collapse" | "expandAll" | "menu" | "copyNodeId" | "copyGoalId" | "copyGoal", target: Node $event: MouseEvent }; const OPERATORS = new Map([ [':->', {pp: "↦"}], ['==', {pp: "="}], ['**', {pp: '∗'}], ['&&', {pp: "∧"}], ['not', {pp: "¬"}], ['=i', {pp: "=ᵢ"}], ['++', {pp: '∪'}]]); export function tokenize(pp: string, env: Data.Environment) { return pp.split(/(\s+|[(){}[\],])/).map(s => { var v = env.get(s), op = OPERATORS.get(s), mo: RegExpMatchArray; if (v) return {kind: 'var', text: s, pp: pprintIdentifier(s), ...v}; else if (op) return {kind: 'op', text: s, ...op}; else if (s.match(/^\s+$/)) return {kind: 'whitespace', text: s}; else if (s.match(/^[(){}[\]]$/)) return {kind: 'brace', text: s}; else if (mo = s.match(/^<(\w+)>$/)) { return {kind: 'cardinality', text: s, pp: pprintIdentifier(mo[1])}; } else if (s != '') return {kind: 'unknown', text: s}; }) .filter(x => x); } export function pprintIdentifier(v: string) { return v.replace('_alpha_', 'α'); } } } import Data = ProofTrace.Data; import View = ProofTrace.View; abstract class KeyedMap<K, V, K0> { _map: Map<K0, V> = new Map(); abstract key(k: K): K0; set(k: K, v: V) { this._map.set(this.key(k), v); } get(k: K) { return this._map.get(this.key(k)); } } class JSONMap<K, V> extends KeyedMap<K, V, string> { key(k: K) { return JSON.stringify(k); } } Vue.component('proof-trace-pane', { props: ['root'], data: () => ({options: {}, zoom: 1}), template: ` <div id="proof-trace-pane" :class="{'proof-trace-filter--only-success': options.proofOnly, 'proof-trace-filter--only-expanded': options.expandedOnly}"> <proof-trace-toolbar :options="options"/> <proof-trace-context-menu ref="contextMenu" @action="toplevelAction"/> <div class="proof-trace-pane-area" :style="{'--zoom': zoom}"> <proof-trace :root="root" @action="toplevelAction"/> </div> </div>`, methods: { toplevelAction(ev) { switch (ev.type) { case 'menu': this.$refs.contextMenu.open(ev); break; } this.$emit('action', ev); } } }); Vue.component('proof-trace', { props: ['root'], data: () => ({statusClass: undefined}), template: ` <div class="proof-trace" :class="[statusClass, root && root.children && root.children.length == 0 ? 'no-children' : 'has-children']"> <template v-if="root"> <proof-trace-node ref="nroot" :value="root.value" :status="root.status" :num-descendants="root.numDescendants" @action="nodeAction"/> <div class="proof-trace-expand-all" :class="{root: root.value.id.length == 0}"> <span @click="expandAll">++</span> </div> <div class="subtrees" ref="subtrees" v-if="root.expanded"> <template v-for="child in root.children"> <proof-trace :root="child" @action="action"/> </template> </div> </template> </div>`, mounted() { this.$watch('root.expanded', () => { requestAnimationFrame(() => { if (this.root.focus && this.$refs.subtrees) this.focusElement(this.$refs.subtrees); }); }); if (this.$refs.nroot) this.statusClass = this.$refs.nroot.statusClass; }, methods: { action(ev) { this.$emit('action', ev); }, nodeAction(ev) { if (ev.type == 'expand/collapse') { this.root.expanded = !this.root.expanded; ev.type = this.root.expanded ? 'expand' : 'collapse'; } this.action({...ev, target: this.root}); }, expandAll() { this.action({type: 'expandAll', target: this.root})}, focusElement(el: HTMLElement) { var box = el.getBoundingClientRect(), clrse = 50, viewport = (<any>window).visualViewport, v = (box.bottom + clrse) - viewport.height, hl = box.left - clrse - viewport.width * 0.33, hr = (box.right + clrse) - viewport.width, h = Math.min(hl, hr); window.scrollBy({left: Math.max(h, 0), top: Math.max(v, 0), behavior: 'smooth'}); } } }); Vue.component('proof-trace-node', { props: ['value', 'status', 'numDescendants'], data: () => ({_anchor: false}), template: ` <div class="proof-trace-node" :class="[value.tag, statusClass]" @click="toggle" @click.capture="clickCapture" @mouseenter="showId" @mouseleave="hideId" @mousedown="clickStart" @mouseover="showRefs" @mouseout="hideRefs" @contextmenu.prevent="action({type: 'menu', $event})"> <div @mousedown="stopDbl" class="title"> <span class="pp">{{value.pp}}</span> <span class="cost" v-if="value.cost >= 0">{{value.cost}}</span> <span class="num-descendants">{{numDescendants}}</span> <span class="goal-id" v-if="value.goal">{{value.goal.id}}</span> <span class="tag" v-else>{{tag}}</span> </div> <proof-trace-goal v-if="value.goal" :value="value.goal" @click.native.stop="action"/> </div>`, computed: { tag() { var pfx = (this.value.tag == Data.NodeType.OrNode) ? 2 : 1; return this.value.id.slice(0, pfx) .reverse().filter((n:number) => n >= 0).join('→'); }, statusClass() { if (this.status) { var {tag, from: fr} = this.status, suffix = fr ? (fr === '*' ? '*' : `-${fr}`) : '' return `${tag}${suffix}`; } else return undefined; } }, methods: { action(ev) { this.$emit('action', ev); }, toggle() { this.action({type: 'expand/collapse', target: this.value}); }, showId() { $('#hint').text(JSON.stringify(this.value.id)); }, hideId() { $('#hint').empty(); }, showRefs(ev) { var el = ev.target; if (['var', 'name', 'cardinality'].some(c => el.classList.contains(c))) { this.varSpans(el.textContent).addClass('highlight'); } }, hideRefs() { this.varSpans().removeClass('highlight'); }, varSpans(nm?: string) { if (nm) return this.varSpans().filter((_,x: Node) => x.textContent == nm); else { var el = $(this.$el); return el.find('span.var, span.cardinality, .proof-trace-vars span.name'); } }, stopDbl(ev) { if (ev.detail > 1) ev.preventDefault(); }, // boilerplate to prevent click after selection clickStart(ev) { this.$data._anchor = {x: ev.pageX, y: ev.pageY}; }, clickCapture(ev) { var a = this.$data._anchor; if (a && (Math.abs(ev.pageX - a.x) > 3 || Math.abs(ev.pageY - a.y) > 3)) ev.stopPropagation(); } } }); Vue.component('proof-trace-goal', { props: ['value'], template: ` <div class="proof-trace-goal"> <proof-trace-vars :value="value.programVars" class="proof-trace-program-vars"/> <proof-trace-vars :value="value.existentials" class="proof-trace-existentials"/> <proof-trace-formula class="proof-trace-pre" :pp="value.pre" :env="env"/> <div class="proof-trace-sketch">{{value.sketch}} </div> <proof-trace-formula class="proof-trace-post" :pp="value.post" :env="env"/> </div>`, computed: { env() { return Data.envOfGoal(this.value); } } }); Vue.component('proof-trace-vars', { props: ['value'], template: ` <div class="proof-trace-vars" v-show="value.length > 0"> <template v-for="v in value"> <span> <span class="type">{{v[0]}}</span> <span class="name">{{pp(v[1])}}</span> </span> </template> </div>`, methods: { pp: View.pprintIdentifier } }); Vue.component('proof-trace-formula', { props: ['pp', 'env', 'css-class'], template: ` <div class="proof-trace-formula"> <template v-for="token in tokenize(pp, env)"> <span :class="token.kind" :data-of="token.of">{{token.pp || token.text}}</span> </template> </div>`, methods: { tokenize: View.tokenize } }); Vue.component('proof-trace-toolbar', { props: {options: {default: () => ({})}}, template: ` <div class="proof-trace-toolbar"> <form> Show: <input type="checkbox" name="proof-only" id="proof-only" v-model="options.proofOnly"> <label for="proof-only">Proof only</label> <input type="checkbox" name="expanded-only" id="expanded-only" v-model="options.expandedOnly"> <label for="expended-only">Expanded only</label> </form> </div>` }); Vue.component('proof-trace-context-menu', { template: ` <vue-context ref="m"> <li><a name="expandAll" @click="action">Expand all</a></li> <li><a name="copyNodeId" @click="action">Copy Node Id</a></li> <li><a name="copyGoal" @click="action">Copy goal</a></li> </vue-context>`, components: {VueContext}, methods: { open(ev: View.ActionEvent) { this._target = ev.target; this.$refs.m.open(ev.$event); }, action(ev) { this.$emit('action', { type: ev.currentTarget.name, target: this._target }); } } }); export { ProofTrace }
the_stack
import { Either, isLeft, left, right } from 'fp-ts/lib/Either' import { Predicate, Refinement } from 'fp-ts/lib/function' // ------------------------------------------------------------------------------------- // Decode error // ------------------------------------------------------------------------------------- /** * @category Decode error * @since 1.0.0 */ export interface ContextEntry { readonly key: string readonly type: Decoder<any, any> /** the input data */ readonly actual?: unknown } /** * @category Decode error * @since 1.0.0 */ export interface Context extends ReadonlyArray<ContextEntry> {} /** * @category Decode error * @since 1.0.0 */ export interface ValidationError { /** the offending (sub)value */ readonly value: unknown /** where the error originated */ readonly context: Context /** optional custom error message */ readonly message?: string } /** * @category Decode error * @since 1.0.0 */ export interface Errors extends Array<ValidationError> {} /** * @category Decode error * @since 1.0.0 */ export type Validation<A> = Either<Errors, A> /** * @category Decode error * @since 1.0.0 */ export const failures: <T>(errors: Errors) => Validation<T> = left /** * @category Decode error * @since 1.0.0 */ export const failure = <T>(value: unknown, context: Context, message?: string): Validation<T> => failures([{ value, context, message }]) /** * @category Decode error * @since 1.0.0 */ export const success: <T>(value: T) => Validation<T> = right // ------------------------------------------------------------------------------------- // Codec // ------------------------------------------------------------------------------------- /** * @since 1.0.0 */ export type Is<A> = (u: unknown) => u is A /** * @since 1.0.0 */ export type Validate<I, A> = (i: I, context: Context) => Validation<A> /** * @since 1.0.0 */ export type Decode<I, A> = (i: I) => Validation<A> /** * @since 1.0.0 */ export type Encode<A, O> = (a: A) => O /** * @since 1.0.0 */ export interface Any extends Type<any, any, any> {} /** * @since 1.0.0 */ export interface Mixed extends Type<any, any, unknown> {} /** * @category Codec * @since 1.0.0 */ export type TypeOf<C extends Any> = C['_A'] /** * @category Codec * @since 1.0.0 */ export type InputOf<C extends Any> = C['_I'] /** * @category Codec * @since 1.0.0 */ export type OutputOf<C extends Any> = C['_O'] /** * @category Codec * @since 1.0.0 */ export interface Decoder<I, A> { readonly name: string readonly validate: Validate<I, A> readonly decode: Decode<I, A> } /** * @category Codec * @since 1.0.0 */ export interface Encoder<A, O> { readonly encode: Encode<A, O> } /** * @category Codec * @since 1.0.0 */ export class Type<A, O = A, I = unknown> implements Decoder<I, A>, Encoder<A, O> { /** * @since 1.0.0 */ readonly _A!: A /** * @since 1.0.0 */ readonly _O!: O /** * @since 1.0.0 */ readonly _I!: I constructor( /** a unique name for this codec */ readonly name: string, /** a custom type guard */ readonly is: Is<A>, /** succeeds if a value of type I can be decoded to a value of type A */ readonly validate: Validate<I, A>, /** converts a value of type A to a value of type O */ readonly encode: Encode<A, O> ) { this.decode = this.decode.bind(this) } /** * @since 1.0.0 */ pipe<B, IB, A extends IB, OB extends A>( this: Type<A, O, I>, ab: Type<B, OB, IB>, name: string = `pipe(${this.name}, ${ab.name})` ): Type<B, O, I> { return new Type( name, ab.is, (i, c) => { const e = this.validate(i, c) if (isLeft(e)) { return e } return ab.validate(e.right, c) }, this.encode === identity && ab.encode === identity ? (identity as any) : (b) => this.encode(ab.encode(b)) ) } /** * @since 1.0.0 */ asDecoder(): Decoder<I, A> { return this } /** * @since 1.0.0 */ asEncoder(): Encoder<A, O> { return this } /** * a version of `validate` with a default context * @since 1.0.0 */ decode(i: I): Validation<A> { return this.validate(i, [{ key: '', type: this, actual: i }]) } } // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * @since 1.0.0 */ export const identity = <A>(a: A): A => a /** * @since 1.0.0 */ export function getFunctionName(f: Function): string { return (f as any).displayName || (f as any).name || `<function${f.length}>` } /** * @since 1.0.0 */ export function getContextEntry(key: string, decoder: Decoder<any, any>): ContextEntry { return { key, type: decoder } } /** * @since 1.0.0 */ export function appendContext(c: Context, key: string, decoder: Decoder<any, any>, actual?: unknown): Context { const len = c.length const r = Array(len + 1) for (let i = 0; i < len; i++) { r[i] = c[i] } r[len] = { key, type: decoder, actual } return r } function pushAll<A>(xs: Array<A>, ys: Array<A>): void { const l = ys.length for (let i = 0; i < l; i++) { xs.push(ys[i]) } } const hasOwnProperty = Object.prototype.hasOwnProperty /** * @since 1.0.0 */ export interface AnyProps { [key: string]: Any } function getNameFromProps(props: Props): string { return Object.keys(props) .map((k) => `${k}: ${props[k].name}`) .join(', ') } function useIdentity(codecs: Array<Any>): boolean { for (let i = 0; i < codecs.length; i++) { if (codecs[i].encode !== identity) { return false } } return true } /** * @since 1.0.0 */ export type TypeOfProps<P extends AnyProps> = { [K in keyof P]: TypeOf<P[K]> } /** * @since 1.0.0 */ export type OutputOfProps<P extends AnyProps> = { [K in keyof P]: OutputOf<P[K]> } /** * @since 1.0.0 */ export interface Props { [key: string]: Mixed } function getInterfaceTypeName(props: Props): string { return `{ ${getNameFromProps(props)} }` } /** * @since 1.0.0 */ export type TypeOfPartialProps<P extends AnyProps> = { [K in keyof P]?: TypeOf<P[K]> } /** * @since 1.0.0 */ export type OutputOfPartialProps<P extends AnyProps> = { [K in keyof P]?: OutputOf<P[K]> } function getPartialTypeName(inner: string): string { return `Partial<${inner}>` } /** * @since 1.0.0 */ export type TypeOfDictionary<D extends Any, C extends Any> = { [K in TypeOf<D>]: TypeOf<C> } /** * @since 1.0.0 */ export type OutputOfDictionary<D extends Any, C extends Any> = { [K in OutputOf<D>]: OutputOf<C> } function enumerableRecord<D extends Mixed, C extends Mixed>( keys: Array<string>, domain: D, codomain: C, name: string = `{ [K in ${domain.name}]: ${codomain.name} }` ): RecordC<D, C> { const len = keys.length return new DictionaryType( name, (u): u is { [K in TypeOf<D>]: TypeOf<C> } => UnknownRecord.is(u) && keys.every((k) => codomain.is(u[k])), (u, c) => { const e = UnknownRecord.validate(u, c) if (isLeft(e)) { return e } const o = e.right const a: { [key: string]: any } = {} const errors: Errors = [] let changed: boolean = false for (let i = 0; i < len; i++) { const k = keys[i] const ok = o[k] const codomainResult = codomain.validate(ok, appendContext(c, k, codomain, ok)) if (isLeft(codomainResult)) { pushAll(errors, codomainResult.left) } else { const vok = codomainResult.right changed = changed || vok !== ok a[k] = vok } } return errors.length > 0 ? failures(errors) : success((changed || Object.keys(o).length !== len ? a : o) as any) }, codomain.encode === identity ? identity : (a: any) => { const s: { [key: string]: any } = {} for (let i = 0; i < len; i++) { const k = keys[i] s[k] = codomain.encode(a[k]) } return s as any }, domain, codomain ) } /** * @internal */ export function getDomainKeys<D extends Mixed>(domain: D): Record<string, unknown> | undefined { if (isLiteralC(domain)) { const literal = domain.value if (string.is(literal)) { return { [literal]: null } } } else if (isKeyofC(domain)) { return domain.keys } else if (isUnionC(domain)) { const keys = domain.types.map((type) => getDomainKeys(type)) return keys.some(undefinedType.is) ? undefined : Object.assign({}, ...keys) } return undefined } function nonEnumerableRecord<D extends Mixed, C extends Mixed>( domain: D, codomain: C, name: string = `{ [K in ${domain.name}]: ${codomain.name} }` ): RecordC<D, C> { return new DictionaryType( name, (u): u is { [K in TypeOf<D>]: TypeOf<C> } => { if (UnknownRecord.is(u)) { return Object.keys(u).every((k) => domain.is(k) && codomain.is(u[k])) } return isAnyC(codomain) && Array.isArray(u) }, (u, c) => { if (UnknownRecord.is(u)) { const a: { [key: string]: any } = {} const errors: Errors = [] const keys = Object.keys(u) const len = keys.length let changed: boolean = false for (let i = 0; i < len; i++) { let k = keys[i] const ok = u[k] const domainResult = domain.validate(k, appendContext(c, k, domain, k)) if (isLeft(domainResult)) { pushAll(errors, domainResult.left) } else { const vk = domainResult.right changed = changed || vk !== k k = vk const codomainResult = codomain.validate(ok, appendContext(c, k, codomain, ok)) if (isLeft(codomainResult)) { pushAll(errors, codomainResult.left) } else { const vok = codomainResult.right changed = changed || vok !== ok a[k] = vok } } } return errors.length > 0 ? failures(errors) : success((changed ? a : u) as any) } if (isAnyC(codomain) && Array.isArray(u)) { return success(u) } return failure(u, c) }, domain.encode === identity && codomain.encode === identity ? identity : (a) => { const s: { [key: string]: any } = {} const keys = Object.keys(a) const len = keys.length for (let i = 0; i < len; i++) { const k = keys[i] s[String(domain.encode(k))] = codomain.encode(a[k]) } return s as any }, domain, codomain ) } function getUnionName<CS extends [Mixed, Mixed, ...Array<Mixed>]>(codecs: CS): string { return '(' + codecs.map((type) => type.name).join(' | ') + ')' } /** * @internal */ export function mergeAll(base: any, us: Array<any>): any { let equal = true let primitive = true const baseIsNotADictionary = !UnknownRecord.is(base) for (const u of us) { if (u !== base) { equal = false } if (UnknownRecord.is(u)) { primitive = false } } if (equal) { return base } else if (primitive) { return us[us.length - 1] } const r: any = {} for (const u of us) { for (const k in u) { if (!r.hasOwnProperty(k) || baseIsNotADictionary || u[k] !== base[k]) { r[k] = u[k] } } } return r } /** * @since 1.1.0 */ export interface HasPropsRefinement extends RefinementType<HasProps, any, any, any> {} /** * @since 1.1.0 */ export interface HasPropsReadonly extends ReadonlyType<HasProps, any, any, any> {} /** * @since 1.1.0 */ export interface HasPropsIntersection extends IntersectionType<Array<HasProps>, any, any, any> {} /** * @since 1.1.0 */ export type HasProps = | HasPropsRefinement | HasPropsReadonly | HasPropsIntersection | InterfaceType<any, any, any, any> // tslint:disable-next-line: deprecation | StrictType<any, any, any, any> | PartialType<any, any, any, any> function getProps(codec: HasProps): Props { switch (codec._tag) { case 'RefinementType': case 'ReadonlyType': return getProps(codec.type) case 'InterfaceType': case 'StrictType': case 'PartialType': return codec.props case 'IntersectionType': return codec.types.reduce<Props>((props, type) => Object.assign(props, getProps(type)), {}) } } function stripKeys(o: any, props: Props): unknown { const keys = Object.getOwnPropertyNames(o) let shouldStrip = false const r: any = {} for (let i = 0; i < keys.length; i++) { const key = keys[i] if (!hasOwnProperty.call(props, key)) { shouldStrip = true } else { r[key] = o[key] } } return shouldStrip ? r : o } function getExactTypeName(codec: Any): string { if (isTypeC(codec)) { return `{| ${getNameFromProps(codec.props)} |}` } else if (isPartialC(codec)) { return getPartialTypeName(`{| ${getNameFromProps(codec.props)} |}`) } return `Exact<${codec.name}>` } interface NonEmptyArray<A> extends Array<A> { 0: A } function isNonEmpty<A>(as: Array<A>): as is NonEmptyArray<A> { return as.length > 0 } interface Tags extends Record<string, NonEmptyArray<LiteralValue>> {} /** * @internal */ export const emptyTags: Tags = {} function intersect(a: NonEmptyArray<LiteralValue>, b: NonEmptyArray<LiteralValue>): Array<LiteralValue> { const r: Array<LiteralValue> = [] for (const v of a) { if (b.indexOf(v) !== -1) { r.push(v) } } return r } function mergeTags(a: Tags, b: Tags): Tags { if (a === emptyTags) { return b } if (b === emptyTags) { return a } let r: Tags = Object.assign({}, a) for (const k in b) { if (a.hasOwnProperty(k)) { const intersection = intersect(a[k], b[k]) if (isNonEmpty(intersection)) { r[k] = intersection } else { r = emptyTags break } } else { r[k] = b[k] } } return r } function intersectTags(a: Tags, b: Tags): Tags { if (a === emptyTags || b === emptyTags) { return emptyTags } let r: Tags = emptyTags for (const k in a) { if (b.hasOwnProperty(k)) { const intersection = intersect(a[k], b[k]) if (intersection.length === 0) { if (r === emptyTags) { r = {} } r[k] = a[k].concat(b[k]) as any } } } return r } // tslint:disable-next-line: deprecation function isAnyC(codec: Any): codec is AnyC { return (codec as any)._tag === 'AnyType' } function isLiteralC(codec: Any): codec is LiteralC<LiteralValue> { return (codec as any)._tag === 'LiteralType' } function isKeyofC(codec: Any): codec is KeyofC<Record<string, unknown>> { return (codec as any)._tag === 'KeyofType' } function isTypeC(codec: Any): codec is TypeC<Props> { return (codec as any)._tag === 'InterfaceType' } function isPartialC(codec: Any): codec is PartialC<Props> { return (codec as any)._tag === 'PartialType' } // tslint:disable-next-line: deprecation function isStrictC(codec: Any): codec is StrictC<Props> { return (codec as any)._tag === 'StrictType' } function isExactC(codec: Any): codec is ExactC<HasProps> { return (codec as any)._tag === 'ExactType' } // tslint:disable-next-line: deprecation function isRefinementC(codec: Any): codec is RefinementC<Any> { return (codec as any)._tag === 'RefinementType' } function isIntersectionC(codec: Any): codec is IntersectionC<[Mixed, Mixed, ...Array<Mixed>]> { return (codec as any)._tag === 'IntersectionType' } function isUnionC(codec: Any): codec is UnionC<[Mixed, Mixed, ...Array<Mixed>]> { return (codec as any)._tag === 'UnionType' } function isRecursiveC(codec: Any): codec is RecursiveType<Any> { return (codec as any)._tag === 'RecursiveType' } const lazyCodecs: Array<Any> = [] /** * @internal */ export function getTags(codec: Any): Tags { if (lazyCodecs.indexOf(codec) !== -1) { return emptyTags } if (isTypeC(codec) || isStrictC(codec)) { let index: Tags = emptyTags // tslint:disable-next-line: forin for (const k in codec.props) { const prop = codec.props[k] if (isLiteralC(prop)) { if (index === emptyTags) { index = {} } index[k] = [prop.value] } } return index } else if (isExactC(codec) || isRefinementC(codec)) { return getTags(codec.type) } else if (isIntersectionC(codec)) { return codec.types.reduce((tags, codec) => mergeTags(tags, getTags(codec)), emptyTags) } else if (isUnionC(codec)) { return codec.types.slice(1).reduce((tags, codec) => intersectTags(tags, getTags(codec)), getTags(codec.types[0])) } else if (isRecursiveC(codec)) { lazyCodecs.push(codec) const tags = getTags(codec.type) lazyCodecs.pop() return tags } return emptyTags } /** * @internal */ export function getIndex(codecs: NonEmptyArray<Any>): [string, NonEmptyArray<NonEmptyArray<LiteralValue>>] | undefined { const tags = getTags(codecs[0]) const keys = Object.keys(tags) const len = codecs.length keys: for (const k of keys) { const all = tags[k].slice() const index: NonEmptyArray<NonEmptyArray<LiteralValue>> = [tags[k]] for (let i = 1; i < len; i++) { const codec = codecs[i] const ctags = getTags(codec) const values = ctags[k] // tslint:disable-next-line: strict-type-predicates if (values === undefined) { continue keys } else { if (values.some((v) => all.indexOf(v) !== -1)) { continue keys } else { all.push(...values) index.push(values) } } } return [k, index] } return undefined } // ------------------------------------------------------------------------------------- // primitives // ------------------------------------------------------------------------------------- /** * @since 1.0.0 */ export class NullType extends Type<null> { /** * @since 1.0.0 */ readonly _tag: 'NullType' = 'NullType' constructor() { super( 'null', (u): u is null => u === null, (u, c) => (this.is(u) ? success(u) : failure(u, c)), identity ) } } /** * @since 1.5.3 */ export interface NullC extends NullType {} /** * @category primitives * @since 1.0.0 */ export const nullType: NullC = new NullType() /** * @since 1.0.0 */ export class UndefinedType extends Type<undefined> { /** * @since 1.0.0 */ readonly _tag: 'UndefinedType' = 'UndefinedType' constructor() { super( 'undefined', (u): u is undefined => u === void 0, (u, c) => (this.is(u) ? success(u) : failure(u, c)), identity ) } } /** * @since 1.5.3 */ export interface UndefinedC extends UndefinedType {} const undefinedType: UndefinedC = new UndefinedType() /** * @since 1.2.0 */ export class VoidType extends Type<void> { /** * @since 1.0.0 */ readonly _tag: 'VoidType' = 'VoidType' constructor() { super('void', undefinedType.is, undefinedType.validate, identity) } } /** * @since 1.5.3 */ export interface VoidC extends VoidType {} /** * @category primitives * @since 1.2.0 */ export const voidType: VoidC = new VoidType() /** * @since 1.5.0 */ export class UnknownType extends Type<unknown> { /** * @since 1.0.0 */ readonly _tag: 'UnknownType' = 'UnknownType' constructor() { super('unknown', (_): _ is unknown => true, success, identity) } } /** * @since 1.5.3 */ export interface UnknownC extends UnknownType {} /** * @category primitives * @since 1.5.0 */ export const unknown: UnknownC = new UnknownType() /** * @since 1.0.0 */ export class StringType extends Type<string> { /** * @since 1.0.0 */ readonly _tag: 'StringType' = 'StringType' constructor() { super( 'string', (u): u is string => typeof u === 'string', (u, c) => (this.is(u) ? success(u) : failure(u, c)), identity ) } } /** * @since 1.5.3 */ export interface StringC extends StringType {} /** * @category primitives * @since 1.0.0 */ export const string: StringC = new StringType() /** * @since 1.0.0 */ export class NumberType extends Type<number> { /** * @since 1.0.0 */ readonly _tag: 'NumberType' = 'NumberType' constructor() { super( 'number', (u): u is number => typeof u === 'number', (u, c) => (this.is(u) ? success(u) : failure(u, c)), identity ) } } /** * @since 1.5.3 */ export interface NumberC extends NumberType {} /** * @category primitives * @since 1.0.0 */ export const number: NumberC = new NumberType() /** * @since 2.1.0 */ export class BigIntType extends Type<bigint> { /** * @since 1.0.0 */ readonly _tag: 'BigIntType' = 'BigIntType' constructor() { super( 'bigint', // tslint:disable-next-line: valid-typeof (u): u is bigint => typeof u === 'bigint', (u, c) => (this.is(u) ? success(u) : failure(u, c)), identity ) } } /** * @since 2.1.0 */ export interface BigIntC extends BigIntType {} /** * @category primitives * @since 2.1.0 */ export const bigint: BigIntC = new BigIntType() /** * @since 1.0.0 */ export class BooleanType extends Type<boolean> { /** * @since 1.0.0 */ readonly _tag: 'BooleanType' = 'BooleanType' constructor() { super( 'boolean', (u): u is boolean => typeof u === 'boolean', (u, c) => (this.is(u) ? success(u) : failure(u, c)), identity ) } } /** * @since 1.5.3 */ export interface BooleanC extends BooleanType {} /** * @category primitives * @since 1.0.0 */ export const boolean: BooleanC = new BooleanType() /** * @since 1.0.0 */ export class AnyArrayType extends Type<Array<unknown>> { /** * @since 1.0.0 */ readonly _tag: 'AnyArrayType' = 'AnyArrayType' constructor() { super('UnknownArray', Array.isArray, (u, c) => (this.is(u) ? success(u) : failure(u, c)), identity) } } /** * @since 1.5.3 */ export interface UnknownArrayC extends AnyArrayType {} /** * @category primitives * @since 1.7.1 */ export const UnknownArray: UnknownArrayC = new AnyArrayType() /** * @since 1.0.0 */ export class AnyDictionaryType extends Type<{ [key: string]: unknown }> { /** * @since 1.0.0 */ readonly _tag: 'AnyDictionaryType' = 'AnyDictionaryType' constructor() { super( 'UnknownRecord', (u): u is { [key: string]: unknown } => { const s = Object.prototype.toString.call(u) return s === '[object Object]' || s === '[object Window]' }, (u, c) => (this.is(u) ? success(u) : failure(u, c)), identity ) } } /** * @since 1.5.3 */ export interface UnknownRecordC extends AnyDictionaryType {} /** * @category primitives * @since 1.7.1 */ export const UnknownRecord: UnknownRecordC = new AnyDictionaryType() export { /** * @category primitives * @since 1.0.0 */ nullType as null, /** * @category primitives * @since 1.0.0 */ undefinedType as undefined, /** * @category primitives * @since 1.0.0 */ voidType as void } // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- type LiteralValue = string | number | boolean /** * @since 1.0.0 */ export class LiteralType<V extends LiteralValue> extends Type<V> { /** * @since 1.0.0 */ readonly _tag: 'LiteralType' = 'LiteralType' constructor( name: string, is: LiteralType<V>['is'], validate: LiteralType<V>['validate'], encode: LiteralType<V>['encode'], readonly value: V ) { super(name, is, validate, encode) } } /** * @since 1.5.3 */ export interface LiteralC<V extends LiteralValue> extends LiteralType<V> {} /** * @category constructors * @since 1.0.0 */ export function literal<V extends LiteralValue>(value: V, name: string = JSON.stringify(value)): LiteralC<V> { const is = (u: unknown): u is V => u === value return new LiteralType(name, is, (u, c) => (is(u) ? success(value) : failure(u, c)), identity, value) } /** * @since 1.0.0 */ export class KeyofType<D extends { [key: string]: unknown }> extends Type<keyof D> { /** * @since 1.0.0 */ readonly _tag: 'KeyofType' = 'KeyofType' constructor( name: string, is: KeyofType<D>['is'], validate: KeyofType<D>['validate'], encode: KeyofType<D>['encode'], readonly keys: D ) { super(name, is, validate, encode) } } /** * @since 1.5.3 */ export interface KeyofC<D extends { [key: string]: unknown }> extends KeyofType<D> {} /** * @category constructors * @since 1.0.0 */ export function keyof<D extends { [key: string]: unknown }>( keys: D, name: string = Object.keys(keys) .map((k) => JSON.stringify(k)) .join(' | ') ): KeyofC<D> { const is = (u: unknown): u is keyof D => string.is(u) && hasOwnProperty.call(keys, u) return new KeyofType(name, is, (u, c) => (is(u) ? success(u) : failure(u, c)), identity, keys) } // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * @since 1.0.0 */ export class RefinementType<C extends Any, A = any, O = A, I = unknown> extends Type<A, O, I> { /** * @since 1.0.0 */ readonly _tag: 'RefinementType' = 'RefinementType' constructor( name: string, is: RefinementType<C, A, O, I>['is'], validate: RefinementType<C, A, O, I>['validate'], encode: RefinementType<C, A, O, I>['encode'], readonly type: C, readonly predicate: Predicate<A> ) { super(name, is, validate, encode) } } declare const _brand: unique symbol /** * @since 1.8.1 */ export interface Brand<B> { readonly [_brand]: B } /** * @since 1.8.1 */ export type Branded<A, B> = A & Brand<B> /** * @since 1.8.1 */ export interface BrandC<C extends Any, B> extends RefinementType<C, Branded<TypeOf<C>, B>, OutputOf<C>, InputOf<C>> {} /** * @category combinators * @since 1.8.1 */ export function brand<C extends Any, N extends string, B extends { readonly [K in N]: symbol }>( codec: C, predicate: Refinement<TypeOf<C>, Branded<TypeOf<C>, B>>, name: N ): BrandC<C, B> { // tslint:disable-next-line: deprecation return refinement(codec, predicate, name) } /** * @since 1.8.1 */ export interface IntBrand { readonly Int: unique symbol } /** * A branded codec representing an integer * * @category primitives * @since 1.8.1 */ export const Int = brand(number, (n): n is Branded<number, IntBrand> => Number.isInteger(n), 'Int') /** * @since 1.8.1 */ export type Int = Branded<number, IntBrand> /** * @since 1.0.0 */ export class RecursiveType<C extends Any, A = any, O = A, I = unknown> extends Type<A, O, I> { /** * @since 1.0.0 */ readonly _tag: 'RecursiveType' = 'RecursiveType' constructor( name: string, is: RecursiveType<C, A, O, I>['is'], validate: RecursiveType<C, A, O, I>['validate'], encode: RecursiveType<C, A, O, I>['encode'], public runDefinition: () => C ) { super(name, is, validate, encode) } /** * @since 1.0.0 */ readonly type!: C } Object.defineProperty(RecursiveType.prototype, 'type', { get: function () { return this.runDefinition() }, enumerable: true, configurable: true }) /** * @category combinators * @since 1.0.0 */ export function recursion<A, O = A, I = unknown, C extends Type<A, O, I> = Type<A, O, I>>( name: string, definition: (self: C) => C ): RecursiveType<C, A, O, I> { let cache: C const runDefinition = (): C => { if (!cache) { cache = definition(Self) ;(cache as any).name = name } return cache } const Self: any = new RecursiveType<C, A, O, I>( name, (u): u is A => runDefinition().is(u), (u, c) => runDefinition().validate(u, c), (a) => runDefinition().encode(a), runDefinition ) return Self } /** * @since 1.0.0 */ export class ArrayType<C extends Any, A = any, O = A, I = unknown> extends Type<A, O, I> { /** * @since 1.0.0 */ readonly _tag: 'ArrayType' = 'ArrayType' constructor( name: string, is: ArrayType<C, A, O, I>['is'], validate: ArrayType<C, A, O, I>['validate'], encode: ArrayType<C, A, O, I>['encode'], readonly type: C ) { super(name, is, validate, encode) } } /** * @since 1.5.3 */ export interface ArrayC<C extends Mixed> extends ArrayType<C, Array<TypeOf<C>>, Array<OutputOf<C>>, unknown> {} /** * @category combinators * @since 1.0.0 */ export function array<C extends Mixed>(item: C, name: string = `Array<${item.name}>`): ArrayC<C> { return new ArrayType( name, (u): u is Array<TypeOf<C>> => UnknownArray.is(u) && u.every(item.is), (u, c) => { const e = UnknownArray.validate(u, c) if (isLeft(e)) { return e } const us = e.right const len = us.length let as: Array<TypeOf<C>> = us const errors: Errors = [] for (let i = 0; i < len; i++) { const ui = us[i] const result = item.validate(ui, appendContext(c, String(i), item, ui)) if (isLeft(result)) { pushAll(errors, result.left) } else { const ai = result.right if (ai !== ui) { if (as === us) { as = us.slice() } as[i] = ai } } } return errors.length > 0 ? failures(errors) : success(as) }, item.encode === identity ? identity : (a) => a.map(item.encode), item ) } /** * @since 1.0.0 */ export class InterfaceType<P, A = any, O = A, I = unknown> extends Type<A, O, I> { /** * @since 1.0.0 */ readonly _tag: 'InterfaceType' = 'InterfaceType' constructor( name: string, is: InterfaceType<P, A, O, I>['is'], validate: InterfaceType<P, A, O, I>['validate'], encode: InterfaceType<P, A, O, I>['encode'], readonly props: P ) { super(name, is, validate, encode) } } /** * @since 1.5.3 */ export interface TypeC<P extends Props> extends InterfaceType<P, { [K in keyof P]: TypeOf<P[K]> }, { [K in keyof P]: OutputOf<P[K]> }, unknown> {} /** * @category combinators * @since 1.0.0 */ export function type<P extends Props>(props: P, name: string = getInterfaceTypeName(props)): TypeC<P> { const keys = Object.keys(props) const types = keys.map((key) => props[key]) const len = keys.length return new InterfaceType( name, (u): u is { [K in keyof P]: TypeOf<P[K]> } => { if (UnknownRecord.is(u)) { for (let i = 0; i < len; i++) { const k = keys[i] const uk = u[k] if ((uk === undefined && !hasOwnProperty.call(u, k)) || !types[i].is(uk)) { return false } } return true } return false }, (u, c) => { const e = UnknownRecord.validate(u, c) if (isLeft(e)) { return e } const o = e.right let a = o const errors: Errors = [] for (let i = 0; i < len; i++) { const k = keys[i] const ak = a[k] const type = types[i] const result = type.validate(ak, appendContext(c, k, type, ak)) if (isLeft(result)) { pushAll(errors, result.left) } else { const vak = result.right if (vak !== ak || (vak === undefined && !hasOwnProperty.call(a, k))) { /* istanbul ignore next */ if (a === o) { a = { ...o } } a[k] = vak } } } return errors.length > 0 ? failures(errors) : success(a as any) }, useIdentity(types) ? identity : (a) => { const s: { [x: string]: any } = { ...a } for (let i = 0; i < len; i++) { const k = keys[i] const encode = types[i].encode if (encode !== identity) { s[k] = encode(a[k]) } } return s as any }, props ) } /** * @since 1.0.0 */ export class PartialType<P, A = any, O = A, I = unknown> extends Type<A, O, I> { /** * @since 1.0.0 */ readonly _tag: 'PartialType' = 'PartialType' constructor( name: string, is: PartialType<P, A, O, I>['is'], validate: PartialType<P, A, O, I>['validate'], encode: PartialType<P, A, O, I>['encode'], readonly props: P ) { super(name, is, validate, encode) } } /** * @since 1.5.3 */ export interface PartialC<P extends Props> extends PartialType<P, { [K in keyof P]?: TypeOf<P[K]> }, { [K in keyof P]?: OutputOf<P[K]> }, unknown> {} /** * @category combinators * @since 1.0.0 */ export function partial<P extends Props>( props: P, name: string = getPartialTypeName(getInterfaceTypeName(props)) ): PartialC<P> { const keys = Object.keys(props) const types = keys.map((key) => props[key]) const len = keys.length return new PartialType( name, (u): u is { [K in keyof P]?: TypeOf<P[K]> } => { if (UnknownRecord.is(u)) { for (let i = 0; i < len; i++) { const k = keys[i] const uk = u[k] if (uk !== undefined && !props[k].is(uk)) { return false } } return true } return false }, (u, c) => { const e = UnknownRecord.validate(u, c) if (isLeft(e)) { return e } const o = e.right let a = o const errors: Errors = [] for (let i = 0; i < len; i++) { const k = keys[i] const ak = a[k] const type = props[k] const result = type.validate(ak, appendContext(c, k, type, ak)) if (isLeft(result)) { if (ak !== undefined) { pushAll(errors, result.left) } } else { const vak = result.right if (vak !== ak) { /* istanbul ignore next */ if (a === o) { a = { ...o } } a[k] = vak } } } return errors.length > 0 ? failures(errors) : success(a as any) }, useIdentity(types) ? identity : (a) => { const s: { [key: string]: any } = { ...a } for (let i = 0; i < len; i++) { const k = keys[i] const ak = a[k] if (ak !== undefined) { s[k] = types[i].encode(ak) } } return s as any }, props ) } /** * @since 1.0.0 */ export class DictionaryType<D extends Any, C extends Any, A = any, O = A, I = unknown> extends Type<A, O, I> { /** * @since 1.0.0 */ readonly _tag: 'DictionaryType' = 'DictionaryType' constructor( name: string, is: DictionaryType<D, C, A, O, I>['is'], validate: DictionaryType<D, C, A, O, I>['validate'], encode: DictionaryType<D, C, A, O, I>['encode'], readonly domain: D, readonly codomain: C ) { super(name, is, validate, encode) } } /** * @since 1.5.3 */ export interface RecordC<D extends Mixed, C extends Mixed> extends DictionaryType<D, C, { [K in TypeOf<D>]: TypeOf<C> }, { [K in OutputOf<D>]: OutputOf<C> }, unknown> {} /** * @category combinators * @since 1.7.1 */ export function record<D extends Mixed, C extends Mixed>(domain: D, codomain: C, name?: string): RecordC<D, C> { const keys = getDomainKeys(domain) return keys ? enumerableRecord(Object.keys(keys), domain, codomain, name) : nonEnumerableRecord(domain, codomain, name) } /** * @since 1.0.0 */ export class UnionType<CS extends Array<Any>, A = any, O = A, I = unknown> extends Type<A, O, I> { /** * @since 1.0.0 */ readonly _tag: 'UnionType' = 'UnionType' constructor( name: string, is: UnionType<CS, A, O, I>['is'], validate: UnionType<CS, A, O, I>['validate'], encode: UnionType<CS, A, O, I>['encode'], readonly types: CS ) { super(name, is, validate, encode) } } /** * @since 1.5.3 */ export interface UnionC<CS extends [Mixed, Mixed, ...Array<Mixed>]> extends UnionType<CS, TypeOf<CS[number]>, OutputOf<CS[number]>, unknown> {} /** * @category combinators * @since 1.0.0 */ export function union<CS extends [Mixed, Mixed, ...Array<Mixed>]>( codecs: CS, name: string = getUnionName(codecs) ): UnionC<CS> { const index = getIndex(codecs) if (index !== undefined && codecs.length > 0) { const [tag, groups] = index const len = groups.length const find = (value: any): number | undefined => { for (let i = 0; i < len; i++) { if (groups[i].indexOf(value) !== -1) { return i } } return undefined } // tslint:disable-next-line: deprecation return new TaggedUnionType( name, (u): u is TypeOf<CS[number]> => { if (UnknownRecord.is(u)) { const i = find(u[tag]) return i !== undefined ? codecs[i].is(u) : false } return false }, (u, c) => { const e = UnknownRecord.validate(u, c) if (isLeft(e)) { return e } const r = e.right const i = find(r[tag]) if (i === undefined) { return failure(u, c) } const codec = codecs[i] return codec.validate(r, appendContext(c, String(i), codec, r)) }, useIdentity(codecs) ? identity : (a) => { const i = find(a[tag]) if (i === undefined) { // https://github.com/gcanti/io-ts/pull/305 throw new Error(`no codec found to encode value in union codec ${name}`) } else { return codecs[i].encode(a) } }, codecs, tag ) } else { return new UnionType( name, (u): u is TypeOf<CS[number]> => codecs.some((type) => type.is(u)), (u, c) => { const errors: Errors = [] for (let i = 0; i < codecs.length; i++) { const codec = codecs[i] const result = codec.validate(u, appendContext(c, String(i), codec, u)) if (isLeft(result)) { pushAll(errors, result.left) } else { return success(result.right) } } return failures(errors) }, useIdentity(codecs) ? identity : (a) => { for (const codec of codecs) { if (codec.is(a)) { return codec.encode(a) } } // https://github.com/gcanti/io-ts/pull/305 throw new Error(`no codec found to encode value in union type ${name}`) }, codecs ) } } /** * @since 1.0.0 */ export class IntersectionType<CS extends Array<Any>, A = any, O = A, I = unknown> extends Type<A, O, I> { /** * @since 1.0.0 */ readonly _tag: 'IntersectionType' = 'IntersectionType' constructor( name: string, is: IntersectionType<CS, A, O, I>['is'], validate: IntersectionType<CS, A, O, I>['validate'], encode: IntersectionType<CS, A, O, I>['encode'], readonly types: CS ) { super(name, is, validate, encode) } } /** * @since 1.5.3 */ export interface IntersectionC<CS extends [Mixed, Mixed, ...Array<Mixed>]> extends IntersectionType< CS, CS extends { length: 2 } ? TypeOf<CS[0]> & TypeOf<CS[1]> : CS extends { length: 3 } ? TypeOf<CS[0]> & TypeOf<CS[1]> & TypeOf<CS[2]> : CS extends { length: 4 } ? TypeOf<CS[0]> & TypeOf<CS[1]> & TypeOf<CS[2]> & TypeOf<CS[3]> : CS extends { length: 5 } ? TypeOf<CS[0]> & TypeOf<CS[1]> & TypeOf<CS[2]> & TypeOf<CS[3]> & TypeOf<CS[4]> : unknown, CS extends { length: 2 } ? OutputOf<CS[0]> & OutputOf<CS[1]> : CS extends { length: 3 } ? OutputOf<CS[0]> & OutputOf<CS[1]> & OutputOf<CS[2]> : CS extends { length: 4 } ? OutputOf<CS[0]> & OutputOf<CS[1]> & OutputOf<CS[2]> & OutputOf<CS[3]> : CS extends { length: 5 } ? OutputOf<CS[0]> & OutputOf<CS[1]> & OutputOf<CS[2]> & OutputOf<CS[3]> & OutputOf<CS[4]> : unknown, unknown > {} /** * @category combinators * @since 1.0.0 */ export function intersection<A extends Mixed, B extends Mixed, C extends Mixed, D extends Mixed, E extends Mixed>( codecs: [A, B, C, D, E], name?: string ): IntersectionC<[A, B, C, D, E]> export function intersection<A extends Mixed, B extends Mixed, C extends Mixed, D extends Mixed>( codecs: [A, B, C, D], name?: string ): IntersectionC<[A, B, C, D]> export function intersection<A extends Mixed, B extends Mixed, C extends Mixed>( codecs: [A, B, C], name?: string ): IntersectionC<[A, B, C]> export function intersection<A extends Mixed, B extends Mixed>(codecs: [A, B], name?: string): IntersectionC<[A, B]> export function intersection<CS extends [Mixed, Mixed, ...Array<Mixed>]>( codecs: CS, name: string = `(${codecs.map((type) => type.name).join(' & ')})` ): IntersectionC<CS> { const len = codecs.length return new IntersectionType( name, (u: unknown): u is any => codecs.every((type) => type.is(u)), codecs.length === 0 ? success : (u, c) => { const us: Array<unknown> = [] const errors: Errors = [] for (let i = 0; i < len; i++) { const codec = codecs[i] const result = codec.validate(u, appendContext(c, String(i), codec, u)) if (isLeft(result)) { pushAll(errors, result.left) } else { us.push(result.right) } } return errors.length > 0 ? failures(errors) : success(mergeAll(u, us)) }, codecs.length === 0 ? identity : (a) => mergeAll( a, codecs.map((codec) => codec.encode(a)) ), codecs ) } /** * @since 1.0.0 */ export class TupleType<CS extends Array<Any>, A = any, O = A, I = unknown> extends Type<A, O, I> { /** * @since 1.0.0 */ readonly _tag: 'TupleType' = 'TupleType' constructor( name: string, is: TupleType<CS, A, O, I>['is'], validate: TupleType<CS, A, O, I>['validate'], encode: TupleType<CS, A, O, I>['encode'], readonly types: CS ) { super(name, is, validate, encode) } } /** * @since 1.5.3 */ export interface TupleC<CS extends [Mixed, ...Array<Mixed>]> extends TupleType< CS, CS extends { length: 1 } ? [TypeOf<CS[0]>] : CS extends { length: 2 } ? [TypeOf<CS[0]>, TypeOf<CS[1]>] : CS extends { length: 3 } ? [TypeOf<CS[0]>, TypeOf<CS[1]>, TypeOf<CS[2]>] : CS extends { length: 4 } ? [TypeOf<CS[0]>, TypeOf<CS[1]>, TypeOf<CS[2]>, TypeOf<CS[3]>] : CS extends { length: 5 } ? [TypeOf<CS[0]>, TypeOf<CS[1]>, TypeOf<CS[2]>, TypeOf<CS[3]>, TypeOf<CS[4]>] : unknown, CS extends { length: 1 } ? [OutputOf<CS[0]>] : CS extends { length: 2 } ? [OutputOf<CS[0]>, OutputOf<CS[1]>] : CS extends { length: 3 } ? [OutputOf<CS[0]>, OutputOf<CS[1]>, OutputOf<CS[2]>] : CS extends { length: 4 } ? [OutputOf<CS[0]>, OutputOf<CS[1]>, OutputOf<CS[2]>, OutputOf<CS[3]>] : CS extends { length: 5 } ? [OutputOf<CS[0]>, OutputOf<CS[1]>, OutputOf<CS[2]>, OutputOf<CS[3]>, OutputOf<CS[4]>] : unknown, unknown > {} /** * @category combinators * @since 1.0.0 */ export function tuple<A extends Mixed, B extends Mixed, C extends Mixed, D extends Mixed, E extends Mixed>( codecs: [A, B, C, D, E], name?: string ): TupleC<[A, B, C, D, E]> export function tuple<A extends Mixed, B extends Mixed, C extends Mixed, D extends Mixed>( codecs: [A, B, C, D], name?: string ): TupleC<[A, B, C, D]> export function tuple<A extends Mixed, B extends Mixed, C extends Mixed>( codecs: [A, B, C], name?: string ): TupleC<[A, B, C]> export function tuple<A extends Mixed, B extends Mixed>(codecs: [A, B], name?: string): TupleC<[A, B]> export function tuple<A extends Mixed>(codecs: [A], name?: string): TupleC<[A]> export function tuple<CS extends [Mixed, ...Array<Mixed>]>( codecs: CS, name: string = `[${codecs.map((type) => type.name).join(', ')}]` ): TupleC<CS> { const len = codecs.length return new TupleType( name, (u): u is any => UnknownArray.is(u) && u.length === len && codecs.every((type, i) => type.is(u[i])), (u, c) => { const e = UnknownArray.validate(u, c) if (isLeft(e)) { return e } const us = e.right let as: Array<any> = us.length > len ? us.slice(0, len) : us // strip additional components const errors: Errors = [] for (let i = 0; i < len; i++) { const a = us[i] const type = codecs[i] const result = type.validate(a, appendContext(c, String(i), type, a)) if (isLeft(result)) { pushAll(errors, result.left) } else { const va = result.right if (va !== a) { /* istanbul ignore next */ if (as === us) { as = us.slice() } as[i] = va } } } return errors.length > 0 ? failures(errors) : success(as) }, useIdentity(codecs) ? identity : (a) => codecs.map((type, i) => type.encode(a[i])), codecs ) } /** * @since 1.0.0 */ export class ReadonlyType<C extends Any, A = any, O = A, I = unknown> extends Type<A, O, I> { /** * @since 1.0.0 */ readonly _tag: 'ReadonlyType' = 'ReadonlyType' constructor( name: string, is: ReadonlyType<C, A, O, I>['is'], validate: ReadonlyType<C, A, O, I>['validate'], encode: ReadonlyType<C, A, O, I>['encode'], readonly type: C ) { super(name, is, validate, encode) } } /** * @since 1.5.3 */ export interface ReadonlyC<C extends Mixed> extends ReadonlyType<C, Readonly<TypeOf<C>>, Readonly<OutputOf<C>>, unknown> {} /** * @category combinators * @since 1.0.0 */ export function readonly<C extends Mixed>(codec: C, name: string = `Readonly<${codec.name}>`): ReadonlyC<C> { return new ReadonlyType(name, codec.is, codec.validate, codec.encode, codec) } /** * @since 1.0.0 */ export class ReadonlyArrayType<C extends Any, A = any, O = A, I = unknown> extends Type<A, O, I> { /** * @since 1.0.0 */ readonly _tag: 'ReadonlyArrayType' = 'ReadonlyArrayType' constructor( name: string, is: ReadonlyArrayType<C, A, O, I>['is'], validate: ReadonlyArrayType<C, A, O, I>['validate'], encode: ReadonlyArrayType<C, A, O, I>['encode'], readonly type: C ) { super(name, is, validate, encode) } } /** * @since 1.5.3 */ export interface ReadonlyArrayC<C extends Mixed> extends ReadonlyArrayType<C, ReadonlyArray<TypeOf<C>>, ReadonlyArray<OutputOf<C>>, unknown> {} /** * @category combinators * @since 1.0.0 */ export function readonlyArray<C extends Mixed>( item: C, name: string = `ReadonlyArray<${item.name}>` ): ReadonlyArrayC<C> { const codec = array(item) return new ReadonlyArrayType(name, codec.is, codec.validate, codec.encode, item) as any } /** * Strips additional properties, equivalent to `exact(type(props))`. * * @category combinators * @since 1.0.0 */ export const strict = <P extends Props>(props: P, name?: string): ExactC<TypeC<P>> => exact(type(props), name) /** * @since 1.1.0 */ export class ExactType<C extends Any, A = any, O = A, I = unknown> extends Type<A, O, I> { /** * @since 1.0.0 */ readonly _tag: 'ExactType' = 'ExactType' constructor( name: string, is: ExactType<C, A, O, I>['is'], validate: ExactType<C, A, O, I>['validate'], encode: ExactType<C, A, O, I>['encode'], readonly type: C ) { super(name, is, validate, encode) } } /** * @since 1.5.3 */ export interface ExactC<C extends HasProps> extends ExactType<C, TypeOf<C>, OutputOf<C>, InputOf<C>> {} /** * Strips additional properties. * * @category combinators * @since 1.1.0 */ export function exact<C extends HasProps>(codec: C, name: string = getExactTypeName(codec)): ExactC<C> { const props: Props = getProps(codec) return new ExactType( name, codec.is, (u, c) => { const e = UnknownRecord.validate(u, c) if (isLeft(e)) { return e } const ce = codec.validate(u, c) if (isLeft(ce)) { return ce } return right(stripKeys(ce.right, props)) }, (a) => codec.encode(stripKeys(a, props)), codec ) } // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * @since 1.0.0 * @deprecated */ export class FunctionType extends Type<Function> { /** * @since 1.0.0 */ readonly _tag: 'FunctionType' = 'FunctionType' constructor() { super( 'Function', // tslint:disable-next-line:strict-type-predicates (u): u is Function => typeof u === 'function', (u, c) => (this.is(u) ? success(u) : failure(u, c)), identity ) } } /** * @since 1.5.3 * @deprecated */ // tslint:disable-next-line: deprecation export interface FunctionC extends FunctionType {} /** * @category primitives * @since 1.0.0 * @deprecated */ // tslint:disable-next-line: deprecation export const Function: FunctionC = new FunctionType() /** * @since 1.3.0 * @deprecated */ export class TaggedUnionType< Tag extends string, CS extends Array<Mixed>, A = any, O = A, I = unknown > extends UnionType<CS, A, O, I> { constructor( name: string, // tslint:disable-next-line: deprecation is: TaggedUnionType<Tag, CS, A, O, I>['is'], // tslint:disable-next-line: deprecation validate: TaggedUnionType<Tag, CS, A, O, I>['validate'], // tslint:disable-next-line: deprecation encode: TaggedUnionType<Tag, CS, A, O, I>['encode'], codecs: CS, readonly tag: Tag ) { super(name, is, validate, encode, codecs) /* istanbul ignore next */ // <= workaround for https://github.com/Microsoft/TypeScript/issues/13455 } } /** * @since 1.5.3 * @deprecated */ export interface TaggedUnionC<Tag extends string, CS extends [Mixed, Mixed, ...Array<Mixed>]> // tslint:disable-next-line: deprecation extends TaggedUnionType<Tag, CS, TypeOf<CS[number]>, OutputOf<CS[number]>, unknown> {} /** * Use `union` instead. * * @category combinators * @since 1.3.0 * @deprecated */ export const taggedUnion = <Tag extends string, CS extends [Mixed, Mixed, ...Array<Mixed>]>( tag: Tag, codecs: CS, name: string = getUnionName(codecs) // tslint:disable-next-line: deprecation ): TaggedUnionC<Tag, CS> => { const U = union(codecs, name) // tslint:disable-next-line: deprecation if (U instanceof TaggedUnionType) { return U } else { console.warn(`[io-ts] Cannot build a tagged union for ${name}, returning a de-optimized union`) // tslint:disable-next-line: deprecation return new TaggedUnionType(name, U.is, U.validate, U.encode, codecs, tag) } } export { /** * Use `UnknownArray` instead. * * @category primitives * @deprecated * @since 1.0.0 */ UnknownArray as Array } export { /** * Use `type` instead. * * @category combinators * @deprecated * @since 1.0.0 */ type as interface } /** * Use `unknown` instead. * * @since 1.0.0 * @deprecated */ export type mixed = unknown /** * @since 1.0.0 * @deprecated */ export const getValidationError /* istanbul ignore next */ = (value: unknown, context: Context): ValidationError => ({ value, context }) /** * @since 1.0.0 * @deprecated */ export const getDefaultContext /* istanbul ignore next */ = (decoder: Decoder<any, any>): Context => [ { key: '', type: decoder } ] /** * @since 1.0.0 * @deprecated */ export class NeverType extends Type<never> { /** * @since 1.0.0 */ readonly _tag: 'NeverType' = 'NeverType' constructor() { super( 'never', (_): _ is never => false, (u, c) => failure(u, c), /* istanbul ignore next */ () => { throw new Error('cannot encode never') } ) } } /** * @since 1.5.3 * @deprecated */ // tslint:disable-next-line: deprecation export interface NeverC extends NeverType {} /** * @category primitives * @since 1.0.0 * @deprecated */ // tslint:disable-next-line: deprecation export const never: NeverC = new NeverType() /** * @since 1.0.0 * @deprecated */ export class AnyType extends Type<any> { /** * @since 1.0.0 */ readonly _tag: 'AnyType' = 'AnyType' constructor() { super('any', (_): _ is any => true, success, identity) } } /** * @since 1.5.3 * @deprecated */ // tslint:disable-next-line: deprecation export interface AnyC extends AnyType {} /** * Use `unknown` instead. * * @category primitives * @since 1.0.0 * @deprecated */ // tslint:disable-next-line: deprecation export const any: AnyC = new AnyType() /** * Use `UnknownRecord` instead. * * @category primitives * @since 1.0.0 * @deprecated */ export const Dictionary: UnknownRecordC = UnknownRecord /** * @since 1.0.0 * @deprecated */ export class ObjectType extends Type<object> { /** * @since 1.0.0 */ readonly _tag: 'ObjectType' = 'ObjectType' constructor() { super( 'object', (u): u is { [key: string]: unknown } => u !== null && typeof u === 'object', (u, c) => (this.is(u) ? success(u) : failure(u, c)), identity ) } } /** * @since 1.5.3 * @deprecated */ // tslint:disable-next-line: deprecation export interface ObjectC extends ObjectType {} /** * Use `UnknownRecord` instead. * * @category primitives * @since 1.0.0 * @deprecated */ // tslint:disable-next-line: deprecation export const object: ObjectC = new ObjectType() /** * Use `BrandC` instead. * * @since 1.5.3 * @deprecated */ export interface RefinementC<C extends Any> extends RefinementType<C, TypeOf<C>, OutputOf<C>, InputOf<C>> {} /** * Use `brand` instead. * * @category combinators * @since 1.0.0 * @deprecated */ export function refinement<C extends Any>( codec: C, predicate: Predicate<TypeOf<C>>, name: string = `(${codec.name} | ${getFunctionName(predicate)})` ): // tslint:disable-next-line: deprecation RefinementC<C> { return new RefinementType( name, (u): u is TypeOf<C> => codec.is(u) && predicate(u), (i, c) => { const e = codec.validate(i, c) if (isLeft(e)) { return e } const a = e.right return predicate(a) ? success(a) : failure(a, c) }, codec.encode, codec, predicate ) } /** * Use `Int` instead. * * @category primitives * @since 1.0.0 * @deprecated */ // tslint:disable-next-line: deprecation export const Integer = refinement(number, Number.isInteger, 'Integer') /** * Use `record` instead. * * @category combinators * @since 1.0.0 * @deprecated */ export const dictionary: typeof record = record /** * @since 1.4.2 * @deprecated */ export type Compact<A> = { [K in keyof A]: A[K] } /** * @since 1.0.0 * @deprecated */ export class StrictType<P, A = any, O = A, I = unknown> extends Type<A, O, I> { /** * @since 1.0.0 */ readonly _tag: 'StrictType' = 'StrictType' constructor( name: string, // tslint:disable-next-line: deprecation is: StrictType<P, A, O, I>['is'], // tslint:disable-next-line: deprecation validate: StrictType<P, A, O, I>['validate'], // tslint:disable-next-line: deprecation encode: StrictType<P, A, O, I>['encode'], readonly props: P ) { super(name, is, validate, encode) } } /** * @since 1.5.3 * @deprecated */ export interface StrictC<P extends Props> // tslint:disable-next-line: deprecation extends StrictType<P, { [K in keyof P]: TypeOf<P[K]> }, { [K in keyof P]: OutputOf<P[K]> }, unknown> {} /** * @since 1.3.0 * @deprecated */ export type TaggedProps<Tag extends string> = { [K in Tag]: LiteralType<any> } /** * @since 1.3.0 * @deprecated */ // tslint:disable-next-line: deprecation export interface TaggedRefinement<Tag extends string, A, O = A> extends RefinementType<Tagged<Tag>, A, O> {} /** * @since 1.3.0 * @deprecated */ // tslint:disable-next-line: deprecation export interface TaggedUnion<Tag extends string, A, O = A> extends UnionType<Array<Tagged<Tag>>, A, O> {} /** * @since 1.3.0 * @deprecated */ export type TaggedIntersectionArgument<Tag extends string> = // tslint:disable-next-line: deprecation | [Tagged<Tag>] // tslint:disable-next-line: deprecation | [Tagged<Tag>, Mixed] // tslint:disable-next-line: deprecation | [Mixed, Tagged<Tag>] // tslint:disable-next-line: deprecation | [Tagged<Tag>, Mixed, Mixed] // tslint:disable-next-line: deprecation | [Mixed, Tagged<Tag>, Mixed] // tslint:disable-next-line: deprecation | [Mixed, Mixed, Tagged<Tag>] // tslint:disable-next-line: deprecation | [Tagged<Tag>, Mixed, Mixed, Mixed] // tslint:disable-next-line: deprecation | [Mixed, Tagged<Tag>, Mixed, Mixed] // tslint:disable-next-line: deprecation | [Mixed, Mixed, Tagged<Tag>, Mixed] // tslint:disable-next-line: deprecation | [Mixed, Mixed, Mixed, Tagged<Tag>] // tslint:disable-next-line: deprecation | [Tagged<Tag>, Mixed, Mixed, Mixed, Mixed] // tslint:disable-next-line: deprecation | [Mixed, Tagged<Tag>, Mixed, Mixed, Mixed] // tslint:disable-next-line: deprecation | [Mixed, Mixed, Tagged<Tag>, Mixed, Mixed] // tslint:disable-next-line: deprecation | [Mixed, Mixed, Mixed, Tagged<Tag>, Mixed] // tslint:disable-next-line: deprecation | [Mixed, Mixed, Mixed, Mixed, Tagged<Tag>] /** * @since 1.3.0 * @deprecated */ export interface TaggedIntersection<Tag extends string, A, O = A> // tslint:disable-next-line: deprecation extends IntersectionType<TaggedIntersectionArgument<Tag>, A, O> {} /** * @since 1.3.0 * @deprecated */ // tslint:disable-next-line: deprecation export interface TaggedExact<Tag extends string, A, O = A> extends ExactType<Tagged<Tag>, A, O> {} /** * @since 1.3.0 * @deprecated */ export type Tagged<Tag extends string, A = any, O = A> = // tslint:disable-next-line: deprecation | InterfaceType<TaggedProps<Tag>, A, O> // tslint:disable-next-line: deprecation | StrictType<TaggedProps<Tag>, A, O> // tslint:disable-next-line: deprecation | TaggedRefinement<Tag, A, O> // tslint:disable-next-line: deprecation | TaggedUnion<Tag, A, O> // tslint:disable-next-line: deprecation | TaggedIntersection<Tag, A, O> // tslint:disable-next-line: deprecation | TaggedExact<Tag, A, O> | RecursiveType<any, A, O> /** * Drops the codec "kind". * * @category combinators * @since 1.1.0 * @deprecated */ export function clean<A, O = A, I = unknown>(codec: Type<A, O, I>): Type<A, O, I> { return codec as any } /** * @since 1.0.0 * @deprecated */ export type PropsOf<T extends { props: any }> = T['props'] /** * @since 1.1.0 * @deprecated */ export type Exact<T, X extends T> = T & { [K in ({ [K in keyof X]: K } & { [K in keyof T]: never } & { [key: string]: never })[keyof X]]?: never } /** * Keeps the codec "kind". * * @category combinators * @since 1.1.0 * @deprecated */ export function alias<A, O, P, I>( codec: PartialType<P, A, O, I> ): < // tslint:disable-next-line: deprecation AA extends Exact<A, AA>, // tslint:disable-next-line: deprecation OO extends Exact<O, OO> = O, // tslint:disable-next-line: deprecation PP extends Exact<P, PP> = P, II extends I = I >() => PartialType<PP, AA, OO, II> export function alias<A, O, P, I>( // tslint:disable-next-line: deprecation codec: StrictType<P, A, O, I> ): < // tslint:disable-next-line: deprecation AA extends Exact<A, AA>, // tslint:disable-next-line: deprecation OO extends Exact<O, OO> = O, // tslint:disable-next-line: deprecation PP extends Exact<P, PP> = P, II extends I = I >() => // tslint:disable-next-line: deprecation StrictType<PP, AA, OO, II> export function alias<A, O, P, I>( codec: InterfaceType<P, A, O, I> ): < // tslint:disable-next-line: deprecation AA extends Exact<A, AA>, // tslint:disable-next-line: deprecation OO extends Exact<O, OO> = O, // tslint:disable-next-line: deprecation PP extends Exact<P, PP> = P, II extends I = I >() => InterfaceType<PP, AA, OO, II> export function alias<A, O, I>( codec: Type<A, O, I> ): // tslint:disable-next-line: deprecation <AA extends Exact<A, AA>, OO extends Exact<O, OO> = O>() => Type<AA, OO, I> { return () => codec as any }
the_stack
import difference from 'lodash/difference'; import camelCase from 'lodash/camelCase'; import isPlainObject from 'lodash/isPlainObject'; import { TreeNode } from './tree-node'; import { TreeNodeValue, TypeIdMap, TypeTimer, TypeTargetNode, TypeTreeNodeData, TypeTreeStoreOptions, TypeTreeFilter, TypeTreeFilterOptions, TypeRelatedNodesOptions, TypeTreeEventState, } from './types'; // 构建一个树的数据模型 // 基本设计思想:写入时更新,减少读取消耗,以减少未来实现虚拟滚动所需的计算量 // 任何一次数据写入,会触发相应节点的状态更新 export class TreeStore { // 根节点集合 public children: TreeNode[]; // 所有节点集合 public nodes: TreeNode[]; // 所有节点映射 public nodeMap: Map<TreeNodeValue, TreeNode>; // 配置选项 public config: TypeTreeStoreOptions; // 活动节点集合 public activedMap: TypeIdMap; // 数据被更新的节点集合 public updatedMap: TypeIdMap; // 选中节点集合 public checkedMap: TypeIdMap; // 展开节点的集合 public expandedMap: TypeIdMap; // 符合过滤条件的节点的集合 public filterMap: TypeIdMap; // 数据更新计时器 public updateTimer: TypeTimer; // 识别是否需要重排 public shouldReflow: boolean; // 树节点过滤器 public prevFilter: TypeTreeFilter; public constructor(options: TypeTreeStoreOptions) { const config: TypeTreeStoreOptions = { prefix: 't', keys: {}, expandAll: false, expandLevel: 0, expandMutex: false, expandParent: false, activable: false, activeMultiple: false, checkable: false, checkStrictly: false, disabled: false, load: null, lazy: false, valueMode: 'onlyLeaf', filter: null, onLoad: null, onReflow: null, onUpdate: null, allowFoldNodeOnFilter: false, ...options, }; this.config = config; this.nodes = []; this.children = []; this.nodeMap = new Map(); this.activedMap = new Map(); this.expandedMap = new Map(); this.checkedMap = new Map(); this.updatedMap = new Map(); this.filterMap = new Map(); this.prevFilter = null; // 这个计时器确保频繁的 update 事件被归纳为1次完整数据更新后的触发 this.updateTimer = null; // 在子节点增删改查时,将此属性设置为 true,来触发视图更新 this.shouldReflow = false; } // 配置选项 public setConfig(options: TypeTreeStoreOptions) { let hasChanged = false; Object.keys(options).forEach((key) => { const val = options[key]; if (val !== this.config[key]) { hasChanged = true; this.config[key] = val; } }); if (hasChanged) { // 在 td-tree 的 render 方法中调用 setConfig // 这样减少了 watch 属性 // 仅在属性变更后刷新状态 // 这样可以避免触发渲染死循环 this.refreshState(); } } // 获取根孩子节点列表 public getChildren() { return this.children; } // 获取节点对象 public getNode(item: TypeTargetNode): TreeNode { let node = null; if (typeof item === 'string' || typeof item === 'number') { node = this.nodeMap.get(item); } else if (item instanceof TreeNode) { node = this.nodeMap.get(item.value); } return node; } // 获取节点在总节点列表中的位置 public getIndex(node: TreeNode): number { return this.nodes.indexOf(node); } // 获取指定节点的父节点 public getParent(value: TypeTargetNode): TreeNode { let parent = null; const node = this.getNode(value); if (node) { parent = node.getParent(); } return parent; } // 获取指定节点的所有父节点 public getParents(value: TypeTargetNode): TreeNode[] { const node = this.getNode(value); let parents: TreeNode[] = []; if (node) { parents = node.getParents(); } return parents; } // 获取指定节点在其所在 children 中的位置 public getNodeIndex(value: TypeTargetNode): number { const node = this.getNode(value); let index = -1; if (node) { index = node.getIndex(); } return index; } // 获取所有符合条件的节点 public getNodes( item?: TypeTargetNode, options?: TypeTreeFilterOptions, ): TreeNode[] { let nodes: TreeNode[] = []; let val: TreeNodeValue = ''; if (typeof item === 'string' || typeof item === 'number') { val = item; } else if (item instanceof TreeNode) { val = item.value; } if (!val) { nodes = this.nodes.slice(0); } else { const node = this.getNode(val); if (node) { nodes = node.walk(); } } if (options) { const conf: TypeTreeFilterOptions = { filter: null, level: Infinity, ...options, }; if (typeof conf.level === 'number' && conf.level !== Infinity) { nodes = nodes.filter((node) => node.level <= conf.level); } if (typeof conf.filter === 'function') { nodes = nodes.filter((node) => { const nodeModel = node.getModel(); return conf.filter(nodeModel); }); } if (isPlainObject(conf.props)) { nodes = nodes.filter((node) => { const result = Object.keys(conf.props).every((key) => { const propEqual = node[key] === conf.props[key]; return propEqual; }); return result; }); } } return nodes; } // 给树添加节点数据 public append(list: TypeTreeNodeData[]): void { list.forEach((item) => { const node = new TreeNode(this, item); this.children.push(node); }); this.reflow(); } // 重新加载数据 public reload(list: TypeTreeNodeData[]): void { this.expandedMap.clear(); this.checkedMap.clear(); this.activedMap.clear(); this.filterMap.clear(); this.removeAll(); this.append(list); } // 解析节点数据,适配多种节点类型 public parseNodeData( para: TreeNodeValue | TreeNode | TypeTreeNodeData, item: TypeTreeNodeData | TypeTreeNodeData[] | TreeNode, ) { let value: TreeNodeValue = ''; let node = null; let data = null; if (typeof para === 'string' || typeof para === 'number') { value = para; data = item; node = this.getNode(value); } else if (para instanceof TreeNode) { node = para; data = item; } else { data = para; } const spec = { node, data, }; return spec; } /** * 向指定节点追加节点或者数据 * 支持下列使用方式 * item: 节点数据, TreeNode: 节点实例, value: 节点值(ID) * appendNodes(item) * appendNodes(TreeNode) * appendNodes(value, item) * appendNodes(value, TreeNode) * appendNodes(TreeNode, item) * appendNodes(TreeNode, TreeNode) */ public appendNodes( para?: TypeTargetNode | TypeTreeNodeData, item?: TypeTreeNodeData | TreeNode, ): void { const spec = this.parseNodeData(para, item); if (spec.data) { if (!spec.node) { // 在根节点插入 if (spec.data instanceof TreeNode) { spec.data.appendTo(this); } else if (Array.isArray(spec.data)) { this.append(spec.data); } else { this.append([spec.data]); } } else { // 插入到目标节点之下 if (spec.data instanceof TreeNode) { spec.data.appendTo(this, spec.node); } else if (Array.isArray(spec.data)) { spec.node.append(spec.data); } else { spec.node.append([spec.data]); } spec.node.updateRelated(); } } } // 在目标节点之前插入节点 public insertBefore(value: TypeTargetNode, item: TypeTreeNodeData): void { const node = this.getNode(value); if (node) { node.insertBefore(item); } } // 在目标节点之后插入节点 public insertAfter(value: TypeTargetNode, item: TypeTreeNodeData): void { const node = this.getNode(value); if (node) { node.insertAfter(item); } } // 更新树结构 // 清空 nodes 数组,然后遍历所有根节点重新插入 node public refreshNodes(): void { const { children, nodes } = this; nodes.length = 0; children.forEach((node) => { const list = node.walk(); Array.prototype.push.apply(nodes, list); }); } // 更新所有树节点状态 public refreshState(): void { const { nodes } = this; nodes.forEach((node) => { node.update(); node.updateChecked(); }); } // 节点重排 // 应该仅在树节点增删改查时调用 public reflow(node?: TreeNode): void { this.shouldReflow = true; this.updated(node); } // 触发更新事件 // 节点属性变更时调用 public updated(node?: TreeNode): void { if (node?.value) { this.updatedMap.set(node.value, true); } if (this.updateTimer) return; this.updateTimer = +setTimeout(() => { clearTimeout(this.updateTimer); this.updateTimer = null; // 检查节点是否需要回流,重排数组 if (this.shouldReflow) { this.refreshNodes(); this.emit('reflow'); } // 检查节点是否有被过滤,锁定路径节点 // 在此之前要遍历节点生成一个经过排序的节点数组 // 以便于优化锁定检查算法 if (!this.config?.allowFoldNodeOnFilter) this.lockFilterPathNodes(); const updatedList = Array.from(this.updatedMap.keys()); if (updatedList.length > 0) { // 统计需要更新状态的节点,派发更新事件 const updatedNodes = updatedList.map((value) => this.getNode(value)); this.emit('update', { nodes: updatedNodes, map: this.updatedMap, }); } else if (this.shouldReflow) { // 单纯的回流不需要更新节点状态 // 但需要触发更新事件 this.emit('update', { nodes: [], map: this.updatedMap, }); } // 每次回流检查完毕,还原检查状态 this.shouldReflow = false; this.updatedMap.clear(); }); } // 获取激活节点集合 public getActived(map?: TypeIdMap): TreeNodeValue[] { const activedMap = map || this.activedMap; return Array.from(activedMap.keys()); } // 获取指定范围的高亮节点 public getActivedNodes(item?: TypeTargetNode): TreeNode[] { let nodes = this.getNodes(item); nodes = nodes.filter((node) => node.isActived()); return nodes; } // 替换激活态 public replaceActived(list: TreeNodeValue[]): void { this.resetActived(); this.setActived(list); } // 设置激活态 public setActived(actived: TreeNodeValue[]): void { const { activeMultiple } = this.config; const list = actived.slice(0); if (!activeMultiple) { list.length = 1; } list.forEach((val) => { this.activedMap.set(val, true); const node = this.getNode(val); if (node) { node.update(); } }); } // 重置激活态 public resetActived(): void { const actived = this.getActived(); this.activedMap.clear(); const relatedNodes = this.getRelatedNodes(actived); relatedNodes.forEach((node) => { node.update(); }); } // 获取展开节点集合 public getExpanded(map?: TypeIdMap): TreeNodeValue[] { const expandedMap = map || this.expandedMap; return Array.from(expandedMap.keys()); } // 替换展开节点 public replaceExpanded(list: TreeNodeValue[]): void { const expanded = this.getExpanded(); const added = difference(list, expanded); const removed = difference(expanded, list); this.setExpandedDirectly(removed, false); this.updateExpanded(removed); this.setExpanded(added); } // 批量设置展开节点 public setExpanded(list: TreeNodeValue[]): void { this.setExpandedDirectly(list); this.updateExpanded(list); } // 直接设置展开节点数据,不更新节点状态 public setExpandedDirectly(list: TreeNodeValue[], expanded = true): void { list.forEach((val) => { if (expanded) { this.expandedMap.set(val, true); const node = this.getNode(val); if (node) { node.afterExpanded(); } } else { this.expandedMap.delete(val); } }); } // 清除所有展开节点 public resetExpanded(): void { const expanded = this.getExpanded(); this.expandedMap.clear(); this.updateExpanded(expanded); } // 更新展开节点相关节点的状态 public updateExpanded(list: TreeNodeValue[]): void { const relatedNodes = this.getRelatedNodes(list, { withParents: false, }); relatedNodes.forEach((node) => { node.update(); }); } // 获取选中态节点 value 数组 public getChecked(map?: TypeIdMap): TreeNodeValue[] { const { nodes, config } = this; const { valueMode, checkStrictly } = config; const list: TreeNodeValue[] = []; const checkedMap = map || this.checkedMap; nodes.forEach((node) => { if (node.isChecked(checkedMap)) { if (valueMode === 'parentFirst' && !checkStrictly) { if (!node.parent || !node.parent.isChecked(checkedMap)) { list.push(node.value); } } else if (valueMode === 'onlyLeaf' && !checkStrictly) { if (node.isLeaf()) { list.push(node.value); } } else { list.push(node.value); } } }); return list; } // 获取指定节点下的选中节点 public getCheckedNodes(item?: TypeTargetNode): TreeNode[] { let nodes = this.getNodes(item); nodes = nodes.filter((node) => node.isChecked()); return nodes; } // 替换选中态列表 public replaceChecked(list: TreeNodeValue[]): void { this.resetChecked(); this.setChecked(list); } // 批量设置选中态 public setChecked(list: TreeNodeValue[]): void { const { valueMode, checkStrictly, checkable } = this.config; if (!checkable) return; list.forEach((val: TreeNodeValue) => { const node = this.getNode(val); if (node) { if (valueMode === 'parentFirst' && !checkStrictly) { const childrenNodes = node.walk(); childrenNodes.forEach((childNode) => { this.checkedMap.set(childNode.value, true); }); } else { this.checkedMap.set(val, true); node.updateChecked(); } } }); if (!checkStrictly) { const checked = this.getChecked(); const relatedNodes = this.getRelatedNodes(checked); relatedNodes.forEach((node) => { node.updateChecked(); }); } } // 清除所有选中节点 public resetChecked(): void { const checked = this.getChecked(); const relatedNodes = this.getRelatedNodes(checked); this.checkedMap.clear(); relatedNodes.forEach((node) => { node.updateChecked(); }); } // 更新全部节点状态 public updateAll(): void { const nodes = this.getNodes(); nodes.forEach((node) => { node.update(); }); } // 移除指定节点 public remove(value?: TypeTargetNode): void { const node = this.getNode(value); if (node) { node.remove(); } } // 清空所有节点 public removeAll(): void { const nodes = this.getNodes(); nodes.forEach((node) => { node.remove(); }); } // 获取节点状态变化可能影响的周边节点 // 实现最小遍历集合 public getRelatedNodes( list: TreeNodeValue[], options?: TypeRelatedNodesOptions, ): TreeNode[] { const conf = { withParents: true, ...options, }; const map = new Map(); list.forEach((value) => { if (map.get(value)) return; const node = this.getNode(value); if (node) { const parents = node.getParents(); const children = node.walk(); let related = []; if (conf.withParents) { related = parents.concat(children); } else { related = children; } related.forEach((relatedNode) => { map.set(relatedNode.value, relatedNode); }); } }); const relatedNodes = Array.from(map.values()); return relatedNodes; } // 触发绑定的事件 public emit(name: string, state?: TypeTreeEventState): void { const config = this.config || {}; const methodName = camelCase(`on-${name}`); const method = config[methodName]; if (typeof method === 'function') { method(state); } } // 锁定过滤节点的路径节点 // 使得路径节点展开,可见,且不可操作 public lockFilterPathNodes() { const { config } = this; const allNodes = this.getNodes(); // 如果之前有进行过滤,则先解锁所有节点 if (this.prevFilter) { allNodes.forEach((node: TreeNode) => { node.lock(false); }); } // 当前没有过滤器 // 则无需处理锁定节点 if (!config.filter) { return; } this.prevFilter = config.filter; // 构造路径节点map const map = new Map(); // 全部节点要经过排序,才能使用这个算法 // 比起每个过滤节点调用 getParents 方法检查父节点状态 // 算法复杂度 O(N*log(N)) => O(N) allNodes.reverse().forEach((item: TreeNode) => { const node = item; // 被过滤节点父节点固定为展开状态 const parent = node.getParent(); if (node.vmIsRest) { if (parent) { // 被过滤节点的父节点固定为展开状态 parent.expanded = true; } // 被过滤节点固定为展示状态 node.visible = true; } if (node.vmIsRest || map.get(node.value)) { if (parent && !parent.vmIsRest) { map.set(parent.value, true); } } }); // 锁定路径节点展示样式 const filterPathValues = Array.from(map.keys()); filterPathValues.forEach((value: TreeNodeValue) => { const node = this.getNode(value); if (node) { node.lock(true); } }); } } export default TreeStore;
the_stack
import { Grammar } from '../../src/magicbox/Grammar'; import { ExpressionConstant } from '../../src/magicbox/Expression/ExpressionConstant'; import { ExpressionRef } from '../../src/magicbox/Expression/ExpressionRef'; import { ExpressionOptions } from '../../src/magicbox/Expression/ExpressionOptions'; import { ExpressionList } from '../../src/magicbox/Expression/ExpressionList'; import { ExpressionRegExp } from '../../src/magicbox/Expression/ExpressionRegExp'; import { Grammars } from '../../src/magicbox/Grammars/Grammars'; export function GrammarTest() { describe('Grammar Expression Builder build expression of type', () => { it('ExpressionConstant', () => { var exp = Grammar.buildExpression('foo', 'id', null); expect(exp).toEqual(jasmine.any(ExpressionConstant)); }); it('ExpressionRef', () => { var exp = <ExpressionRef>Grammar.buildExpression('[foo]', 'id', null); expect(exp).toEqual(jasmine.any(ExpressionRef)); expect(exp.ref).toBe('foo'); expect(exp.occurrence).toBeNull(); exp = <ExpressionRef>Grammar.buildExpression('[foo?]', 'id', null); expect(exp).toEqual(jasmine.any(ExpressionRef)); expect(exp.ref).toBe('foo'); expect(exp.occurrence).toBe('?'); exp = <ExpressionRef>Grammar.buildExpression('[foo{2}]', 'id', null); expect(exp).toEqual(jasmine.any(ExpressionRef)); expect(exp.ref).toBe('foo'); expect(exp.occurrence).toBe(2); }); it('ExpressionOptions', () => { var exp = <ExpressionOptions>Grammar.buildExpression(['foo', 'bar'], 'id', null); expect(exp).toEqual(jasmine.any(ExpressionOptions)); expect(exp.parts.length).toBe(2); }); it('ExpressionList', () => { // this generate a list because at [ he do not know if it will be a ref start var exp1 = Grammar.buildExpression('foo[bar', 'id', null); expect(exp1).toEqual(jasmine.any(ExpressionList)); var exp2 = Grammar.buildExpression('foo[bar]', 'id', null); expect(exp2).toEqual(jasmine.any(ExpressionList)); }); it('ExpressionRegExp', () => { var exp = Grammar.buildExpression(/foo/, 'id', null); expect(exp).toEqual(jasmine.any(ExpressionRegExp)); }); }); // http://pegjs.org/online /* A = "A" B? B = "B" C C = "C" */ describe('ABC Grammar parse correctly', () => { var FakeGrammar = new Grammar('A', { A: 'A[B?]', B: 'B[C+]', C: 'C' }); var FakeGrammar2 = new Grammar('A', { A: '[B][C*]', B: 'B', C: 'C[B]' }); it('Empty String', () => { var result = FakeGrammar.parse(''); expect(result.isSuccess()).toBeFalsy(); expect(result.getHumanReadableExpect()).toBe('Expected "A" but end of input found.'); }); it('"A"', () => { var result = FakeGrammar.parse('A'); expect(result.isSuccess()).toBeTruthy(); }); it('"AB"', () => { var result = FakeGrammar.parse('AB'); expect(result.isSuccess()).toBeFalsy(); expect(result.getHumanReadableExpect()).toBe('Expected "C" but end of input found.'); }); it('"ABC"', () => { var result = FakeGrammar.parse('ABC'); expect(result.isSuccess()).toBeTruthy(); }); it('"AC"', () => { var result = FakeGrammar.parse('AC'); expect(result.isSuccess()).toBeFalsy(); expect(result.getHumanReadableExpect()).toBe('Expected "B" but "C" found.'); }); it('"ABBC"', () => { var result = FakeGrammar.parse('ABBC'); expect(result.isSuccess()).toBeFalsy(); expect(result.getHumanReadableExpect()).toBe('Expected "C" but "B" found.'); }); it('"BC"', () => { var result = FakeGrammar2.parse('BC'); expect(result.isSuccess()).toBeFalsy(); expect(result.getHumanReadableExpect()).toBe('Expected "B" but end of input found.'); }); it('"BCBB"', () => { var result = FakeGrammar2.parse('BCBB'); expect(result.isSuccess()).toBeFalsy(); expect(result.getHumanReadableExpect()).toBe('Expected end of input or "C" but "B" found.'); expect(result.clean().toString()).toBe('BCBB'); }); }); /* bcbb Expr = Product / Sum / Value Value = SubExpr / Number SubExpr = "(" Expr ")" Number = [0-9]+ Product = Value "*" Value Sum= Value "+" Value */ describe('Math Grammar parse correctly', () => { var FakeGrammar = new Grammar('Expr', { Expr: ['Product', 'Sum', 'Value'], Value: ['SubExpr', 'Number'], SubExpr: '([Expr])', Number: /([1-9][0-9]*|0)(\.[0-9]+)?/, Product: '[Value]*[Value]', Sum: '[Value]+[Value]' }); it('Empty String', () => { var result = FakeGrammar.parse(''); expect(result.isSuccess()).toBeFalsy(); expect(result.getHumanReadableExpect()).toBe('Expected Expr but end of input found.'); }); it('"1"', () => { var result = FakeGrammar.parse('1'); expect(result.isSuccess()).toBeTruthy(); }); it('"1+"', () => { var result = FakeGrammar.parse('1+'); expect(result.isSuccess()).toBeFalsy(); expect(result.getHumanReadableExpect()).toBe('Expected Value but end of input found.'); }); it('"1+2"', () => { var result = FakeGrammar.parse('1+2'); expect(result.isSuccess()).toBeTruthy(); }); it('"1+2+"', () => { var result = FakeGrammar.parse('1+2+'); expect(result.isSuccess()).toBeFalsy(); expect(result.getHumanReadableExpect()).toBe('Expected end of input but "+" found.'); }); it('"1+2+3"', () => { var result = FakeGrammar.parse('1+2+3'); expect(result.isSuccess()).toBeFalsy(); expect(result.getHumanReadableExpect()).toBe('Expected end of input but "+" found.'); }); it('"(1+2)+3"', () => { var result = FakeGrammar.parse('(1+2)+3'); expect(result.isSuccess()).toBeTruthy(); }); }); describe('Coveo Field Grammar parse correctly', () => { var completeExpressions = Grammars.Expressions(Grammars.Complete); var coveoGrammar = new Grammar(completeExpressions.start, completeExpressions.expressions); it('Empty String', () => { var result = coveoGrammar.parse(''); expect(result.isSuccess()).toBeTruthy(); }); it('"@fieldName"', () => { var result = coveoGrammar.parse('@fieldName'); expect(result.isSuccess()).toBeTruthy(); }); it('"@fieldName="', () => { var result = coveoGrammar.parse('@fieldName='); expect(result.isSuccess()).toBeFalsy(); expect(result.getHumanReadableExpect()).toBe('Expected FieldValue but end of input found.'); console.log(result.clean()); }); it('"@fieldName=value"', () => { var result = coveoGrammar.parse('@fieldName=value'); expect(result.isSuccess()).toBeTruthy(); }); it('"@fieldName=(value"', () => { var result = coveoGrammar.parse('@fieldName=(value'); expect(result.isSuccess()).toBeFalsy(); expect(result.getHumanReadableExpect()).toBe('Expected FieldValueSeparator or ")" but end of input found.'); }); it('"@fieldName=(value)"', () => { var result = coveoGrammar.parse('@fieldName=(value)'); expect(result.isSuccess()).toBeTruthy(); }); it('"@fieldName=(value,)"', () => { var result = coveoGrammar.parse('@fieldName=(value,)'); expect(result.isSuccess()).toBeFalsy(); expect(result.getHumanReadableExpect()).toBe('Expected FieldValueString but ")" found.'); }); it('"@fieldName=(value, abc)"', () => { var result = coveoGrammar.parse('@fieldName=(value, abc)'); expect(result.isSuccess()).toBeTruthy(); }); it('"word @fieldName=(value, abc)"', () => { var result = coveoGrammar.parse('word @fieldName=(value, abc)'); expect(result.isSuccess()).toBeTruthy(); }); it('"word @fieldName = (value , abc)"', () => { var result = coveoGrammar.parse('word @fieldName = (value , abc)'); expect(result.isSuccess()).toBeTruthy(); }); it('"@fieldName=value]"', () => { var result = coveoGrammar.parse('@fieldName=value]'); expect(result.isSuccess()).toBeFalsy(); expect(result.getHumanReadableExpect()).toBe('Expected Spaces or end of input but "]" found.'); }); it('"word (word2"', () => { var result = coveoGrammar.parse('word (word2'); expect(result.isSuccess()).toBeFalsy(); expect(result.getHumanReadableExpect()).toBe('Expected ":" or Spaces or ")" but end of input found.'); }); it('"word(word2)"', () => { var result = coveoGrammar.parse('word(word2)'); expect(result.isSuccess()).toBeFalsy(); expect(result.getHumanReadableExpect()).toBe('Expected ":" or Spaces or end of input but "(" found.'); }); it('"word (word2)"', () => { var result = coveoGrammar.parse('word (word2)'); expect(result.isSuccess()).toBeTruthy(); }); it('"word OR (word2)"', () => { var result = coveoGrammar.parse('word OR (word2)'); expect(result.isSuccess()).toBeTruthy(); }); it('"word OR"', () => { var result = coveoGrammar.parse('word OR'); expect(result.isSuccess()).toBeTruthy(); }); it('"(word OR (word2))"', () => { var result = coveoGrammar.parse('(word OR (word2))'); expect(result.isSuccess()).toBeTruthy(); }); it('"word @"', () => { var result = coveoGrammar.parse('word @'); expect(result.isSuccess()).toBeFalsy(); expect(result.getHumanReadableExpect()).toBe('Expected FieldName but end of input found.'); }); it('"foo ( bar foo )"', () => { var result = coveoGrammar.parse('foo ( bar foo )'); expect(result.isSuccess()).toBeTruthy(); }); it('"foo bar"', () => { var result = coveoGrammar.parse('foo bar'); expect(result.isSuccess()).toBeTruthy(); expect(result.clean().toString()).toBe('foo bar'); }); it('"$extension("', () => { var result = coveoGrammar.parse('$extension('); expect(result.isSuccess()).toBeFalsy(); expect(result.getHumanReadableExpect()).toBe('Expected QueryExtensionArgumentName but end of input found.'); }); it('"$extension(a"', () => { var result = coveoGrammar.parse('$extension(a'); expect(result.isSuccess()).toBeFalsy(); expect(result.getHumanReadableExpect()).toBe('Expected ":" but end of input found.'); }); it('"$extension(a:"', () => { var result = coveoGrammar.parse('$extension(a:'); expect(result.isSuccess()).toBeFalsy(); expect(result.getHumanReadableExpect()).toBe('Expected QueryExtensionArgumentValue but end of input found.'); }); it('"$extension(a:value"', () => { var result = coveoGrammar.parse('$extension(a:value'); expect(result.isSuccess()).toBeFalsy(); expect(result.getHumanReadableExpect()).toBe('Expected ":" or Spaces or "," or ")" but end of input found.'); }); it('"$extension(a:value)"', () => { var result = coveoGrammar.parse('$extension(a:value)'); expect(result.isSuccess()).toBeTruthy(); }); it('"$extension(a:value,"', () => { var result = coveoGrammar.parse('$extension(a:value,'); expect(result.isSuccess()).toBeFalsy(); expect(result.getHumanReadableExpect()).toBe('Expected QueryExtensionArgumentName but end of input found.'); }); it('"$extension(a:value,b"', () => { var result = coveoGrammar.parse('$extension(a:value,b'); expect(result.isSuccess()).toBeFalsy(); expect(result.getHumanReadableExpect()).toBe('Expected ":" but end of input found.'); }); it('"$extension(a:value,b:"', () => { var result = coveoGrammar.parse('$extension(a:value,b:'); expect(result.isSuccess()).toBeFalsy(); expect(result.getHumanReadableExpect()).toBe('Expected QueryExtensionArgumentValue but end of input found.'); }); it('"$extension(a:value,b:\'"', () => { var result = coveoGrammar.parse("$extension(a:value,b:'"); expect(result.isSuccess()).toBeFalsy(); expect(result.getHumanReadableExpect()).toBe('Expected "\'" but end of input found.'); }); it('"$extension(a:value,b:\'abc\')"', () => { var result = coveoGrammar.parse("$extension(a:value,b:'abc')"); expect(result.isSuccess()).toBeTruthy(); }); it('"["', () => { var result = coveoGrammar.parse('['); expect(result.isSuccess()).toBeFalsy(); expect(result.getHumanReadableExpect()).toBe('Expected "[" but end of input found.'); }); it('"[["', () => { var result = coveoGrammar.parse('[['); expect(result.isSuccess()).toBeFalsy(); expect(result.getHumanReadableExpect()).toBe('Expected "@" but end of input found.'); }); it('"[[@field"', () => { var result = coveoGrammar.parse('[[@field'); expect(result.isSuccess()).toBeFalsy(); expect(result.getHumanReadableExpect()).toBe('Expected "]" but end of input found.'); }); it('"[[@field]"', () => { var result = coveoGrammar.parse('[[@field]'); expect(result.isSuccess()).toBeFalsy(); expect(result.getHumanReadableExpect()).toBe('Expected Expression but end of input found.'); }); it('"[[@field]]"', () => { var result = coveoGrammar.parse('[[@field]]'); expect(result.isSuccess()).toBeFalsy(); expect(result.getHumanReadableExpect()).toBe('Expected Expression but "]" found.'); }); it('"[[@field] @sysuri"', () => { var result = coveoGrammar.parse('[[@field] @sysuri'); expect(result.isSuccess()).toBeFalsy(); expect(result.getHumanReadableExpect()).toBe('Expected FieldQueryOperation or Spaces or "]" but end of input found.'); }); it('"[[@field] @sysuri]"', () => { var result = coveoGrammar.parse('[[@field] @sysuri]'); expect(result.isSuccess()).toBeTruthy(); }); it('""Not Quoted""', () => { var result = coveoGrammar.parse('"Not Quoted"'); expect(result.isSuccess()).toBeTruthy(); }); it('" start with space"', () => { var result = coveoGrammar.parse(' start with space'); expect(result.isSuccess()).toBeTruthy(); }); it('"end with space "', () => { var result = coveoGrammar.parse('end with space '); expect(result.isSuccess()).toBeTruthy(); }); it('"@fieldName<now"', () => { var result = coveoGrammar.parse('@fieldName<now'); expect(result.isSuccess()).toBeTruthy(); }); it('"@fieldName<now-d"', () => { var result = coveoGrammar.parse('@fieldName<now-d'); expect(result.isSuccess()).toBeFalsy(); expect(result.getHumanReadableExpect()).toBe('Expected DateRelativeNegativeRef or Spaces or end of input but "-" found.'); }); it('"@fieldName<now-1d"', () => { var result = coveoGrammar.parse('@fieldName<now-1d'); expect(result.isSuccess()).toBeTruthy(); }); it('"@fieldName<10..420"', () => { var result = coveoGrammar.parse('@fieldName<10..420'); expect(result.isSuccess()).toBeFalsy(); expect(result.getHumanReadableExpect()).toBe('Expected Spaces or end of input but "." found.'); }); it('"@fieldName=10..420"', () => { var result = coveoGrammar.parse('@fieldName=10..420'); expect(result.isSuccess()).toBeTruthy(); }); it('"@fieldName=420"', () => { var result = coveoGrammar.parse('@fieldName=420'); expect(result.isSuccess()).toBeTruthy(); }); it('"@fieldName<420"', () => { var result = coveoGrammar.parse('@fieldName<420'); expect(result.isSuccess()).toBeTruthy(); }); it('"@fieldName<4.20"', () => { var result = coveoGrammar.parse('@fieldName<4.20'); expect(result.isSuccess()).toBeTruthy(); }); it('"@fieldName<4,20"', () => { var result = coveoGrammar.parse('@fieldName<4,20'); expect(result.isSuccess()).toBeFalsy(); }); it('"@fieldName<-4.20"', () => { var result = coveoGrammar.parse('@fieldName<-4.20'); expect(result.isSuccess()).toBeTruthy(); }); it('"@fieldName<4.20.20"', () => { var result = coveoGrammar.parse('@fieldName<4.20.20'); expect(result.isSuccess()).toBeFalsy(); }); it('@fieldName>=2000/01/01', () => { var result = coveoGrammar.parse('@fieldName>=2000/01/01'); expect(result.isSuccess()).toBeTruthy(); }); it('@fieldName<=2000/01/01', () => { var result = coveoGrammar.parse('@fieldName<=2000/01/01'); expect(result.isSuccess()).toBeTruthy(); }); it('@fieldName>2000/01/01', () => { var result = coveoGrammar.parse('@fieldName>2000/01/01'); expect(result.isSuccess()).toBeTruthy(); }); it('@fieldName<2000/01/01', () => { var result = coveoGrammar.parse('@fieldName<2000/01/01'); expect(result.isSuccess()).toBeTruthy(); }); it('@fieldName==2000/01/01', () => { var result = coveoGrammar.parse('@fieldName==2000/01/01'); expect(result.isSuccess()).toBeTruthy(); }); }); }
the_stack
import * as d3 from "d3"; import { assert } from "chai"; import * as Plottable from "../../src"; import { getScaleValues, getTranslateValues } from "../../src/utils/domUtils"; import * as TestMethods from "../testMethods"; describe("Plots", () => { describe("XY Plot", () => { describe("autoranging on the x and y scales", () => { let div: d3.Selection<HTMLDivElement, any, any, any>; let xScale: Plottable.Scales.Linear; let yScale: Plottable.Scales.Linear; let plot: Plottable.XYPlot<number, number>; const xAccessor = (d: any) => d.x; const yAccessor = (d: any) => d.y; const yTransform = (d: number) => Math.pow(d, 2); const xTransform = (d: number) => Math.pow(d, 0.5); beforeEach(() => { div = TestMethods.generateDiv(); xScale = new Plottable.Scales.Linear(); yScale = new Plottable.Scales.Linear(); plot = new Plottable.XYPlot<number, number>(); const simpleDataset = new Plottable.Dataset(generateYTransformData(5)); plot.addDataset(simpleDataset); plot.x(xAccessor, xScale) .y(yAccessor, yScale) .anchor(div); xScale.padProportion(0); yScale.padProportion(0); }); function generateYTransformData(count: number) { return Plottable.Utils.Math.range(0, count).map((datumNumber: number) => { return { x: datumNumber, y: yTransform(datumNumber), }; }); } it("can set the autorange mode", () => { assert.strictEqual(plot.autorangeMode(), "none", "defaults to no autoranging"); assert.strictEqual(plot.autorangeMode("x"), plot, "setting autorange mode returns plot"); assert.strictEqual(plot.autorangeMode(), "x", "autorange mode set to x"); plot.autorangeMode("y"); assert.strictEqual(plot.autorangeMode(), "y", "autorange mode set to y"); plot.autorangeMode("none"); assert.strictEqual(plot.autorangeMode(), "none", "autorange mode set to none"); div.remove(); }); it("throws an error on setting an invalid autorange mode", () => { (<any> assert).throws(() => plot.autorangeMode("foobar"), "Invalid scale", "cannot set an invalid mode"); div.remove(); }); it("automatically adjusts Y domain over visible points", () => { const oldYDomain = yScale.domain(); const newXDomain = [2, 3]; xScale.domain(newXDomain); assert.deepEqual(yScale.domain(), oldYDomain, "domain not adjusted to visible points"); plot.autorangeMode("y"); assert.deepEqual(yScale.domain(), newXDomain.map(yTransform), "domain has been adjusted to visible points"); div.remove(); }); it("automatically adjusts Y domain to the default when no points are visible", () => { plot.autorangeMode("y"); const newXDomain = [-2, -1]; xScale.domain(newXDomain); assert.deepEqual(yScale.domain(), [0, 1], "scale uses default domain"); div.remove(); }); it("automatically adjusts Y domain when X scale is replaced", () => { plot.autorangeMode("y"); const newXScaleDomain = [0, 3]; const newXScale = new Plottable.Scales.Linear().domain(newXScaleDomain); plot.x(xAccessor, newXScale); assert.deepEqual(yScale.domain(), newXScaleDomain.map(yTransform), "domain adjusted to visible points on new X scale domain"); xScale.domain([-2, 2]); assert.deepEqual(yScale.domain(), newXScaleDomain.map(yTransform), "y scale domain does not change"); div.remove(); }); it("automatically adjusts X domain over visible points", () => { const oldXDomain = xScale.domain(); yScale.domain([0, 1]); assert.deepEqual(xScale.domain(), oldXDomain, "domain has not been adjusted to visible points"); plot.autorangeMode("x"); assert.deepEqual(xScale.domain(), yScale.domain().map(xTransform), "domain has been adjusted to visible points"); div.remove(); }); it("automatically adjusts X domain to the default when no points are visible", () => { plot.autorangeMode("x"); yScale.domain([-2, -1]); assert.deepEqual(xScale.domain(), [0, 1], "scale uses default domain"); div.remove(); }); it("automatically adjusts X domain when Y scale is replaced", () => { plot.autorangeMode("x"); const newYScaleDomain = [0, 1]; const newYScale = new Plottable.Scales.Linear().domain(newYScaleDomain); plot.y(yAccessor, newYScale); assert.deepEqual(xScale.domain(), newYScaleDomain.map(xTransform), "domain adjusted to visible points on new Y scale domain"); yScale.domain([-2, 2]); assert.deepEqual(xScale.domain(), newYScaleDomain.map(xTransform), "x scale domain does not change"); div.remove(); }); it("can show all of the data regardless of autoranging", () => { plot.autorangeMode("y"); xScale.domain([-0.5, 0.5]); plot.showAllData(); assert.deepEqual(yScale.domain(), [0, 16], "y domain adjusted to show all data"); assert.deepEqual(xScale.domain(), [0, 4], "x domain adjusted to show all data"); div.remove(); }); it("stops autoranging after the plot is destroyed", () => { plot.autorangeMode("y"); plot.destroy(); xScale.domain([0, 2]); assert.deepEqual(yScale.domain(), [0, 1], "autoranging no longer occurs"); div.remove(); }); }); describe("deferred rendering", () => { let plot: Plottable.XYPlot<number, number>; beforeEach(() => { plot = new Plottable.XYPlot<number, number>(); }); it("can set if rendering is deferred", () => { assert.strictEqual(plot.deferredRendering(), false, "deferred rendering is false by default"); assert.strictEqual(plot.deferredRendering(true), plot, "setting the deferred rendering option returns the plot"); assert.strictEqual(plot.deferredRendering(), true, "deferred rendering can be turned on"); plot.deferredRendering(false); assert.strictEqual(plot.deferredRendering(), false, "deferred rendering can be turned off"); }); it("immediately translates the render area when the scale domain is translated", () => { plot.deferredRendering(true); const div = TestMethods.generateDiv(); plot.anchor(div); const xScale = new Plottable.Scales.Linear(); plot.x(0, xScale); const translateAmount = 1; xScale.domain(xScale.domain().map((d) => d + translateAmount)); const renderAreaTranslate = getTranslateValues(plot.content().select(".render-area")); assert.deepEqual(renderAreaTranslate[0], -translateAmount, "translates with the same amount as domain shift"); div.remove(); }); it("immediately scales the render area when the scale domain is scaled", () => { const div = TestMethods.generateDiv(); plot.anchor(div); const xScale = new Plottable.Scales.Linear(); plot.x(0, xScale); plot.deferredRendering(true); plot.computeLayout(); const magnifyAmount = 2; xScale.domain(xScale.domain().map((d) => d * magnifyAmount)); const renderAreaScale = getScaleValues(plot.content().select(".render-area")); assert.deepEqual(renderAreaScale[0], 1 / magnifyAmount, "scales with the same amount as domain change"); div.remove(); }); }); describe("computing the layout", () => { let div: d3.Selection<HTMLDivElement, any, any, any>; beforeEach(() => { div = TestMethods.generateDiv(); }); it("extends the x scale range to the component width", () => { const xScale = new Plottable.Scales.Linear(); const plot = new Plottable.XYPlot<number, number>(); plot.x(0, xScale); plot.anchor(div); plot.computeLayout(); assert.deepEqual(xScale.range(), [0, plot.width()], "range extends to the width"); div.remove(); }); it("sets the y scale range to start from the bottom for non-Category scales", () => { const yScale = new Plottable.Scales.Linear(); const plot = new Plottable.XYPlot<number, number>(); plot.y(0, yScale); plot.anchor(div); plot.computeLayout(); assert.deepEqual(yScale.range(), [plot.height(), 0], "range extends from the height"); div.remove(); }); it("sets the y scale range to start from the top if it is a Category scale", () => { const yScale = new Plottable.Scales.Category(); const plot = new Plottable.XYPlot<number, string>(); plot.y("one", yScale); plot.anchor(div); plot.computeLayout(); assert.deepEqual(yScale.range(), [0, plot.height()], "range extends to the height"); div.remove(); }); }); describe("managing the x property", () => { let plot: Plottable.XYPlot<number, number>; beforeEach(() => { plot = new Plottable.XYPlot<number, number>(); // HACKHACK: Must install y scale https://github.com/palantir/plottable/issues/2934 plot.y(0, new Plottable.Scales.Linear()); }); afterEach(() => { plot.destroy(); }); it("can set the x property to a constant value", () => { const constantX = 10; assert.strictEqual(plot.x(constantX), plot, "setting the x property returns the plot"); assert.strictEqual(plot.x().accessor(null, 0, null), constantX, "returns an accessor returning the constant value"); }); it("can set the x property be based on data", () => { const accessor = (d: any) => d * 10; assert.strictEqual(plot.x(accessor), plot, "setting the x property returns the plot"); const testData = [4, 2, 3, 5, 6]; const dataset = new Plottable.Dataset(testData); dataset.data().forEach((d, i) => { assert.strictEqual(plot.x().accessor(d, i, dataset), accessor(d), "returns the input accessor"); }); }); it("can set the x property be based on scaled data", () => { const accessor = (d: any) => d * 10; const scale = new Plottable.Scales.Linear(); assert.strictEqual(plot.x(accessor, scale), plot, "setting the x property returns the plot"); const testData = [4, 2, 3, 5, 6]; const dataset = new Plottable.Dataset(testData); dataset.data().forEach((d, i) => { const bindingAccessor = plot.x().accessor; const bindingScale = plot.x().scale; assert.strictEqual(bindingScale.scale(bindingAccessor(d, i, dataset)), scale.scale(accessor(d)), "returns the input accessor and scale"); }); }); it("sets the range on the input scale if the plot has a width", () => { const div = TestMethods.generateDiv(); plot.anchor(div); plot.computeLayout(); const scale = new Plottable.Scales.Linear(); assert.strictEqual(plot.x(0, scale), plot, "setting the x property returns the plot"); assert.deepEqual(scale.range(), [0, plot.width()], "range goes to width on scale"); div.remove(); }); it("can install its extent onto the input scale", () => { const div = TestMethods.generateDiv(); const data = [0, 1, 2, 3, 4]; plot.addDataset(new Plottable.Dataset(data)); plot.anchor(div); const scale = new Plottable.Scales.Linear(); scale.padProportion(0); assert.strictEqual(plot.x((d) => d, scale), plot, "setting the x property returns the plot"); const mathUtils = Plottable.Utils.Math; assert.deepEqual(scale.domain(), [mathUtils.min(data, 0), mathUtils.max(data, 0)], "range goes to width on scale"); div.remove(); }); }); describe("managing the y property", () => { let plot: Plottable.XYPlot<number, any>; beforeEach(() => { plot = new Plottable.XYPlot<number, any>(); // HACKHACK: Must install x scale https://github.com/palantir/plottable/issues/2934 plot.x(0, new Plottable.Scales.Linear()); }); afterEach(() => { plot.destroy(); }); it("can set the y property to a constant value", () => { const constantY = 10; assert.strictEqual(plot.y(constantY), plot, "setting the y property returns the plot"); assert.strictEqual(plot.y().accessor(null, 0, null), constantY, "returns an accessor returning the constant value"); }); it("can set the y property be based on data", () => { const accessor = (d: any) => d * 10; assert.strictEqual(plot.y(accessor), plot, "setting the y property returns the plot"); const testData = [4, 2, 3, 5, 6]; const dataset = new Plottable.Dataset(testData); dataset.data().forEach((d, i) => { assert.strictEqual(plot.y().accessor(d, i, dataset), accessor(d), "returns the input accessor"); }); }); it("can set the y property be based on scaled data", () => { const accessor = (d: any) => d * 10; const scale = new Plottable.Scales.Linear(); assert.strictEqual(plot.y(accessor, scale), plot, "setting the y property returns the plot"); const testData = [4, 2, 3, 5, 6]; const dataset = new Plottable.Dataset(testData); dataset.data().forEach((d, i) => { const bindingAccessor = plot.y().accessor; const bindingScale = plot.y().scale; assert.strictEqual(bindingScale.scale(bindingAccessor(d, i, dataset)), scale.scale(accessor(d)), "returns the input accessor and scale"); }); }); it("sets the range on the input scale if the plot has a height", () => { const div = TestMethods.generateDiv(); plot.anchor(div); plot.computeLayout(); const scale = new Plottable.Scales.Linear(); assert.strictEqual(plot.y(0, scale), plot, "setting the y property returns the plot"); assert.deepEqual(scale.range(), [plot.height(), 0], "range goes from height on scale"); div.remove(); }); it("sets the range to be reversed on the input Category scale if the plot has a height", () => { const div = TestMethods.generateDiv(); plot.anchor(div); plot.computeLayout(); const scale = new Plottable.Scales.Category(); assert.strictEqual(plot.y(0, scale), plot, "setting the y property returns the plot"); assert.deepEqual(scale.range(), [0, plot.height()], "range goes to height on scale"); div.remove(); }); it("can install its extent onto the input scale", () => { const div = TestMethods.generateDiv(); const data = [0, 1, 2, 3, 4]; plot.addDataset(new Plottable.Dataset(data)); plot.anchor(div); const scale = new Plottable.Scales.Linear(); scale.padProportion(0); assert.strictEqual(plot.y((d: number) => d, scale), plot, "setting the y property returns the plot"); const mathUtils = Plottable.Utils.Math; assert.deepEqual(scale.domain(), [mathUtils.min(data, 0), mathUtils.max(data, 0)], "range goes to width on scale"); div.remove(); }); }); }); });
the_stack
import * as React from 'react' import { createHashHistory, createBrowserHistory, createMemoryHistory, BrowserHistory, MemoryHistory, History, HashHistory, } from 'history' import { decode, encode } from './qss' export { createHashHistory, createBrowserHistory, createMemoryHistory } // Types type Timeout = ReturnType<typeof setTimeout> type Maybe<T, TUnknown> = T extends {} ? T : TUnknown export type DefaultGenerics = { Params: Params<string> Search: Search<unknown> RouteMeta: RouteMeta<unknown> } export type PartialGenerics = Partial<DefaultGenerics> export type MakeGenerics<TGenerics extends PartialGenerics> = TGenerics export type Search<T> = Record<string, T> export type Params<T> = Record<string, T> export type RouteMeta<T> = Record<string, T> export type UseGeneric< TGenerics extends PartialGenerics, TGeneric extends keyof PartialGenerics, > = TGeneric extends 'Search' ? Partial<Maybe<TGenerics[TGeneric], DefaultGenerics[TGeneric]>> : Maybe<TGenerics[TGeneric], DefaultGenerics[TGeneric]> export type ReactLocationOptions = { // The history object to be used internally by react-location // A history will be created automatically if not provided. history?: BrowserHistory | MemoryHistory | HashHistory stringifySearch?: SearchSerializer parseSearch?: SearchParser } type SearchSerializer = (searchObj: Record<string, any>) => string type SearchParser = (searchStr: string) => Record<string, any> export type Updater<TResult> = TResult | ((prev?: TResult) => TResult) export type Location<TGenerics extends PartialGenerics = DefaultGenerics> = { href: string pathname: string search: UseGeneric<TGenerics, 'Search'> searchStr: string hash: string key?: string // nextAction?: 'push' | 'replace' } export type Route<TGenerics extends PartialGenerics = DefaultGenerics> = { // The path to match (relative to the nearest parent `Route` component or root basepath) path?: string // An ID to uniquely identify this route within its siblings. This is only required for routes that *only match on search* or if you have multiple routes with the same path id?: string // If true, this route will be matched as case-sensitive caseSensitive?: boolean // Either (1) an object that will be used to shallowly match the current location's search or (2) A function that receives the current search params and can return truthy if they are matched. search?: SearchPredicate<UseGeneric<TGenerics, 'Search'>> // Filter functions that can manipulate search params *before* they are passed to links and navigate // calls that match this route. preSearchFilters?: SearchFilter<TGenerics>[] // Filter functions that can manipulate search params *after* they are passed to links and navigate // calls that match this route. postSearchFilters?: SearchFilter<TGenerics>[] // An array of child routes children?: Route<TGenerics>[] // Route Loaders (see below) can be inline on the route, or resolved async pendingElement?: React.ReactNode } & RouteLoaders<TGenerics> export type RouteLoaders<TGenerics> = { // The content to be rendered when the route is matched. If no element is provided, defaults to `<Outlet />` element?: React.ReactNode // An asynchronous function responsible for preparing or fetching data for the route before it is rendered // An object of whatever you want! This object is accessible anywhere matches are. meta?: UseGeneric<TGenerics, 'RouteMeta'> } export type SearchFilter<TGenerics> = ( prev: UseGeneric<TGenerics, 'Search'>, ) => UseGeneric<TGenerics, 'Search'> export type MatchLocation<TGenerics extends PartialGenerics = DefaultGenerics> = { to?: string | number | null search?: SearchPredicate<UseGeneric<TGenerics, 'Search'>> fuzzy?: boolean caseSensitive?: boolean } export type SearchPredicate<TSearch> = (search: TSearch) => any export type ListenerFn = () => void export type Segment = { type: 'pathname' | 'param' | 'wildcard' value: string } export type RouterProps<TGenerics extends PartialGenerics = DefaultGenerics> = { // Children will default to `<Outlet />` if not provided children?: React.ReactNode location: ReactLocation<TGenerics> } & RouterOptions<TGenerics> export type RouterOptions<TGenerics> = { // An array of route objects to match routes: Route<TGenerics>[] basepath?: string filterRoutes?: FilterRoutesFn useErrorBoundary?: boolean defaultElement?: React.ReactNode defaultPendingElement?: React.ReactNode caseSensitive?: boolean // An array of route match objects that have been both _matched_ and _loaded_. See the [SRR](#ssr) section for more details // snapshot?: RouterSnapshot<TGenerics> } export type BuildNextOptions< TGenerics extends PartialGenerics = DefaultGenerics, > = { to?: string | number | null search?: true | Updater<UseGeneric<TGenerics, 'Search'>> hash?: true | Updater<string> from?: Partial<Location<TGenerics>> key?: string __preSearchFilters?: SearchFilter<TGenerics>[] __postSearchFilters?: SearchFilter<TGenerics>[] } export type NavigateOptions<TGenerics> = BuildNextOptions<TGenerics> & { replace?: boolean fromCurrent?: boolean } export type PromptProps = { message: string when?: boolean | any children?: React.ReactNode } export type LinkProps<TGenerics extends PartialGenerics = DefaultGenerics> = Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, 'href' | 'children'> & { // The absolute or relative destination pathname to?: string | number | null // The new search object or a function to update it search?: true | Updater<UseGeneric<TGenerics, 'Search'>> // The new has string or a function to update it hash?: Updater<string> // Whether to replace the current history stack instead of pushing a new one replace?: boolean // A function that is passed the [Location API](#location-api) and returns additional props for the `active` state of this link. These props override other props passed to the link (`style`'s are merged, `className`'s are concatenated) getActiveProps?: () => Record<string, any> // A function that is passed the [Location API](#location-api) and returns additional props for the `inactive` state of this link. These props override other props passed to the link (`style`'s are merged, `className`'s are concatenated) getInactiveProps?: () => Record<string, any> // Defaults to `{ exact: false, includeHash: false }` activeOptions?: ActiveOptions // If true, will render the link without the href attribute disabled?: boolean // A custom ref prop because of this: https://stackoverflow.com/questions/58469229/react-with-typescript-generics-while-using-react-forwardref/58473012 _ref?: React.Ref<HTMLAnchorElement> // If a function is pass as a child, it will be given the `isActive` boolean to aid in further styling on the element it returns children?: | React.ReactNode | ((state: { isActive: boolean }) => React.ReactNode) } type ActiveOptions = { exact?: boolean includeHash?: boolean } export type LinkPropsType<TGenerics extends PartialGenerics = DefaultGenerics> = LinkProps<TGenerics> export type TransitionState<TGenerics> = { location: Location<TGenerics> matches: RouteMatch<TGenerics>[] } export type FilterRoutesFn = < TGenerics extends PartialGenerics = DefaultGenerics, >( routes: Route<TGenerics>[], ) => Route<TGenerics>[] export type RouterPropsType< TGenerics extends PartialGenerics = DefaultGenerics, > = RouterProps<TGenerics> export type RouterType<TGenerics extends PartialGenerics = DefaultGenerics> = ( props: RouterProps<TGenerics>, ) => JSX.Element type Listener = () => void // Source const LocationContext = React.createContext<{ location: ReactLocation<any> }>( null!, ) const MatchesContext = React.createContext<RouteMatch<any>[]>(null!) const routerContext = React.createContext< RouterInstance<any> & { state: TransitionState<any> } >(null!) // Detect if we're in the DOM const isDOM = Boolean( typeof window !== 'undefined' && window.document && window.document.createElement, ) const useLayoutEffect = isDOM ? React.useLayoutEffect : React.useEffect // This is the default history object if none is defined const createDefaultHistory = () => isDOM ? createBrowserHistory() : createMemoryHistory() export class ReactLocation< TGenerics extends PartialGenerics = DefaultGenerics, > { history: BrowserHistory | MemoryHistory stringifySearch: SearchSerializer parseSearch: SearchParser current: Location<TGenerics> destroy: () => void navigateTimeout?: Timeout nextAction?: 'push' | 'replace' // listeners: Listener[] = [] isTransitioning: boolean = false constructor(options?: ReactLocationOptions) { this.history = options?.history || createDefaultHistory() this.stringifySearch = options?.stringifySearch ?? defaultStringifySearch this.parseSearch = options?.parseSearch ?? defaultParseSearch this.current = this.parseLocation(this.history.location) this.destroy = this.history.listen((event) => { this.current = this.parseLocation(event.location, this.current) this.notify() }) } subscribe(listener: Listener): () => void { this.listeners.push(listener as Listener) return () => { this.listeners = this.listeners.filter((x) => x !== listener) } } notify(): void { this.listeners.forEach((listener) => listener()) } buildNext( basepath: string = '/', dest: BuildNextOptions<TGenerics> = {}, ): Location<TGenerics> { const from = { ...this.current, ...dest.from, } const pathname = resolvePath(basepath, from.pathname, `${dest.to ?? '.'}`) // Pre filters first const preFilteredSearch = dest.__preSearchFilters?.length ? dest.__preSearchFilters.reduce((prev, next) => next(prev), from.search) : from.search // Then the link/navigate function const destSearch = dest.search === true ? preFilteredSearch // Preserve from true : dest.search ? functionalUpdate(dest.search, preFilteredSearch) ?? {} // Updater : dest.__preSearchFilters?.length ? preFilteredSearch // Preserve from filters : {} // Then post filters const postFilteredSearch = dest.__postSearchFilters?.length ? dest.__postSearchFilters.reduce((prev, next) => next(prev), destSearch) : destSearch const search = replaceEqualDeep(from.search, postFilteredSearch) const searchStr = this.stringifySearch(search) let hash = dest.hash === true ? from.hash : functionalUpdate(dest.hash, from.hash) hash = hash ? `#${hash}` : '' return { pathname, search, searchStr, hash, href: `${pathname}${searchStr}${hash}`, key: dest.key, } } navigate(next: Location<TGenerics>, replace?: boolean): void { this.current = next if (this.navigateTimeout) clearTimeout(this.navigateTimeout) let nextAction: 'push' | 'replace' = 'replace' if (!replace) { nextAction = 'push' } const isSameUrl = this.parseLocation(this.history.location).href === this.current.href if (isSameUrl && !this.current.key) { nextAction = 'replace' } if (nextAction === 'replace') { return this.history.replace({ pathname: this.current.pathname, hash: this.current.hash, search: this.current.searchStr, }) } return this.history.push({ pathname: this.current.pathname, hash: this.current.hash, search: this.current.searchStr, }) } parseLocation( location: History['location'], previousLocation?: Location<TGenerics>, ): Location<TGenerics> { const parsedSearch = this.parseSearch(location.search) return { pathname: location.pathname, searchStr: location.search, search: replaceEqualDeep(previousLocation?.search, parsedSearch), hash: location.hash.split('#').reverse()[0] ?? '', href: `${location.pathname}${location.search}${location.hash}`, key: location.key, } } } export type MatchesProviderProps<TGenerics> = { value: RouteMatch<TGenerics>[] children: React.ReactNode } export function MatchesProvider<TGenerics>( props: MatchesProviderProps<TGenerics>, ) { return <MatchesContext.Provider {...props} /> } export type RouterInstance<TGenerics> = { routesById: Record<string, Route<TGenerics>> basepath: string rootMatch?: RouteMatch<TGenerics> routes: Route<TGenerics>[] filterRoutes?: FilterRoutesFn useErrorBoundary?: boolean defaultElement?: React.ReactNode defaultPendingElement?: React.ReactNode caseSensitive?: boolean state: TransitionState<TGenerics> } export function Router<TGenerics extends PartialGenerics = DefaultGenerics>({ children, location, routes, basepath: userBasepath, // snapshot, ...rest }: RouterProps<TGenerics>) { const basepath = cleanPath(`/${userBasepath ?? ''}`) const [routerState, setRouterState] = React.useState< TransitionState<TGenerics> >({ location: location.current, matches: [], }) const rootMatch = React.useMemo( () => ({ id: 'root', params: {} as any, search: {} as any, pathname: basepath, route: null!, }), [basepath], ) const router: RouterInstance<TGenerics> = React.useMemo(() => { const routesById: RouterInstance<TGenerics>['routesById'] = {} const recurseRoutes = ( routes: Route<TGenerics>[], parent?: Route<TGenerics>, ): Route<TGenerics>[] => { return routes.map((route) => { const path = route.path ?? '*' const id = joinPaths([ parent?.id === 'root' ? '' : parent?.id, `${path?.replace(/(.)\/$/, '$1')}${route.id ? `-${route.id}` : ''}`, ]) route = { ...route, id, } if (routesById[id]) { if (process.env.NODE_ENV !== 'production') { console.warn( `Duplicate routes found with id: ${id}`, routesById, route, ) } throw new Error() } routesById[id] = route route.children = route.children?.length ? recurseRoutes(route.children, route) : undefined return route }) } routes = recurseRoutes(routes) return { ...rest, routesById, routes, basepath, rootMatch, state: routerState, } }, [routerState, rootMatch, basepath]) useLayoutEffect(() => { const update = () => { const matches = matchRoutes(router, location.current) setRouterState(() => { return { location: location.current, matches: matches, } }) } update() return location.subscribe(update) }, [location]) return ( <LocationContext.Provider value={{ location }}> <routerContext.Provider value={router}> <InitialSideEffects /> <MatchesProvider value={[router.rootMatch!, ...router.state.matches]}> {children ?? <Outlet />} </MatchesProvider> </routerContext.Provider> </LocationContext.Provider> ) } function InitialSideEffects() { const location = useLocation() const buildNext = useBuildNext() const navigate = useNavigate() useLayoutEffect(() => { const next = buildNext({ to: '.', search: true, hash: true, }) if (next.href !== location.current.href) { navigate({ to: '.', search: true, hash: true, fromCurrent: true, replace: true, }) } }, []) return null } export type UseLocationType< TGenerics extends PartialGenerics = DefaultGenerics, > = () => ReactLocation<TGenerics> export function useLocation< TGenerics extends PartialGenerics = DefaultGenerics, >(): ReactLocation<TGenerics> { const context = React.useContext(LocationContext) as { location: ReactLocation<TGenerics> } warning(!!context, 'useLocation must be used within a <ReactLocation />') return context.location } export type RouteMatch<TGenerics extends PartialGenerics = DefaultGenerics> = { id: string route: Route<TGenerics> pathname: string params: UseGeneric<TGenerics, 'Params'> search: UseGeneric<TGenerics, 'Search'> } export type UseRouterType<TGenerics extends PartialGenerics = DefaultGenerics> = () => RouterInstance<TGenerics> export function useRouter< TGenerics extends PartialGenerics = DefaultGenerics, >(): RouterInstance<TGenerics> { const value = React.useContext(routerContext) if (!value) { warning(true, 'You are trying to use useRouter() outside of ReactLocation!') throw new Error() } return value as RouterInstance<TGenerics> } export type MatchRoutesType< TGenerics extends PartialGenerics = DefaultGenerics, > = ( router: RouterInstance<TGenerics>[], currentLocation: Location<TGenerics>, ) => Promise<RouteMatch<TGenerics>[]> export function matchRoutes< TGenerics extends PartialGenerics = DefaultGenerics, >( router: RouterInstance<TGenerics>, currentLocation: Location<TGenerics>, ): RouteMatch<TGenerics>[] { if (!router.routes.length) { return [] } const matches: RouteMatch<TGenerics>[] = [] const recurse = ( routes: Route<TGenerics>[], parentMatch: RouteMatch<TGenerics>, ) => { let { pathname, params } = parentMatch const filteredRoutes = router?.filterRoutes ? router?.filterRoutes(routes) : routes const route = filteredRoutes.find((route) => { const fullRoutePathName = joinPaths([pathname, route.path]) const fuzzy = !!(route.path !== '/' || route.children?.length) const matchParams = matchRoute(currentLocation, { to: fullRoutePathName, search: route.search, fuzzy, caseSensitive: route.caseSensitive ?? router.caseSensitive, }) if (matchParams) { params = { ...params, ...matchParams, } } return !!matchParams }) if (!route) { return } const interpolatedPath = interpolatePath(route.path, params) pathname = joinPaths([pathname, interpolatedPath]) const interpolatedId = interpolatePath(route.id, params, true) const match: RouteMatch<TGenerics> = { id: interpolatedId, route, params, pathname, search: currentLocation.search, } matches.push(match) if (route.children?.length) { recurse(route.children, match) } } recurse(router.routes, router.rootMatch!) return matches } function interpolatePath( path: string | undefined, params: any, leaveWildcard?: boolean, ) { const interpolatedPathSegments = parsePathname(path) return joinPaths( interpolatedPathSegments.map((segment) => { if (segment.value === '*' && !leaveWildcard) { return '' } if (segment.type === 'param') { return params![segment.value.substring(1)] ?? '' } return segment.value }), ) } export type UseMatchesType< TGenerics extends PartialGenerics = DefaultGenerics, > = () => RouteMatch<TGenerics>[] export function useParentMatches< TGenerics extends PartialGenerics = DefaultGenerics, >(): RouteMatch<TGenerics>[] { const router = useRouter<TGenerics>() const match = useMatch() const matches = router.state.matches return matches.slice(0, matches.findIndex((d) => d.id === match.id) - 1) } export function useMatches< TGenerics extends PartialGenerics = DefaultGenerics, >(): RouteMatch<TGenerics>[] { return React.useContext(MatchesContext) } export type UseMatchType<TGenerics extends PartialGenerics = DefaultGenerics> = () => RouteMatch<TGenerics> export function useMatch< TGenerics extends PartialGenerics = DefaultGenerics, >(): RouteMatch<TGenerics> { return useMatches<TGenerics>()?.[0]! } export type UseNavigateType< TGenerics extends PartialGenerics = DefaultGenerics, > = (options: NavigateOptions<TGenerics>) => void export function useNavigate< TGenerics extends PartialGenerics = DefaultGenerics, >() { const location = useLocation<TGenerics>() const match = useMatch<TGenerics>() const buildNext = useBuildNext<TGenerics>() function navigate({ search, hash, replace, from, to, fromCurrent, }: NavigateOptions<TGenerics> & { replace?: boolean }) { fromCurrent = fromCurrent ?? typeof to === 'undefined' const next = buildNext({ to, search, hash, from: fromCurrent ? location.current : from ?? { pathname: match.pathname }, }) location.navigate(next, replace) } return useLatestCallback(navigate) } export type NavigateType<TGenerics extends PartialGenerics = DefaultGenerics> = (options: NavigateOptions<TGenerics>) => null export function Navigate<TGenerics extends PartialGenerics = DefaultGenerics>( options: NavigateOptions<TGenerics>, ) { let navigate = useNavigate<TGenerics>() useLayoutEffect(() => { navigate(options) }, [navigate]) return null } function useBuildNext<TGenerics>() { const location = useLocation<TGenerics>() const router = useRouter<TGenerics>() const buildNext = (opts: BuildNextOptions<TGenerics>) => { const next = location.buildNext(router.basepath, opts) const matches = matchRoutes<TGenerics>(router, next) const __preSearchFilters = matches .map((match) => match.route.preSearchFilters ?? []) .flat() .filter(Boolean) const __postSearchFilters = matches .map((match) => match.route.postSearchFilters ?? []) .flat() .filter(Boolean) return location.buildNext(router.basepath, { ...opts, __preSearchFilters, __postSearchFilters, }) } return useLatestCallback(buildNext) } export type LinkType<TGenerics extends PartialGenerics = DefaultGenerics> = ( props: LinkProps<TGenerics>, ) => JSX.Element export const Link = function Link< TGenerics extends PartialGenerics = DefaultGenerics, >({ to = '.', search, hash, children, target, style = {}, replace, onClick, onMouseEnter, className = '', getActiveProps = () => ({ className: 'active' }), getInactiveProps = () => ({}), activeOptions, disabled, _ref, ...rest }: LinkProps<TGenerics>) { const match = useMatch<TGenerics>() const location = useLocation<TGenerics>() const navigate = useNavigate<TGenerics>() const buildNext = useBuildNext<TGenerics>() // If this `to` is a valid external URL, log a warning try { const url = new URL(`${to}`) warning( false, `<Link /> should not be used for external URLs like: ${url.href}`, ) } catch (e) {} const next = buildNext({ to, search, hash, from: { pathname: match.pathname }, }) // The click handler const handleClick = (e: React.MouseEvent<HTMLAnchorElement>) => { if (onClick) onClick(e) if ( !isCtrlEvent(e) && !e.defaultPrevented && (!target || target === '_self') && e.button === 0 ) { e.preventDefault() // All is well? Navigate! navigate({ to, search, hash, replace, from: { pathname: match.pathname }, }) } } // Compare path/hash for matches const pathIsEqual = location.current.pathname === next.pathname const currentPathSplit = location.current.pathname.split('/') const nextPathSplit = next.pathname.split('/') const pathIsFuzzyEqual = nextPathSplit.every( (d, i) => d === currentPathSplit[i], ) const hashIsEqual = location.current.hash === next.hash // Combine the matches based on user options const pathTest = activeOptions?.exact ? pathIsEqual : pathIsFuzzyEqual const hashTest = activeOptions?.includeHash ? hashIsEqual : true // The final "active" test const isActive = pathTest && hashTest // Get the active props const { style: activeStyle = {}, className: activeClassName = '', ...activeRest } = isActive ? getActiveProps() : {} // Get the inactive props const { style: inactiveStyle = {}, className: inactiveClassName = '', ...inactiveRest } = isActive ? {} : getInactiveProps() return ( <a {...{ ref: _ref, href: disabled ? undefined : next.href, onClick: handleClick, target, style: { ...style, ...activeStyle, ...inactiveStyle, }, className: [className, activeClassName, inactiveClassName] .filter(Boolean) .join(' ') || undefined, ...(disabled ? { role: 'link', 'aria-disabled': true, } : undefined), ...rest, ...activeRest, ...inactiveRest, children: typeof children === 'function' ? children({ isActive }) : children, }} /> ) } export function Outlet<TGenerics extends PartialGenerics = DefaultGenerics>() { const router = useRouter<TGenerics>() const [_, ...matches] = useMatches<TGenerics>() const match = matches[0] if (!match) { return null } const matchElement = match.route.element ?? router.defaultElement const element = ( <MatchesProvider value={matches}> {matchElement ?? <Outlet />} </MatchesProvider> ) const pendingElement = match.route.pendingElement ?? router.defaultPendingElement if (pendingElement) { return <React.Suspense fallback={pendingElement}>{element}</React.Suspense> } return element } export function useResolvePath< TGenerics extends PartialGenerics = DefaultGenerics, >() { const router = useRouter<TGenerics>() const match = useMatch<TGenerics>() return useLatestCallback((path: string) => resolvePath(router.basepath!, match.pathname!, cleanPath(path)), ) } export type UseSearchType<TGenerics extends PartialGenerics = DefaultGenerics> = () => Partial<Maybe<TGenerics['Search'], Search<any>>> export function useSearch< TGenerics extends PartialGenerics = DefaultGenerics, >() { const location = useLocation<TGenerics>() return location.current.search } export type MatchRouteType< TGenerics extends PartialGenerics = DefaultGenerics, > = ( currentLocation: Location<TGenerics>, matchLocation: MatchLocation<TGenerics>, ) => UseGeneric<TGenerics, 'Params'> | undefined export function matchRoute<TGenerics extends PartialGenerics = DefaultGenerics>( currentLocation: Location<TGenerics>, matchLocation: MatchLocation<TGenerics>, ): UseGeneric<TGenerics, 'Params'> | undefined { const pathParams = matchByPath(currentLocation, matchLocation) const searchMatched = matchBySearch(currentLocation, matchLocation) if (matchLocation.to && !pathParams) { return } if (matchLocation.search && !searchMatched) { return } return (pathParams ?? {}) as UseGeneric<TGenerics, 'Params'> } export type UseMatchRouteType< TGenerics extends PartialGenerics = DefaultGenerics, > = () => ( matchLocation: MatchLocation<TGenerics>, ) => Maybe<TGenerics['Params'], Params<any>> | undefined export function useMatchRoute< TGenerics extends PartialGenerics = DefaultGenerics, >(): ( matchLocation: MatchLocation<TGenerics>, opts?: { caseSensitive?: boolean }, ) => Maybe<TGenerics['Params'], Params<any>> | undefined { const router = useRouter<TGenerics>() const resolvePath = useResolvePath<TGenerics>() return useLatestCallback( (matchLocation: MatchLocation<TGenerics> & { pending?: boolean }) => { matchLocation = { ...matchLocation, to: matchLocation.to ? resolvePath(`${matchLocation.to}`) : undefined, } return matchRoute(router.state.location, matchLocation) }, ) } export function MatchRoute< TGenerics extends PartialGenerics = DefaultGenerics, >({ children, ...rest }: MatchLocation<TGenerics> & { children: | React.ReactNode | ((isNextLocation?: Params<TGenerics>) => React.ReactNode) }) { const matchRoute = useMatchRoute<TGenerics>() const match = matchRoute(rest) if (typeof children === 'function') { return children(match as any) } return match ? children : null } export function usePrompt(message: string, when: boolean | any): void { const location = useLocation() React.useEffect(() => { if (!when) return let unblock = location.history.block((transition) => { if (window.confirm(message)) { unblock() transition.retry() } else { location.current.pathname = window.location.pathname } }) return unblock }, [when, location, message]) } export function Prompt({ message, when, children }: PromptProps) { usePrompt(message, when ?? true) return (children ?? null) as React.ReactNode } function warning(cond: boolean, message: string) { if (!cond) { if (typeof console !== 'undefined') console.warn(message) try { throw new Error(message) } catch {} } } function isFunction(d: any): d is Function { return typeof d === 'function' } export function functionalUpdate<TResult>( updater?: Updater<TResult>, previous?: TResult, ) { if (isFunction(updater)) { return updater(previous as TResult) } return updater } function joinPaths(paths: (string | undefined)[]) { return cleanPath(paths.filter(Boolean).join('/')) } export function cleanPath(path: string) { // remove double slashes return `${path}`.replace(/\/{2,}/g, '/') } export function matchByPath< TGenerics extends PartialGenerics = DefaultGenerics, >( currentLocation: Location<TGenerics>, matchLocation: MatchLocation<TGenerics>, ): UseGeneric<TGenerics, 'Params'> | undefined { const baseSegments = parsePathname(currentLocation.pathname) const routeSegments = parsePathname(`${matchLocation.to ?? '*'}`) const params: Record<string, string> = {} let isMatch = (() => { for ( let i = 0; i < Math.max(baseSegments.length, routeSegments.length); i++ ) { const baseSegment = baseSegments[i] const routeSegment = routeSegments[i] const isLastRouteSegment = i === routeSegments.length - 1 const isLastBaseSegment = i === baseSegments.length - 1 if (routeSegment) { if (routeSegment.type === 'wildcard') { if (baseSegment?.value) { params['*'] = joinPaths(baseSegments.slice(i).map((d) => d.value)) return true } return false } if (routeSegment.type === 'pathname') { if (routeSegment.value === '/' && !baseSegment?.value) { return true } if (baseSegment) { if (matchLocation.caseSensitive) { if (routeSegment.value !== baseSegment.value) { return false } } else if ( routeSegment.value.toLowerCase() !== baseSegment.value.toLowerCase() ) { return false } } } if (!baseSegment) { return false } if (routeSegment.type === 'param') { params[routeSegment.value.substring(1)] = baseSegment.value } } if (isLastRouteSegment && !isLastBaseSegment) { return !!matchLocation.fuzzy } } return true })() return isMatch ? (params as UseGeneric<TGenerics, 'Params'>) : undefined } function matchBySearch<TGenerics extends PartialGenerics = DefaultGenerics>( currentLocation: Location<TGenerics>, matchLocation: MatchLocation<TGenerics>, ) { return !!( matchLocation.search && matchLocation.search(currentLocation.search) ) } export function parsePathname(pathname?: string): Segment[] { if (!pathname) { return [] } pathname = cleanPath(pathname) const segments: Segment[] = [] if (pathname.slice(0, 1) === '/') { pathname = pathname.substring(1) segments.push({ type: 'pathname', value: '/', }) } if (!pathname) { return segments } // Remove empty segments and '.' segments const split = pathname.split('/').filter(Boolean) segments.push( ...split.map((part): Segment => { if (part.startsWith('*')) { return { type: 'wildcard', value: part, } } if (part.charAt(0) === ':') { return { type: 'param', value: part, } } return { type: 'pathname', value: part, } }), ) if (pathname.slice(-1) === '/') { pathname = pathname.substring(1) segments.push({ type: 'pathname', value: '/', }) } return segments } export function resolvePath(basepath: string, base: string, to: string) { base = base.replace(new RegExp(`^${basepath}`), '/') to = to.replace(new RegExp(`^${basepath}`), '/') let baseSegments = parsePathname(base) const toSegments = parsePathname(to) toSegments.forEach((toSegment, index) => { if (toSegment.value === '/') { if (!index) { // Leading slash baseSegments = [toSegment] } else if (index === toSegments.length - 1) { // Trailing Slash baseSegments.push(toSegment) } else { // ignore inter-slashes } } else if (toSegment.value === '..') { baseSegments.pop() } else if (toSegment.value === '.') { return } else { baseSegments.push(toSegment) } }) const joined = joinPaths([basepath, ...baseSegments.map((d) => d.value)]) return cleanPath(joined) } function isCtrlEvent(e: React.MouseEvent) { return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) } function useLatestCallback<TCallback extends (...args: any[]) => any>( cb: TCallback, ): TCallback { const stableFnRef = React.useRef<(...args: Parameters<TCallback>) => ReturnType<TCallback>>() const cbRef = React.useRef<TCallback>(cb) cbRef.current = cb if (!stableFnRef.current) { stableFnRef.current = (...args) => cbRef.current(...args) } return stableFnRef.current as TCallback } /** * This function returns `a` if `b` is deeply equal. * If not, it will replace any deeply equal children of `b` with those of `a`. * This can be used for structural sharing between JSON values for example. */ function replaceEqualDeep(prev: any, next: any) { if (prev === next) { return prev } const array = Array.isArray(prev) && Array.isArray(next) if (array || (isPlainObject(prev) && isPlainObject(next))) { const aSize = array ? prev.length : Object.keys(prev).length const bItems = array ? next : Object.keys(next) const bSize = bItems.length const copy: any = array ? [] : {} let equalItems = 0 for (let i = 0; i < bSize; i++) { const key = array ? i : bItems[i] copy[key] = replaceEqualDeep(prev[key], next[key]) if (copy[key] === prev[key]) { equalItems++ } } return aSize === bSize && equalItems === aSize ? prev : copy } return next } // Copied from: https://github.com/jonschlinkert/is-plain-object function isPlainObject(o: any) { if (!hasObjectPrototype(o)) { return false } // If has modified constructor const ctor = o.constructor if (typeof ctor === 'undefined') { return true } // If has modified prototype const prot = ctor.prototype if (!hasObjectPrototype(prot)) { return false } // If constructor does not have an Object-specific method if (!prot.hasOwnProperty('isPrototypeOf')) { return false } // Most likely a plain Object return true } function hasObjectPrototype(o: any) { return Object.prototype.toString.call(o) === '[object Object]' } export const defaultParseSearch = parseSearchWith(JSON.parse) export const defaultStringifySearch = stringifySearchWith(JSON.stringify) export function parseSearchWith(parser: (str: string) => any) { return (searchStr: string): Record<string, any> => { if (searchStr.substring(0, 1) === '?') { searchStr = searchStr.substring(1) } let query: Record<string, unknown> = decode(searchStr) // Try to parse any query params that might be json for (let key in query) { const value = query[key] if (typeof value === 'string') { try { query[key] = parser(value) } catch (err) { // } } } return query } } export function stringifySearchWith(stringify: (search: any) => string) { return (search: Record<string, any>) => { search = { ...search } if (search) { Object.keys(search).forEach((key) => { const val = search[key] if (typeof val === 'undefined' || val === undefined) { delete search[key] } else if (val && typeof val === 'object' && val !== null) { try { search[key] = stringify(val) } catch (err) { // silent } } }) } const searchStr = encode(search as Record<string, string>) return searchStr ? `?${searchStr}` : '' } }
the_stack
import { ipairs, kpairs, loadstring, lualength, LuaObj, tostring, wipe, } from "@wowts/lua"; import { abs, huge, huge as INFINITY, max, min } from "@wowts/math"; import { AstActionNode, AstBooleanNode, AstExpressionNode, AstFunctionNode, AstGroupNode, AstIfNode, AstLuaNode, AstNode, AstNodeSnapshot, AstNodeWithParameters, AstStringNode, AstTypedFunctionNode, AstUnlessNode, AstValueNode, AstVariableNode, isAstNodeWithChildren, NamedParameters, NamedParametersOf, NodeActionResult, NodeNoResult, NodeType, NodeTypes, PositionalParameters, setResultType, } from "./ast"; import { BaseState } from "../states/BaseState"; import { ActionType } from "./best-action"; import { OvaleConditionClass } from "./condition"; import { DebugTools, Tracer } from "./debug"; import { newTimeSpan, OvaleTimeSpan, releaseTimeSpans, universe, } from "../tools/TimeSpan"; import { isNumber, isString, oneTimeMessage } from "../tools/tools"; export type ActionInfo = [ texture?: string, inRange?: boolean, cooldownStart?: number, cooldownDuration?: number, usable?: boolean, shortcut?: string, isCurrent?: boolean, enable?: boolean, type?: ActionType, id?: string | number, target?: string, resourceExtend?: number, charges?: number, castTime?: number ]; export type ActionInfoHandler = ( element: AstActionNode, atTime: number, target: string ) => NodeActionResult | NodeNoResult; type ComputerFunction<T extends AstNode> = ( element: T, atTime: number ) => AstNodeSnapshot; export class Runner { private tracer: Tracer; public serial = 0; private actionHandlers: LuaObj<ActionInfoHandler> = {}; constructor( ovaleDebug: DebugTools, private baseState: BaseState, private ovaleCondition: OvaleConditionClass ) { this.tracer = ovaleDebug.create("runner"); } public refresh() { this.serial = this.serial + 1; this.tracer.log("Advancing age to %d.", this.serial); } public postOrderCompute(element: AstNode, atTime: number): AstNodeSnapshot { let result: AstNodeSnapshot | undefined; const postOrder = element.postOrder; if (postOrder && element.result.serial !== this.serial) { this.tracer.log( "[%d] [[[ Compute '%s' post-order nodes.", element.nodeId, element.type ); let index = 1; const n = lualength(postOrder); while (index < n) { const [childNode, parentNode] = [ postOrder[index], postOrder[index + 1], ]; index = index + 2; result = this.postOrderCompute(childNode, atTime); let shortCircuit = false; if ( isAstNodeWithChildren(parentNode) && parentNode.child[1] == childNode ) { if ( parentNode.type == "if" && result.timeSpan.measure() == 0 ) { this.tracer.log( "[%d] '%s' [%d] will trigger short-circuit evaluation of parent node '%s' [%d] with zero-measure time span.", element.nodeId, childNode.type, childNode.nodeId, parentNode.type, parentNode.nodeId ); shortCircuit = true; } else if ( parentNode.type == "unless" && result.timeSpan.isUniverse() ) { this.tracer.log( "[%d] '%s' [%d] will trigger short-circuit evaluation of parent node '%s' [%d] with universe as time span.", element.nodeId, childNode.type, childNode.nodeId, parentNode.type, parentNode.nodeId ); shortCircuit = true; } else if ( parentNode.type == "logical" && parentNode.operator == "and" && result.timeSpan.measure() == 0 ) { this.tracer.log( "[%d] '%s' [%d] will trigger short-circuit evaluation of parent node '%s' [%d] with zero measure.", element.nodeId, childNode.type, childNode.nodeId, parentNode.type, parentNode.nodeId ); shortCircuit = true; } else if ( parentNode.type == "logical" && parentNode.operator == "or" && result.timeSpan.isUniverse() ) { this.tracer.log( "[%d] '%s' [%d] will trigger short-circuit evaluation of parent node '%s' [%d] with universe as time span.", element.nodeId, childNode.type, childNode.nodeId, parentNode.type, parentNode.nodeId ); shortCircuit = true; } } if (shortCircuit) { while (parentNode != postOrder[index] && index <= n) { index = index + 2; } if (index > n) { this.tracer.error( "Ran off end of postOrder node list for node %d.", element.nodeId ); } } } this.tracer.log( "[%d] ]]] Compute '%s' post-order nodes: complete.", element.nodeId, element.type ); } this.recursiveCompute(element, atTime); return element.result; } private recursiveCompute( element: AstNode, atTime: number ): AstNodeSnapshot { this.tracer.log( "[%d] >>> Computing '%s' at time=%f", element.nodeId, element.asString || element.type, atTime ); if (element.result.constant) { // Constant value this.tracer.log( "[%d] <<< '%s' returns %s with constant %s", element.nodeId, element.asString || element.type, element.result.timeSpan, this.resultToString(element.result) ); return element.result; } else if (element.result.serial == -1) { oneTimeMessage( "Recursive call is not supported in '%s'. Please fix the script.", element.asString || element.type ); return element.result; } else if (element.result.serial === this.serial) { this.tracer.log( "[%d] <<< '%s' returns %s with cached %s", element.nodeId, element.asString || element.type, element.result.timeSpan, this.resultToString(element.result) ); } else { // Set to -1 to prevent recursive call of this same node (see check above) element.result.serial = -1; const visitor = this.computeVisitors[ element.type ] as ComputerFunction<typeof element>; let result; if (visitor) { result = visitor(element, atTime); element.result.serial = this.serial; this.tracer.log( "[%d] <<< '%s' returns %s with computed %s", element.nodeId, element.asString || element.type, result.timeSpan, this.resultToString(element.result) ); } else { this.tracer.error( "[%d] Runtime error: unable to compute node of type '%s': %s.", element.nodeId, element.type, element.asString ); wipe(element.result.timeSpan); element.result.serial = this.serial; } } return element.result; } private computeBool(element: AstNode, atTime: number) { const newElement = this.compute(element, atTime); // if ( // newElement.type === "value" && // newElement.value == 0 && // (newElement.rate == 0 || newElement.rate === undefined) // ) { // // Force a value of 0 to be falsy // return EMPTY_SET; // } else { return newElement.timeSpan; // } } public registerActionInfoHandler(name: string, handler: ActionInfoHandler) { this.actionHandlers[name] = handler; } public getActionInfo( element: AstActionNode, atTime: number, namedParameters: NamedParametersOf<AstActionNode> ) { if (element.result.serial === this.serial) { this.tracer.log( "[%d] using cached result (age = %d/%d)", element.nodeId, element.result.serial, this.serial ); } else { const target = (isString(namedParameters.target) && namedParameters.target) || this.baseState.defaultTarget; const result = this.actionHandlers[element.name]( element, atTime, target ); if (result.type === "action") result.options = namedParameters; } return element.result; } private computeBoolean: ComputerFunction<AstBooleanNode> = (node) => { if (node.value) { this.getTimeSpan(node, universe); } else { this.getTimeSpan(node); } return node.result; }; private computeAction: ComputerFunction<AstActionNode> = ( node, atTime: number ) => { const nodeId = node.nodeId; const timeSpan = this.getTimeSpan(node); this.tracer.log("[%d] evaluating action: %s()", nodeId, node.name); const [, namedParameters] = this.computeParameters(node, atTime); const result = this.getActionInfo(node, atTime, namedParameters); if (result.type !== "action") return result; const action = node.name; // element.positionalParams[1]; if (result.actionTexture === undefined) { this.tracer.log("[%d] Action %s not found.", nodeId, action); wipe(timeSpan); setResultType(result, "none"); } else if (!result.actionEnable) { this.tracer.log("[%d] Action %s not enabled.", nodeId, action); wipe(timeSpan); setResultType(result, "none"); } else if (namedParameters.usable == 1 && !result.actionUsable) { this.tracer.log("[%d] Action %s not usable.", nodeId, action); wipe(timeSpan); setResultType(result, "none"); } else { if (result.castTime === undefined) { result.castTime = 0; } let start: number; if ( result.actionCooldownStart !== undefined && result.actionCooldownStart > 0 && (result.actionCharges == undefined || result.actionCharges == 0) ) { this.tracer.log( "[%d] Action %s (actionCharges=%s)", nodeId, action, result.actionCharges || "(nil)" ); if ( result.actionCooldownDuration !== undefined && result.actionCooldownDuration > 0 ) { this.tracer.log( "[%d] Action %s is on cooldown (start=%f, duration=%f).", nodeId, action, result.actionCooldownStart, result.actionCooldownDuration ); start = result.actionCooldownStart + result.actionCooldownDuration; } else { this.tracer.log( "[%d] Action %s is waiting on the GCD (start=%f).", nodeId, action, result.actionCooldownStart ); start = result.actionCooldownStart; } } else { if (result.actionCharges == undefined) { this.tracer.log( "[%d] Action %s is off cooldown.", nodeId, action ); start = atTime; } else if ( result.actionCooldownDuration !== undefined && result.actionCooldownDuration > 0 ) { this.tracer.log( "[%d] Action %s still has %f charges and is not on GCD.", nodeId, action, result.actionCharges ); start = atTime; } else { this.tracer.log( "[%d] Action %s still has %f charges but is on GCD (start=%f).", nodeId, action, result.actionCharges, result.actionCooldownStart ); start = result.actionCooldownStart || 0; } } if ( result.actionResourceExtend !== undefined && result.actionResourceExtend > 0 ) { if ( namedParameters.pool_resource !== undefined && namedParameters.pool_resource == 1 ) { this.tracer.log( "[%d] Action %s is ignoring resource requirements because it is a pool_resource action.", nodeId, action ); } else { this.tracer.log( "[%d] Action %s is waiting on resources (start=%f, extend=%f).", nodeId, action, start, result.actionResourceExtend ); start = start + result.actionResourceExtend; } } this.tracer.log( "[%d] start=%f atTime=%f", nodeId, start, atTime ); if (result.offgcd) { this.tracer.log( "[%d] Action %s is off the global cooldown.", nodeId, action ); } else if (start < atTime) { this.tracer.log( "[%d] Action %s is waiting for the global cooldown.", nodeId, action ); start = atTime; } this.tracer.log( "[%d] Action %s can start at %f.", nodeId, action, start ); timeSpan.copy(start, huge); } return result; }; private computeArithmetic: ComputerFunction<AstExpressionNode> = ( element, atTime ) => { const timeSpan = this.getTimeSpan(element); const result = element.result; const nodeA = this.compute(element.child[1], atTime); const [a, b, c, timeSpanA] = this.asValue(atTime, nodeA); const nodeB = this.compute(element.child[2], atTime); const [x, y, z, timeSpanB] = this.asValue(atTime, nodeB); timeSpanA.intersect(timeSpanB, timeSpan); if (timeSpan.measure() == 0) { this.tracer.log( "[%d] arithmetic '%s' returns %s with zero measure", element.nodeId, element.operator, timeSpan ); this.setValue(element, 0); } else { const operator = element.operator; const t = atTime; this.tracer.log( "[%d] %s+(t-%s)*%s %s %s+(t-%s)*%s", element.nodeId, a, b, c, operator, x, y, z ); let l, m, n; // The new value, origin, and rate if (!isNumber(a) || !isNumber(x)) { this.tracer.error( "[%d] Operands of arithmetic operators must be numbers", element.nodeId ); return result; } const at = a + (t - b) * c; // the A value at time t let bt = x + (t - y) * z; // The B value at time t /** * A(t) = a + (t - b)*c * = a + (t - t0 + t0 - b)*c, for all t0 * = a + (t - t0)*c + (t0 - b)*c * = [a + (t0 - b)*c] + (t - t0)*c * = A(t0) + (t - t0)*c * B(t) = B(t0) + (t - t0)*z */ if (operator == "+") { /** * A(t) + B(t) = [A(t0) + B(t0)] + (t - t0)*(c + z) */ l = at + bt; m = t; n = c + z; } else if (operator == "-") { /** * A(t) - B(t) = [A(t0) - B(t0)] + (t - t0)*(c - z) */ l = at - bt; m = t; n = c - z; } else if (operator == "*") { /** * A(t)*B(t) = [A(t0) + (t - t0)*c] * [B(t0) + (t - t0)*z] * = [A(t0)*B(t0)] + (t - t0)*[A(t0)*z + B(t0)*c] + (t - t0)^2*(c*z) * = [A(t0)*B(t0)] + (t - t0)*[A(t0)*z + B(t0)*c] + O(t^2) */ l = at * bt; m = t; n = at * z + bt * c; } else if (operator == "/") { /** * C(t) = 1/B(t) * = 1/[B(t0) - (t - t0)*z] * C(t) = C(t0) + C'(t0)*(t - t0) + O(t^2) (Taylor series at t = t0) * = 1/B(t0) + [-z/B(t0)^2]*(t - t0) + O(t^2) converges when |t - t0| < |B(t0)/z| * A(t)/B(t) = A(t0)/B(t0) + (t - t0)*{[B(t0)*c - A(t0)*z]/B(t0)^2} + O(t^2) * = A(t0)/B(t0) + (t - t0)*{[c/B(t0)] - [A(t0)/B(t0)]*[z/B(t0)]} + O(t^2) */ if (bt === 0) { if (at !== 0) { oneTimeMessage( "[%d] Division by 0 in %s", element.nodeId, element.asString ); } bt = 0.00001; } l = at / bt; m = t; n = c / bt - (at / bt) * (z / bt); let bound; if (z == 0) { bound = huge; } else { bound = abs(bt / z); } const scratch = timeSpan.intersectInterval( t - bound, t + bound ); timeSpan.copyFromArray(scratch); scratch.release(); } else if (operator == "%") { // A % B = A mod B if (c == 0 && z == 0) { l = at % bt; m = t; n = 0; } else { this.tracer.error( "[%d] Parameters of modulus operator '%' must be constants.", element.nodeId ); l = 0; m = 0; n = 0; } } else if (operator === "<?" || operator === ">?") { // A(t) <? B(t) = min(A(t), B(t)) // A(t) >? B(t) = max(A(t), B(t)) if (z === c) { // A(t) and B(t) have the same slope. l = (operator === "<?" && min(at, bt)) || max(at, bt); m = t; n = z; } else { /** * A(t) and B(t) intersect when: * A(t) = B(t) * A(t0) - (t - t0)*c = B(t0) - (t - t0)*z * (t - t0)*(z - c) = B(t0) - A(t0) * t - t0 = [B(t0) - A(t0)]/(z - c) */ const ct = (bt - at) / (z - c); if (ct <= 0) { // A(t) and B(t) intersect at or to the left of t0. const scratch = timeSpan.intersectInterval( t + ct, INFINITY ); timeSpan.copyFromArray(scratch); scratch.release(); if (z < c) { // A(t) has a greater slope than B(t). l = (operator === ">?" && at) || bt; } else { // B(t) has a greater slope than A(t). l = (operator === "<?" && at) || bt; } } else { // A(t) and B(t) intersect to the right of t0. const scratch = timeSpan.intersectInterval(0, t + ct); timeSpan.copyFromArray(scratch); scratch.release(); if (z < c) { // A(t) has a greater slope than B(t). l = (operator === "<?" && at) || bt; } else { // B(t) has a greater slope than A(t). l = (operator === ">?" && at) || bt; } } m = t; n = (l === at && c) || z; } } this.tracer.log( "[%d] arithmetic '%s' returns %s+(t-%s)*%s", element.nodeId, operator, l, m, n ); this.setValue(element, l, m, n); } return result; }; private computeCompare: ComputerFunction<AstExpressionNode> = ( element, atTime ) => { const timeSpan = this.getTimeSpan(element); const elementA = this.compute(element.child[1], atTime); const [a, b, c, timeSpanA] = this.asValue(atTime, elementA); const elementB = this.compute(element.child[2], atTime); const [x, y, z, timeSpanB] = this.asValue(atTime, elementB); timeSpanA.intersect(timeSpanB, timeSpan); if (timeSpan.measure() == 0) { this.tracer.log( "[%d] compare '%s' returns %s with zero measure", element.nodeId, element.operator, timeSpan ); } else { const operator = element.operator; this.tracer.log( "[%d] %s+(t-%s)*%s %s %s+(t-%s)*%s", element.nodeId, a, b, c, operator, x, y, z ); if (!isNumber(a) || !isNumber(x)) { if ( (operator === "==" && a !== b) || (operator === "!=" && a === b) ) { wipe(timeSpan); } return element.result; } const at = a - b * c; const bt = x - y * z; if (c == z) { if ( !( (operator == "==" && at == bt) || (operator == "!=" && at != bt) || (operator == "<" && at < bt) || (operator == "<=" && at <= bt) || (operator == ">" && at > bt) || (operator == ">=" && at >= bt) ) ) { wipe(timeSpan); } } else { const diff = bt - at; let t; if (diff == huge) { t = huge; } else { t = diff / (c - z); } t = (t > 0 && t) || 0; this.tracer.log( "[%d] intersection at t = %s", element.nodeId, t ); let scratch: OvaleTimeSpan | undefined; if ( (c > z && operator == "<") || (c > z && operator == "<=") || (c < z && operator == ">") || (c < z && operator == ">=") ) { scratch = timeSpan.intersectInterval(0, t); } else if ( (c < z && operator == "<") || (c < z && operator == "<=") || (c > z && operator == ">") || (c > z && operator == ">=") ) { scratch = timeSpan.intersectInterval(t, huge); } if (scratch) { timeSpan.copyFromArray(scratch); scratch.release(); } else { wipe(timeSpan); } } this.tracer.log( "[%d] compare '%s' returns %s", element.nodeId, operator, timeSpan ); } return element.result; }; private computeCustomFunction: ComputerFunction<AstFunctionNode> = ( element, atTime ): AstNodeSnapshot => { const timeSpan = this.getTimeSpan(element); const result = element.result; const node = element.annotation.customFunction && element.annotation.customFunction[element.name]; if (node) { if (this.tracer.debugTools.trace) this.tracer.log( "[%d]: calling custom function [%d] %s", element.nodeId, node.child[1].nodeId, element.name ); const elementA = this.compute(node.child[1], atTime); timeSpan.copyFromArray(elementA.timeSpan); if (this.tracer.debugTools.trace) this.tracer.log( "[%d]: [%d] %s is returning %s with timespan = %s", element.nodeId, node.child[1].nodeId, element.name, this.resultToString(elementA), timeSpan ); this.copyResult(result, elementA); } else { this.tracer.error(`Unable to find ${element.name}`); wipe(timeSpan); } return result; }; // private copyValue(target: AstNodeSnapshot, source: AstNodeSnapshot) { // target.value = source.value; // target.rate = source.rate; // target.origin = source.origin; // } private copyResult(target: AstNodeSnapshot, source: AstNodeSnapshot) { for (const [k] of kpairs(target)) { if ( k !== "timeSpan" && k !== "type" && k !== "serial" && source[k] === undefined ) delete target[k]; } for (const [k, v] of kpairs(source)) { // eslint-disable-next-line @typescript-eslint/no-explicit-any if ( k !== "timeSpan" && k !== "serial" && k !== "constant" && target[k] !== v ) { (target[k] as any) = v; } } } private computeFunction: ComputerFunction<AstFunctionNode> = ( element, atTime: number ) => { const timeSpan = this.getTimeSpan(element); const [positionalParams, namedParams] = this.computeParameters( element, atTime ); const [start, ending, value, origin, rate] = this.ovaleCondition.evaluateCondition( element.name, positionalParams, namedParams, atTime ); if (start !== undefined && ending !== undefined) { timeSpan.copy(start, ending); } else { wipe(timeSpan); } if (value !== undefined) { this.setValue(element, value, origin, rate); } this.tracer.log( "[%d] condition '%s' returns %s, %s, %s, %s, %s", element.nodeId, element.name, start, ending, value, origin, rate ); return element.result; }; private computeTypedFunction: ComputerFunction<AstTypedFunctionNode> = ( element, atTime: number ) => { const timeSpan = this.getTimeSpan(element); const positionalParams = this.computePositionalParameters( element, atTime ); const [start, ending, value, origin, rate] = this.ovaleCondition.call( element.name, atTime, positionalParams ); if (start !== undefined && ending !== undefined) { timeSpan.copy(start, ending); } else { wipe(timeSpan); } if (value !== undefined) { this.setValue(element, value, origin, rate); } this.tracer.log( "[%d] condition '%s' returns %s, %s, %s, %s, %s", element.nodeId, element.name, start, ending, value, origin, rate ); return element.result; }; private computeGroup: ComputerFunction<AstGroupNode> = (group, atTime) => { let bestTimeSpan, bestElement; const best = newTimeSpan(); const currentTimeSpanAfterTime = newTimeSpan(); for (const [, child] of ipairs(group.child)) { const nodeString = child.asString || child.type; this.tracer.log( "[%d] checking child '%s' [%d]", group.nodeId, nodeString, child.nodeId ); const currentElement = this.compute(child, atTime); const currentElementTimeSpan = currentElement.timeSpan; wipe(currentTimeSpanAfterTime); currentElementTimeSpan.intersectInterval( atTime, huge, currentTimeSpanAfterTime ); this.tracer.log( "[%d] child '%s' [%d]: %s", group.nodeId, nodeString, child.nodeId, currentTimeSpanAfterTime ); if (currentTimeSpanAfterTime.measure() > 0) { let currentIsBetter = false; if (best.measure() == 0 || bestElement === undefined) { this.tracer.log( "[%d] group first best is '%s' [%d]: %s", group.nodeId, nodeString, child.nodeId, currentTimeSpanAfterTime ); currentIsBetter = true; } else { const threshold = (bestElement.type === "action" && bestElement.options && bestElement.options.wait) || 0; const difference = best[1] - currentTimeSpanAfterTime[1]; if ( difference > threshold || (difference === threshold && bestElement.type === "action" && currentElement.type === "action" && !bestElement.actionUsable && currentElement.actionUsable) ) { this.tracer.log( "[%d] group new best is '%s' [%d]: %s", group.nodeId, nodeString, child.nodeId, currentElementTimeSpan ); currentIsBetter = true; } else { this.tracer.log( "[%d] group best is still %s: %s", group.nodeId, this.resultToString(group.result), best ); } } if (currentIsBetter) { best.copyFromArray(currentTimeSpanAfterTime); bestTimeSpan = currentElementTimeSpan; bestElement = currentElement; } } else { this.tracer.log( "[%d] child '%s' [%d] has zero measure, skipping", group.nodeId, nodeString, child.nodeId ); } } releaseTimeSpans(best, currentTimeSpanAfterTime); const timeSpan = this.getTimeSpan(group, bestTimeSpan); if (bestElement) { this.copyResult(group.result, bestElement); this.tracer.log( "[%d] group best action remains %s at %s", group.nodeId, this.resultToString(group.result), timeSpan ); } else { setResultType(group.result, "none"); this.tracer.log( "[%d] group no best action returns %s at %s", group.nodeId, this.resultToString(group.result), timeSpan ); } return group.result; }; private resultToString(result: AstNodeSnapshot) { if (result.type === "value") { if (result.value === undefined) { return "nil value"; } if (isString(result.value)) { return `value "${result.value}"`; } if (isNumber(result.value)) { return `value ${result.value} + (t - ${tostring( result.origin )}) * ${tostring(result.rate)}`; } return `value ${(result.value === true && "true") || "false"}`; } else if (result.type === "action") { return `action ${result.actionType || "?"} ${ result.actionId || "nil" }`; } else if (result.type === "none") { return `none`; } else if (result.type === "state") { return `state ${result.name}`; } return ""; } private computeIf: ComputerFunction<AstIfNode | AstUnlessNode> = ( element, atTime ) => { const timeSpan = this.getTimeSpan(element); const result = element.result; const timeSpanA = this.computeBool(element.child[1], atTime); let conditionTimeSpan = timeSpanA; if (element.type == "unless") { conditionTimeSpan = timeSpanA.complement(); } if (conditionTimeSpan.measure() == 0) { timeSpan.copyFromArray(conditionTimeSpan); this.tracer.log( "[%d] '%s' returns %s with zero measure", element.nodeId, element.type, timeSpan ); } else { const elementB = this.compute(element.child[2], atTime); conditionTimeSpan.intersect(elementB.timeSpan, timeSpan); this.tracer.log( "[%d] '%s' returns %s (intersection of %s and %s)", element.nodeId, element.type, timeSpan, conditionTimeSpan, elementB.timeSpan ); this.copyResult(result, elementB); } if (element.type == "unless") { conditionTimeSpan.release(); } return result; }; private computeLogical: ComputerFunction<AstExpressionNode> = ( element, atTime ) => { const timeSpan = this.getTimeSpan(element); const timeSpanA = this.computeBool(element.child[1], atTime); if (element.operator == "and") { if (timeSpanA.measure() == 0) { timeSpan.copyFromArray(timeSpanA); this.tracer.log( "[%d] logical '%s' short-circuits with zero measure left argument", element.nodeId, element.operator ); } else { const timeSpanB = this.computeBool(element.child[2], atTime); timeSpanA.intersect(timeSpanB, timeSpan); } } else if (element.operator == "not") { timeSpanA.complement(timeSpan); } else if (element.operator == "or") { if (timeSpanA.isUniverse()) { timeSpan.copyFromArray(timeSpanA); this.tracer.log( "[%d] logical '%s' short-circuits with universe as left argument", element.nodeId, element.operator ); } else { const timeSpanB = this.computeBool(element.child[2], atTime); timeSpanA.union(timeSpanB, timeSpan); } } else if (element.operator == "xor") { const timeSpanB = this.computeBool(element.child[2], atTime); const left = timeSpanA.union(timeSpanB); const scratch = timeSpanA.intersect(timeSpanB); const right = scratch.complement(); left.intersect(right, timeSpan); releaseTimeSpans(left, scratch, right); } else { wipe(timeSpan); } this.tracer.log( "[%d] logical '%s' returns %s", element.nodeId, element.operator, timeSpan ); return element.result; }; private computeLua: ComputerFunction<AstLuaNode> = (element) => { if (!element.lua) return element.result; const value = loadstring(element.lua)(); this.tracer.log("[%d] lua returns %s", element.nodeId, value); if (value !== undefined) { this.setValue(element, value); } this.getTimeSpan(element, universe); return element.result; }; private computeValue: ComputerFunction<AstValueNode> = (element) => { this.tracer.log("[%d] value is %s", element.nodeId, element.value); this.getTimeSpan(element, universe); this.setValue(element, element.value, element.origin, element.rate); return element.result; }; private computeString: ComputerFunction<AstStringNode> = (element) => { this.tracer.log("[%d] value is %s", element.nodeId, element.value); this.getTimeSpan(element, universe); this.setValue(element, element.value, undefined, undefined); return element.result; }; private computeVariable: ComputerFunction<AstVariableNode> = (element) => { // TODO This should not happen but it's to support many old cases where an undefined variable name is used // as a string this.tracer.log("[%d] value is %s", element.nodeId, element.name); this.getTimeSpan(element, universe); this.setValue(element, element.name, undefined, undefined); return element.result; }; private setValue( node: AstNode, value?: number | string, origin?: number, rate?: number ): void { const result = node.result; if (result.type !== "value") { setResultType(result, "value"); } value = value || 0; origin = origin || 0; rate = rate || 0; if ( value !== result.value || result.origin !== origin || result.rate !== rate ) { result.value = value; result.origin = origin; result.rate = rate; } } private asValue( atTime: number, node: AstNodeSnapshot ): [ value: number | string | boolean, origin: number, rate: number, timeSpan: OvaleTimeSpan ] { let value: number | string | boolean, origin: number, rate: number, timeSpan; if (node.type === "value" && node.value !== undefined) { value = node.value; origin = node.origin || 0; rate = node.rate || 0; timeSpan = node.timeSpan || universe; } else if (node.timeSpan.hasTime(atTime)) { [value, origin, rate, timeSpan] = [1, 0, 0, universe]; } else { [value, origin, rate, timeSpan] = [0, 0, 0, universe]; } return [value, origin, rate, timeSpan]; } private getTimeSpan(node: AstNode, defaultTimeSpan?: OvaleTimeSpan) { const timeSpan = node.result.timeSpan; if (defaultTimeSpan) { timeSpan.copyFromArray(defaultTimeSpan); } else { wipe(timeSpan); } return timeSpan; } public compute(element: AstNode, atTime: number): AstNodeSnapshot { return this.postOrderCompute(element, atTime); } public computeAsBoolean(element: AstNode, atTime: number) { const result = this.recursiveCompute(element, atTime); return result.timeSpan.hasTime(atTime); } public computeAsNumber(element: AstNode, atTime: number) { const result = this.recursiveCompute(element, atTime); if (result.type === "value" && isNumber(result.value)) { if (result.origin !== undefined && result.rate !== undefined) return result.value + result.rate * (atTime - result.origin); return result.value; } return 0; } public computeAsString(element: AstNode, atTime: number) { const result = this.recursiveCompute(element, atTime); if (result.type === "value" && isString(result.value)) { return result.value; } return undefined; } public computeAsValue(element: AstNode, atTime: number) { const result = this.recursiveCompute(element, atTime); if (result.type === "value") { if (!result.timeSpan.hasTime(atTime)) return undefined; return result.value; } return result.timeSpan.hasTime(atTime); } public computeParameters<T extends NodeType, P extends string>( node: AstNodeWithParameters<T, P>, atTime: number ): [PositionalParameters, NamedParameters<P>] { if ( node.cachedParams.serial === undefined || node.cachedParams.serial < this.serial ) { node.cachedParams.serial = this.serial; for (const [k, v] of ipairs(node.rawPositionalParams)) { node.cachedParams.positional[k] = this.computeAsValue(v, atTime) || false; } for (const [k, v] of kpairs(node.rawNamedParams)) { node.cachedParams.named[k] = this.computeAsValue(v, atTime); } } return [node.cachedParams.positional, node.cachedParams.named]; } public computePositionalParameters<T extends NodeType, P extends string>( node: AstNodeWithParameters<T, P>, atTime: number ): PositionalParameters { if ( node.cachedParams.serial === undefined || node.cachedParams.serial < this.serial ) { this.tracer.log("computing positional parameters"); node.cachedParams.serial = this.serial; for (const [k, v] of ipairs(node.rawPositionalParams)) { node.cachedParams.positional[k] = this.computeAsValue( v, atTime ); } } return node.cachedParams.positional; } computeVisitors: { [k in AstNode["type"]]?: ComputerFunction<NodeTypes[k]>; } = { ["action"]: this.computeAction, ["arithmetic"]: this.computeArithmetic, ["boolean"]: this.computeBoolean, ["compare"]: this.computeCompare, ["custom_function"]: this.computeCustomFunction, ["function"]: this.computeFunction, ["group"]: this.computeGroup, ["if"]: this.computeIf, ["logical"]: this.computeLogical, ["lua"]: this.computeLua, ["state"]: this.computeFunction, ["string"]: this.computeString, ["typed_function"]: this.computeTypedFunction, ["unless"]: this.computeIf, ["value"]: this.computeValue, ["variable"]: this.computeVariable, }; }
the_stack
import { makeStyles, Theme, TextField, IconButton } from '@material-ui/core'; import { FC, Fragment, ReactElement, useMemo } from 'react'; import { useTranslation } from 'react-i18next'; import CustomButton from '../../components/customButton/CustomButton'; import CustomSelector from '../../components/customSelector/CustomSelector'; import icons from '../../components/icons/Icons'; import { PRIMARY_KEY_FIELD } from '../../consts/Milvus'; import { generateId } from '../../utils/Common'; import { getCreateFieldType } from '../../utils/Format'; import { checkEmptyValid, getCheckResult } from '../../utils/Validation'; import { ALL_OPTIONS, AUTO_ID_OPTIONS, VECTOR_FIELDS_OPTIONS, } from './Constants'; import { CreateFieldsProps, CreateFieldType, DataTypeEnum, Field, } from './Types'; const useStyles = makeStyles((theme: Theme) => ({ optionalWrapper: { width: '100%', paddingRight: theme.spacing(1), maxHeight: '240px', overflowY: 'auto', }, rowWrapper: { display: 'flex', flexWrap: 'nowrap', alignItems: 'center', // only Safari 14.1+ support flexbox gap // gap: '10px', width: '100%', '& > *': { marginLeft: '10px', }, '& .dimension': { maxWidth: '160px', }, }, input: { fontSize: '14px', }, primaryInput: { maxWidth: '160px', '&:first-child': { marginLeft: 0, }, }, select: { width: '160px', marginBottom: '22px', '&:first-child': { marginLeft: 0, }, }, descInput: { minWidth: '270px', flexGrow: 1, }, btnTxt: { textTransform: 'uppercase', }, iconBtn: { marginLeft: 0, padding: 0, width: '20px', height: '20px', }, mb2: { marginBottom: theme.spacing(2), }, helperText: { lineHeight: '20px', margin: theme.spacing(0.25, 0), marginLeft: '12px', }, })); type inputType = { label: string; value: string | number | null; handleChange?: (value: string) => void; className?: string; inputClassName?: string; isReadOnly?: boolean; validate?: (value: string | number | null) => string; type?: 'number' | 'text'; }; const CreateFields: FC<CreateFieldsProps> = ({ fields, setFields, setAutoID, autoID, setFieldsValidation, }) => { const { t: collectionTrans } = useTranslation('collection'); const { t: warningTrans } = useTranslation('warning'); const classes = useStyles(); const AddIcon = icons.add; const RemoveIcon = icons.remove; const { requiredFields, optionalFields } = useMemo( () => fields.reduce( (acc, field) => { const createType: CreateFieldType = getCreateFieldType(field); const requiredTypes: CreateFieldType[] = [ 'primaryKey', 'defaultVector', ]; const key = requiredTypes.includes(createType) ? 'requiredFields' : 'optionalFields'; acc[key].push({ ...field, createType, }); return acc; }, { requiredFields: [] as Field[], optionalFields: [] as Field[], } ), [fields] ); const getSelector = ( type: 'all' | 'vector', label: string, value: number, onChange: (value: DataTypeEnum) => void ) => { return ( <CustomSelector wrapperClass={classes.select} options={type === 'all' ? ALL_OPTIONS : VECTOR_FIELDS_OPTIONS} onChange={(e: React.ChangeEvent<{ value: unknown }>) => { onChange(e.target.value as DataTypeEnum); }} value={value} variant="filled" label={label} /> ); }; const getInput = (data: inputType) => { const { label, value, handleChange = () => {}, className = '', inputClassName = '', isReadOnly = false, validate = (value: string | number | null) => ' ', type = 'text', } = data; return ( <TextField label={label} // value={value} onChange={(e: React.ChangeEvent<{ value: unknown }>) => { handleChange(e.target.value as string); }} variant="filled" className={className} InputProps={{ classes: { input: inputClassName, }, }} disabled={isReadOnly} error={validate(value) !== ' '} helperText={validate(value)} FormHelperTextProps={{ className: classes.helperText, }} defaultValue={value} type={type} /> ); }; const generateFieldName = (field: Field) => { return getInput({ label: collectionTrans('fieldName'), value: field.name, handleChange: (value: string) => { const isValid = checkEmptyValid(value); setFieldsValidation(v => v.map(item => item.id === field.id! ? { ...item, name: isValid } : item ) ); changeFields(field.id!, 'name', value); }, validate: (value: any) => { if (value === null) return ' '; const isValid = checkEmptyValid(value); return isValid ? ' ' : warningTrans('required', { name: collectionTrans('fieldName') }); }, }); }; const generateDesc = (field: Field) => { return getInput({ label: collectionTrans('description'), value: field.description, handleChange: (value: string) => changeFields(field.id!, 'description', value), className: classes.descInput, }); }; const generateDimension = (field: Field) => { const validateDimension = (value: string) => { const isPositive = getCheckResult({ value, rule: 'positiveNumber', }); const isMutiple = getCheckResult({ value, rule: 'multiple', extraParam: { multipleNumber: 8, }, }); if (field.data_type === DataTypeEnum.BinaryVector) { return { isMutiple, isPositive, }; } return { isPositive, }; }; return getInput({ label: collectionTrans('dimension'), value: field.dimension as number, handleChange: (value: string) => { const { isPositive, isMutiple } = validateDimension(value); const isValid = field.data_type === DataTypeEnum.BinaryVector ? !!isMutiple && isPositive : isPositive; changeFields(field.id!, 'dimension', `${value}`); setFieldsValidation(v => v.map(item => item.id === field.id! ? { ...item, dimension: isValid } : item ) ); }, type: 'number', validate: (value: any) => { const { isPositive, isMutiple } = validateDimension(value); if (isMutiple === false) { return collectionTrans('dimensionMutipleWarning'); } return isPositive ? ' ' : collectionTrans('dimensionPositiveWarning'); }, }); }; const changeFields = (id: string, key: string, value: any) => { const newFields = fields.map(f => { if (f.id !== id) { return f; } return { ...f, [key]: value, }; }); setFields(newFields); }; const handleAddNewField = () => { const id = generateId(); const newDefaultItem: Field = { name: null, data_type: DataTypeEnum.Int16, is_primary_key: false, description: '', isDefault: false, dimension: '128', id, }; const newValidation = { id, name: false, dimension: true, }; setFields([...fields, newDefaultItem]); setFieldsValidation(v => [...v, newValidation]); }; const handleRemoveField = (field: Field) => { const newFields = fields.filter(f => f.id !== field.id); setFields(newFields); setFieldsValidation(v => v.filter(item => item.id !== field.id)); }; const generatePrimaryKeyRow = ( field: Field, autoID: boolean ): ReactElement => { return ( <div className={`${classes.rowWrapper}`}> {getInput({ label: collectionTrans('fieldType'), value: PRIMARY_KEY_FIELD, className: classes.primaryInput, inputClassName: classes.input, isReadOnly: true, })} {generateFieldName(field)} <CustomSelector label={collectionTrans('autoId')} options={AUTO_ID_OPTIONS} value={autoID ? 'true' : 'false'} onChange={(e: React.ChangeEvent<{ value: unknown }>) => { const autoId = e.target.value === 'true'; setAutoID(autoId); }} variant="filled" wrapperClass={classes.select} /> {generateDesc(field)} </div> ); }; const generateDefaultVectorRow = (field: Field): ReactElement => { return ( <> <div className={`${classes.rowWrapper}`}> {getSelector( 'vector', collectionTrans('fieldType'), field.data_type, (value: DataTypeEnum) => changeFields(field.id!, 'data_type', value) )} {generateFieldName(field)} {generateDimension(field)} {generateDesc(field)} </div> <CustomButton onClick={handleAddNewField} className={classes.mb2}> <AddIcon /> <span className={classes.btnTxt}>{collectionTrans('newBtn')}</span> </CustomButton> </> ); }; const generateNumberRow = (field: Field): ReactElement => { return ( <div className={`${classes.rowWrapper}`}> <IconButton onClick={() => handleRemoveField(field)} classes={{ root: classes.iconBtn }} aria-label="delete" > <RemoveIcon /> </IconButton> {generateFieldName(field)} {getSelector( 'all', collectionTrans('fieldType'), field.data_type, (value: DataTypeEnum) => changeFields(field.id!, 'data_type', value) )} {generateDesc(field)} </div> ); }; const generateVectorRow = (field: Field) => { return ( <div className={`${classes.rowWrapper}`}> <IconButton classes={{ root: classes.iconBtn }} aria-label="delete"> <RemoveIcon /> </IconButton> {generateFieldName(field)} {getSelector( 'all', collectionTrans('fieldType'), field.data_type, (value: DataTypeEnum) => changeFields(field.id!, 'data_type', value) )} {generateDimension(field)} {generateDesc(field)} </div> ); }; const generateRequiredFieldRow = (field: Field, autoID: boolean) => { // required type is primaryKey or defaultVector if (field.createType === 'primaryKey') { return generatePrimaryKeyRow(field, autoID); } // use defaultVector as default return type return generateDefaultVectorRow(field); }; const generateOptionalFieldRow = (field: Field) => { // optional type is vector or number if (field.createType === 'vector') { return generateVectorRow(field); } // use number as default createType return generateNumberRow(field); }; return ( <> {requiredFields.map((field, index) => ( <Fragment key={index}> {generateRequiredFieldRow(field, autoID)} </Fragment> ))} <div className={classes.optionalWrapper}> {optionalFields.map((field, index) => ( <Fragment key={index}>{generateOptionalFieldRow(field)}</Fragment> ))} </div> </> ); }; export default CreateFields;
the_stack
import { ArrayHelper, Convert, StringHelper } from "../ExtensionMethods"; import { EwsServiceXmlWriter } from "../Core/EwsServiceXmlWriter"; import { ExchangeService } from "../Core/ExchangeService"; import { FolderPermissionLevel } from "../Enumerations/FolderPermissionLevel"; import { FolderPermissionReadAccess } from "../Enumerations/FolderPermissionReadAccess"; import { IRefParam } from "../Interfaces/IRefParam"; import { IndexerWithEnumKey } from "../AltDictionary"; import { LazyMember } from "../Core/LazyMember"; import { PermissionScope } from "../Enumerations/PermissionScope"; import { ServiceLocalException } from "../Exceptions/ServiceLocalException"; import { ServiceValidationException } from "../Exceptions/ServiceValidationException"; import { StandardUser } from "../Enumerations/StandardUser"; import { Strings } from "../Strings"; import { UserId } from "./UserId"; import { XmlElementNames } from "../Core/XmlElementNames"; import { XmlNamespace } from "../Enumerations/XmlNamespace"; import { ComplexProperty } from "./ComplexProperty"; /** * Represents a permission on a folder. * * @sealed */ export class FolderPermission extends ComplexProperty { private static defaultPermissions: LazyMember<IndexerWithEnumKey<FolderPermissionLevel, FolderPermission>> = new LazyMember<IndexerWithEnumKey<FolderPermissionLevel, FolderPermission>>( () => { var result: IndexerWithEnumKey<FolderPermissionLevel, FolderPermission> = {};// new Dictionary<FolderPermissionLevel, FolderPermission>(); var permission: FolderPermission = new FolderPermission(); permission.canCreateItems = false; permission.canCreateSubFolders = false; permission.deleteItems = PermissionScope.None; permission.editItems = PermissionScope.None; permission.isFolderContact = false; permission.isFolderOwner = false; permission.isFolderVisible = false; permission.readItems = FolderPermissionReadAccess.None; result[FolderPermissionLevel.None] = permission; permission = new FolderPermission(); permission.canCreateItems = true; permission.canCreateSubFolders = false; permission.deleteItems = PermissionScope.None; permission.editItems = PermissionScope.None; permission.isFolderContact = false; permission.isFolderOwner = false; permission.isFolderVisible = true; permission.readItems = FolderPermissionReadAccess.None; result[FolderPermissionLevel.Contributor] = permission; permission = new FolderPermission(); permission.canCreateItems = false; permission.canCreateSubFolders = false; permission.deleteItems = PermissionScope.None; permission.editItems = PermissionScope.None; permission.isFolderContact = false; permission.isFolderOwner = false; permission.isFolderVisible = true; permission.readItems = FolderPermissionReadAccess.FullDetails; result[FolderPermissionLevel.Reviewer] = permission; permission = new FolderPermission(); permission.canCreateItems = true; permission.canCreateSubFolders = false; permission.deleteItems = PermissionScope.Owned; permission.editItems = PermissionScope.None; permission.isFolderContact = false; permission.isFolderOwner = false; permission.isFolderVisible = true; permission.readItems = FolderPermissionReadAccess.FullDetails; result[FolderPermissionLevel.NoneditingAuthor] = permission; permission = new FolderPermission(); permission.canCreateItems = true; permission.canCreateSubFolders = false; permission.deleteItems = PermissionScope.Owned; permission.editItems = PermissionScope.Owned; permission.isFolderContact = false; permission.isFolderOwner = false; permission.isFolderVisible = true; permission.readItems = FolderPermissionReadAccess.FullDetails; result[FolderPermissionLevel.Author] = permission; permission = new FolderPermission(); permission.canCreateItems = true; permission.canCreateSubFolders = true; permission.deleteItems = PermissionScope.Owned; permission.editItems = PermissionScope.Owned; permission.isFolderContact = false; permission.isFolderOwner = false; permission.isFolderVisible = true; permission.readItems = FolderPermissionReadAccess.FullDetails; result[FolderPermissionLevel.PublishingAuthor] = permission; permission = new FolderPermission(); permission.canCreateItems = true; permission.canCreateSubFolders = false; permission.deleteItems = PermissionScope.All; permission.editItems = PermissionScope.All; permission.isFolderContact = false; permission.isFolderOwner = false; permission.isFolderVisible = true; permission.readItems = FolderPermissionReadAccess.FullDetails; result[FolderPermissionLevel.Editor] = permission; permission = new FolderPermission(); permission.canCreateItems = true; permission.canCreateSubFolders = true; permission.deleteItems = PermissionScope.All; permission.editItems = PermissionScope.All; permission.isFolderContact = false; permission.isFolderOwner = false; permission.isFolderVisible = true; permission.readItems = FolderPermissionReadAccess.FullDetails; result[FolderPermissionLevel.PublishingEditor] = permission; permission = new FolderPermission(); permission.canCreateItems = true; permission.canCreateSubFolders = true; permission.deleteItems = PermissionScope.All; permission.editItems = PermissionScope.All; permission.isFolderContact = true; permission.isFolderOwner = true; permission.isFolderVisible = true; permission.readItems = FolderPermissionReadAccess.FullDetails; result[FolderPermissionLevel.Owner] = permission; permission = new FolderPermission(); permission.canCreateItems = false; permission.canCreateSubFolders = false; permission.deleteItems = PermissionScope.None; permission.editItems = PermissionScope.None; permission.isFolderContact = false; permission.isFolderOwner = false; permission.isFolderVisible = false; permission.readItems = FolderPermissionReadAccess.TimeOnly; result[FolderPermissionLevel.FreeBusyTimeOnly] = permission; permission = new FolderPermission(); permission.canCreateItems = false; permission.canCreateSubFolders = false; permission.deleteItems = PermissionScope.None; permission.editItems = PermissionScope.None; permission.isFolderContact = false; permission.isFolderOwner = false; permission.isFolderVisible = false; permission.readItems = FolderPermissionReadAccess.TimeAndSubjectAndLocation; result[FolderPermissionLevel.FreeBusyTimeAndSubjectAndLocation] = permission; return result; }); /** * Variants of pre-defined permission levels that Outlook also displays with the same levels. */ private static levelVariants: LazyMember<FolderPermission[]> = new LazyMember<FolderPermission[]>( () => { var results: FolderPermission[] = [];// new List<FolderPermission>(); var permissionNone: FolderPermission = FolderPermission.defaultPermissions.Member[FolderPermissionLevel.None]; var permissionOwner: FolderPermission = FolderPermission.defaultPermissions.Member[FolderPermissionLevel.Owner]; // PermissionLevelNoneOption1 var permission: FolderPermission = permissionNone.Clone(); permission.isFolderVisible = true; results.push(permission); // PermissionLevelNoneOption2 permission = permissionNone.Clone(); permission.isFolderContact = true; results.push(permission); // PermissionLevelNoneOption3 permission = permissionNone.Clone(); permission.isFolderContact = true; permission.isFolderVisible = true; results.push(permission); // PermissionLevelOwnerOption1 permission = permissionOwner.Clone(); permission.isFolderContact = false; results.push(permission); return results; }); private userId: UserId; private canCreateItems: boolean; private canCreateSubFolders: boolean; private isFolderOwner: boolean; private isFolderVisible: boolean; private isFolderContact: boolean; private editItems: PermissionScope; private deleteItems: PermissionScope; private readItems: FolderPermissionReadAccess; private permissionLevel: FolderPermissionLevel; /** * Gets the Id of the user the permission applies to. */ get UserId(): UserId { return this.userId; } set UserId(value) { if (this.userId != null) { ArrayHelper.RemoveEntry(this.userId.OnChange, this.PropertyChanged); } this.SetFieldValue<UserId>({ getValue: () => this.userId, setValue: (id) => this.userId = id }, value); if (this.userId != null) { this.userId.OnChange.push(this.PropertyChanged.bind(this)); } } /** * Gets or sets a value indicating whether the user can create new items. */ get CanCreateItems(): boolean { return this.canCreateItems; } set CanCreateItems(value) { this.SetFieldValue<boolean>({ getValue: () => this.canCreateItems, setValue: (data) => this.canCreateItems = data }, value); this.AdjustPermissionLevel(); } /** * Gets or sets a value indicating whether the user can create sub-folders. */ get CanCreateSubFolders(): boolean { return this.canCreateSubFolders; } set CanCreateSubFolders(value) { this.SetFieldValue<boolean>({ getValue: () => this.canCreateSubFolders, setValue: (data) => this.canCreateSubFolders = data }, value); this.AdjustPermissionLevel(); } /** * Gets or sets a value indicating whether the user owns the folder. */ get IsFolderOwner(): boolean { return this.isFolderOwner; } set IsFolderOwner(value) { this.SetFieldValue<boolean>({ getValue: () => this.isFolderOwner, setValue: (data) => this.isFolderOwner = data }, value); this.AdjustPermissionLevel(); } /** * Gets or sets a value indicating whether the folder is visible to the user. */ get IsFolderVisible(): boolean { return this.isFolderVisible; } set IsFolderVisible(value) { this.SetFieldValue<boolean>({ getValue: () => this.isFolderVisible, setValue: (data) => this.isFolderVisible = data }, value); this.AdjustPermissionLevel(); } /** * Gets or sets a value indicating whether the user is a contact for the folder. */ get IsFolderContact(): boolean { return this.isFolderContact; } set IsFolderContact(value) { this.SetFieldValue<boolean>({ getValue: () => this.isFolderContact, setValue: (data) => this.isFolderContact = data }, value); this.AdjustPermissionLevel(); } /** * Gets or sets a value indicating if/how the user can edit existing items. */ get EditItems(): PermissionScope { return this.editItems; } set EditItems(value) { this.SetFieldValue<PermissionScope>({ getValue: () => this.editItems, setValue: (data) => this.editItems = data }, value); this.AdjustPermissionLevel(); } /** * Gets or sets a value indicating if/how the user can delete existing items. */ get DeleteItems(): PermissionScope { return this.deleteItems; } set DeleteItems(value) { this.SetFieldValue<PermissionScope>({ getValue: () => this.deleteItems, setValue: (data) => this.deleteItems = data }, value); this.AdjustPermissionLevel(); } /** * Gets or sets the read items access permission. */ get ReadItems(): FolderPermissionReadAccess { return this.readItems; } set ReadItems(value) { this.SetFieldValue<FolderPermissionReadAccess>({ getValue: () => this.readItems, setValue: (data) => this.readItems = data }, value); this.AdjustPermissionLevel(); } /** * Gets or sets the permission level. */ get PermissionLevel(): FolderPermissionLevel { return this.permissionLevel; } set PermissionLevel(value) { if (this.permissionLevel != value) { if (value == FolderPermissionLevel.Custom) { throw new ServiceLocalException(Strings.CannotSetPermissionLevelToCustom); } this.AssignIndividualPermissions(FolderPermission.defaultPermissions.Member[value]); this.SetFieldValue<FolderPermissionLevel>({ getValue: () => this.permissionLevel, setValue: (data) => this.permissionLevel = data }, value); } } /** * Gets the permission level that Outlook would display for this folder permission. */ get DisplayPermissionLevel(): FolderPermissionLevel { // If permission level is set to Custom, see if there's a variant // that Outlook would map to the same permission level. if (this.permissionLevel == FolderPermissionLevel.Custom) { for (var variant of FolderPermission.levelVariants.Member) { if (this.IsEqualTo(variant)) { return variant.PermissionLevel; } } } return this.permissionLevel; } /** * Initializes a new instance of the **FolderPermission** class. */ constructor(); /** * Initializes a new instance of the **FolderPermission** class. * * @param {UserId} userId The Id of the user the permission applies to. * @param {FolderPermissionLevel} permissionLevel The level of the permission. */ constructor(userId: UserId, permissionLevel: FolderPermissionLevel); /** * Initializes a new instance of the **FolderPermission** class. * * @param {string} primarySmtpAddress The primary SMTP address of the user the permission applies to. * @param {FolderPermissionLevel} permissionLevel The level of the permission. */ constructor(primarySmtpAddress: string, permissionLevel: FolderPermissionLevel); /** * Initializes a new instance of the **FolderPermission** class. * * @param {StandardUser} standardUser The standard user the permission applies to. * @param {FolderPermissionLevel} permissionLevel The level of the permission. */ constructor(standardUser: StandardUser, permissionLevel: FolderPermissionLevel); constructor(userIdOrStandardUserOrSmtpAddress?: UserId | StandardUser | string, permissionLevel?: FolderPermissionLevel) { super(); if (typeof userIdOrStandardUserOrSmtpAddress !== 'undefined' && typeof permissionLevel === 'undefined') throw new Error("FolderPermission - Constructor: permission level parameter cant be undefined or null when userid/smtpaddress/standarduser is provided in first place."); if (typeof userIdOrStandardUserOrSmtpAddress === 'undefined') { this.userId = new UserId(); } else { this.permissionLevel = permissionLevel; if (typeof userIdOrStandardUserOrSmtpAddress === 'string' || typeof userIdOrStandardUserOrSmtpAddress === 'number') { this.userId = new UserId(userIdOrStandardUserOrSmtpAddress); } else { this.userId = userIdOrStandardUserOrSmtpAddress; } } } /** * Determines the permission level of this folder permission based on its individual settings, and sets the PermissionLevel property accordingly. */ private AdjustPermissionLevel(): void { for (var key in FolderPermission.defaultPermissions.Member) { var value = FolderPermission.defaultPermissions.Member[key]; if (this.IsEqualTo(value)) { this.permissionLevel = <FolderPermissionLevel><any>key; return; } } this.permissionLevel = FolderPermissionLevel.Custom; } /** * Copies the values of the individual permissions of the specified folder permission to this folder permissions. * * @param {FolderPermission} permission The folder permission to copy the values from. */ private AssignIndividualPermissions(permission: FolderPermission): void { this.canCreateItems = permission.CanCreateItems; this.canCreateSubFolders = permission.CanCreateSubFolders; this.isFolderContact = permission.IsFolderContact; this.isFolderOwner = permission.IsFolderOwner; this.isFolderVisible = permission.IsFolderVisible; this.editItems = permission.EditItems; this.deleteItems = permission.DeleteItems; this.readItems = permission.ReadItems; } /** * Create a copy of this FolderPermission instance. * * @return {FolderPermission} Clone of this instance. */ private Clone(): FolderPermission { var res = new FolderPermission(); res.canCreateItems = this.canCreateItems; res.canCreateSubFolders = this.canCreateSubFolders; res.deleteItems = this.deleteItems; res.editItems = this.editItems; res.isFolderContact = this.isFolderContact; res.isFolderOwner = this.isFolderOwner; res.isFolderVisible = this.isFolderVisible; res.permissionLevel = this.permissionLevel; res.readItems = this.readItems; res.userId = this.userId; return res; } /** * Determines whether the specified folder permission is the same as this one. The comparison does not take UserId and PermissionLevel into consideration. * * @param {FolderPermission} permission The folder permission to compare with this folder permission. * @return {boolean} True is the specified folder permission is equal to this one, false otherwise. */ private IsEqualTo(permission: FolderPermission): boolean { return this.CanCreateItems == permission.CanCreateItems && this.CanCreateSubFolders == permission.CanCreateSubFolders && this.IsFolderContact == permission.IsFolderContact && this.IsFolderVisible == permission.IsFolderVisible && this.IsFolderOwner == permission.IsFolderOwner && this.EditItems == permission.EditItems && this.DeleteItems == permission.DeleteItems && this.ReadItems == permission.ReadItems; } /** * @internal Loads service object from XML. * * @param {any} jsObject Json Object converted from XML. * @param {ExchangeService} service The service. */ LoadFromXmlJsObject(jsObject: any/*JsonObject*/, service: ExchangeService): void { for (var key in jsObject) { switch (key) { case XmlElementNames.UserId: this.UserId = new UserId(); this.UserId.LoadFromXmlJsObject(jsObject[key], service); break; case XmlElementNames.CanCreateItems: this.canCreateItems = Convert.toBool(jsObject[key]); break; case XmlElementNames.CanCreateSubFolders: this.canCreateSubFolders = Convert.toBool(jsObject[key]); break; case XmlElementNames.IsFolderOwner: this.isFolderOwner = Convert.toBool(jsObject[key]); break; case XmlElementNames.IsFolderVisible: this.isFolderVisible = Convert.toBool(jsObject[key]); break; case XmlElementNames.IsFolderContact: this.isFolderContact = Convert.toBool(jsObject[key]); break; case XmlElementNames.EditItems: //debugger;//check for assignable enumeration type this.editItems = <PermissionScope><any>PermissionScope[jsObject[key]]; break; case XmlElementNames.DeleteItems: //debugger;//check for assignable enumeration type this.deleteItems = <PermissionScope><any>PermissionScope[jsObject[key]]; break; case XmlElementNames.ReadItems: //debugger;//check for assignable enumeration type this.readItems = <FolderPermissionReadAccess><any>FolderPermissionReadAccess[jsObject[key]] break; case XmlElementNames.PermissionLevel: case XmlElementNames.CalendarPermissionLevel: //debugger;//check for assignable enumeration type this.permissionLevel = <FolderPermissionLevel><any>FolderPermissionLevel[jsObject[key]]; break; default: break; } } this.AdjustPermissionLevel(); } /** * Property was changed. * * @param {ComplexProperty} complexProperty The complex property. */ private PropertyChanged(complexProperty: ComplexProperty): void { this.Changed(); } //Validate(isCalendarFolder: boolean, permissionIndex: number): void { throw new Error("FolderPermission.ts - Validate : Not implemented."); } /** * @internal Validates this instance. * ## parameters not optional: Typescript inheritance issue if not set as optional in code. * * @param {boolean} isCalendarFolder if set to true calendar permissions are allowed. * @param {number} permissionIndex Index of the permission. */ Validate(isCalendarFolder?: boolean, permissionIndex?: number): void { //ref: inheritance issue if parameters are not optional if (typeof isCalendarFolder === 'undefined' || typeof permissionIndex === 'undefined') throw new Error("FolderPermission - Validate: incorrect call to validate, without the isCalendar or permissionIndex pearameter. this signature makes it optional to comply with typescript inheritance system and to avoid compiletime error."); // Check UserId if (!this.UserId.IsValid()) { throw new ServiceValidationException( StringHelper.Format( Strings.FolderPermissionHasInvalidUserId, permissionIndex)); } // If this permission is to be used for a non-calendar folder make sure that read access and permission level aren't set to Calendar-only values if (!isCalendarFolder) { if ((this.readItems == FolderPermissionReadAccess.TimeAndSubjectAndLocation) || (this.readItems == FolderPermissionReadAccess.TimeOnly)) { throw new ServiceLocalException( StringHelper.Format( Strings.ReadAccessInvalidForNonCalendarFolder, this.readItems)); } if ((this.permissionLevel == FolderPermissionLevel.FreeBusyTimeAndSubjectAndLocation) || (this.permissionLevel == FolderPermissionLevel.FreeBusyTimeOnly)) { throw new ServiceLocalException( StringHelper.Format( Strings.PermissionLevelInvalidForNonCalendarFolder, FolderPermissionLevel[this.permissionLevel])); } } } /** * @internal Writes elements to XML. * * @param {EwsServiceXmlWriter} writer The writer. * @param {boolean} isCalendarFolder If true, this permission is for a calendar folder. */ WriteElementsToXml(writer: EwsServiceXmlWriter, isCalendarFolder: boolean = false): void { if (this.UserId != null) { this.UserId.WriteToXml(writer, XmlElementNames.UserId); } if (this.PermissionLevel == FolderPermissionLevel.Custom) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.CanCreateItems, this.CanCreateItems); writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.CanCreateSubFolders, this.CanCreateSubFolders); writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.IsFolderOwner, this.IsFolderOwner); writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.IsFolderVisible, this.IsFolderVisible); writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.IsFolderContact, this.IsFolderContact); writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.EditItems, this.EditItems); writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.DeleteItems, this.DeleteItems); writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.ReadItems, this.ReadItems); } writer.WriteElementValue( XmlNamespace.Types, isCalendarFolder ? XmlElementNames.CalendarPermissionLevel : XmlElementNames.PermissionLevel, FolderPermissionLevel[this.PermissionLevel]); } /** * @internal Writes to XML. * * @param {EwsServiceXmlWriter} writer The writer. * @param {string} xmlElementName Name of the XML element. * @param {XmlNamespace} xmlNamespace * @param {isCalendarFolder} isCalendarFolder If true, this permission is for a calendar folder. */ WriteToXml(writer: EwsServiceXmlWriter, xmlElementName: string, xmlNamespace?: XmlNamespace, isCalendarFolder: boolean = false): void { //ref: XmlNamespace - incorrect inheritance error with typesctipt in folderpermission class if removed xmlnamespace parameter writer.WriteStartElement(this.Namespace, xmlElementName); this.WriteAttributesToXml(writer); this.WriteElementsToXml(writer, isCalendarFolder); writer.WriteEndElement(); } }
the_stack
type ComponentValueCallback<T> = (key: string, val?: T) => T; type SliderOptions = { min?: number; max?: number; step?: number; formatter?: (x: number) => string; } type SwitchButton = HTMLButtonElement & { index: number }; type AlignDir = "up" | "down" | "left" | "right" | "none"; export default class Components { static createSettingOverlay(...elements: Node[]) { let node = document.createElement("div"); node.style.display = "block"; node.innerHTML = ` <div class="sgf-settings-overlay"> <div class="sgf-settings-modal" tabindex="1" role="dialog"> <div class="sgf-settings-container"> <div class="sgf-settings-header"> <h1 class="sgf-header-title" as="h1">Soggfy settings</h1> <button aria-label="Close" class="sgf-settings-closeBtn"> <svg width="18" height="18" viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg"> <title>Close</title> <path d="M31.098 29.794L16.955 15.65 31.097 1.51 29.683.093 15.54 14.237 1.4.094-.016 1.508 14.126 15.65-.016 29.795l1.414 1.414L15.54 17.065l14.144 14.143" fill="currentColor" fill-rule="evenodd"></path> </svg> </button> </div> <div class="sgf-settings-elements"> </div> </div> </div> </div>`; node.querySelector(".sgf-settings-elements").append(...elements); //@ts-ignore node.querySelector(".sgf-settings-closeBtn").onclick = () => node.remove(); let overlay: HTMLElement = node.querySelector(".sgf-settings-overlay"); let container: HTMLElement = node.querySelector(".sgf-settings-container"); //fix for an annoying behavior in onclick(): //onclick() is fired if we click on the container and then release with the cursor in the overlay. //container.onclick = (ev) => ev.stopPropagation(); (doesn't do shit) //(I keep wondering if libraries like react deal with things like these painlessly lol) let clickedOut = false; overlay.onmousedown = (ev) => { if (!container.contains(ev.target as Node)) { clickedOut = true; } }; overlay.onmouseup = (ev) => { if (!container.contains(ev.target as Node) && clickedOut) { node.remove(); } }; return node; } static addTopbarButton(title: string, icon: string, callback: () => void) { let backButton = document.querySelector(".Root__top-bar").querySelector("button"); let topbarContainer = backButton.parentElement; let button = document.createElement("button"); button.className = backButton.classList[0]; button.innerHTML = icon; button.onclick = callback; topbarContainer.append(button); return button; } static toggle(key: string, callback: ComponentValueCallback<boolean>) { let node = document.createElement("input"); node.className = "sgf-toggle-switch"; node.type = "checkbox"; node.checked = callback(key); node.onchange = () => callback(key, node.checked); return node; } static select<T>(key: string, options: Record<string, T> | string[], callback: ComponentValueCallback<T>) { let node = document.createElement("select"); node.className = "sgf-select"; let entries = Array.isArray(options) ? options.map(v => [v, v]) : Object.entries(options); let defaultVal = callback(key); for (let i = 0; i < entries.length; i++) { let [k, v] = entries[i]; let opt = document.createElement("option"); opt.innerText = k; node.appendChild(opt); if (v === defaultVal) { node.selectedIndex = i; } } node.onchange = () => { callback(key, entries[node.selectedIndex][1] as any); }; return node; } static textInput(key: string, callback: ComponentValueCallback<string>) { let node = document.createElement("input"); node.className = "sgf-text-input"; node.value = callback(key); node.onchange = () => callback(key, node.value); return node; } static slider(key: string, opts: SliderOptions, callback: ComponentValueCallback<number>) { let initialValue = callback(key); let formatter = opts?.formatter ?? (x => x.toString()); let node = document.createElement("div"); node.className = "sgf-slider-wrapper"; node.innerHTML = ` <input class="sgf-slider-label"></input> <input class="sgf-slider" type="range" min="${opts?.min ?? 0}" max="${opts?.max ?? 100}" step="${opts?.step ?? 1}" value="${initialValue}"> `; let slider: HTMLInputElement = node.querySelector(".sgf-slider"); let label: HTMLInputElement = node.querySelector(".sgf-slider-label"); label.value = formatter(initialValue); slider.oninput = () => label.value = formatter(slider.valueAsNumber); //remove custom format when editing via the textbox label.oninput = () => slider.value = label.value; label.onfocus = () => label.value = callback(key).toString(); label.onblur = () => label.value = formatter(callback(key)); label.onchange = () => callback(key, parseFloat(label.value)); slider.onchange = () => callback(key, parseFloat(slider.value)); return node; } static collapsible(desc: string, ...elements: Node[]) { let node = document.createElement("details"); node.className = "sgf-collapsible"; node.innerHTML = `<summary>${desc}</summary>`; node.append(...elements); return node; } static tagButton(text: string, callback?: { (): void; }) { let node = document.createElement("button"); node.className = "sgf-tag-button"; node.innerText = text; node.onclick = callback; return node; } static button(text: string = null, child: string = null, callback: { (): void; }) { let node = document.createElement("button"); node.className = "sgf-button"; if (child) node.appendChild(this.parse(child)); if (text) node.appendChild(new Text(text)); node.onclick = callback; return node; } static switchField(key: string, options: (string | Node | DocumentFragment)[], callback: ComponentValueCallback<number>) { let node = document.createElement("div"); node.className = "sgf-switch-field"; let activeIndex = callback(key, undefined); let onButtonClick = (button: SwitchButton) => { if (button.index === activeIndex) return; activeIndex = button.index; for (let btn of node.children) { btn.removeAttribute("active"); } button.setAttribute("active", ""); callback(key, button.index); }; for (let i = 0; i < options.length; i++) { let button = document.createElement("button") as SwitchButton; button.style.width = (100.0 / options.length) + "%"; button.index = i; button.onclick = () => onButtonClick(button); let opt = options[i]; button.appendChild( typeof opt === "string" ? document.createTextNode(opt as string) : opt as Node ); node.appendChild(button); } node.children[activeIndex].setAttribute("active", ""); return node; } static notification(content: (string | Node), anchor: Element, dir: AlignDir, showArrow = true, fadeDelay = 2.5) { let node = document.createElement("span"); node.className = `sgf-notification-bubble sgf-notification-bubble-${showArrow ? dir : "none"}`; if (typeof content === "string") { node.innerText = content; } else { node.appendChild(content); } node.style.setProperty("--anim-delay", fadeDelay + "s"); //getBoundingClientRect() won't work before adding to dom anchor.parentElement.appendChild(node); node.onanimationend = () => node.remove(); let rect = node.getBoundingClientRect(); let anchorRect = anchor.getBoundingClientRect(); let [x, y, aw, ah] = [anchorRect.left, anchorRect.top, anchorRect.width, anchorRect.height]; let cx = (aw - rect.width) / 2; let cy = (ah - rect.height) / 2; if (dir === "none") dir = "up"; if (dir === "up") { x += cx; y -= rect.height + 7; } if (dir === "down") { x += cx; y += ah + 7; } if (dir === "left") { x -= rect.width + 7; y += cy; } if (dir === "right") { x += aw + 7; y += cy; } node.style.left = x + "px"; node.style.top = y + "px"; return node; } static title(text: string, tagName: "h1" | "h2" | "h3" = "h2") { let node = document.createElement(tagName); node.innerText = text; return node; } static row(desc: string, action: any) { let node = document.createElement("div"); node.className = "sgf-setting-row"; node.innerHTML = ` <label class="col description">${desc}</label> <div class="col action"></div>`; node.querySelector(".action").appendChild(action); return node; } static rows(...elements: (string | Node)[]) { let node = document.createElement("div"); node.className = "sgf-setting-rows"; node.append(...elements); return node; } static colDesc(text: string) { let node = document.createElement("label"); node.className = "col description"; node.innerText = text; return node; } static colSection(...elements: Node[]) { let node = document.createElement("div"); node.className = "sgf-setting-cols"; node.append(...elements); return node; } static section(desc: string, ...elements: Node[]) { let node = document.createElement("div"); node.className = "sgf-setting-section"; node.innerHTML = `<h2>${desc}</h2>`; node.append(...elements); return node; } static subSection(...elements: Node[]) { let node = document.createElement("div"); node.className = "sgf-setting-section"; node.style.marginLeft = "20px"; node.append(...elements); return node; } static parse(html: string): DocumentFragment | Node { var template = document.createElement("template"); template.innerHTML = html.trim(); //trim(): Never return a text node of whitespace as the result return template.content.childElementCount > 1 ? template.content : template.content.firstChild; } }
the_stack
import * as tf from '../../index'; import {ALL_ENVS, describeWithFlags} from '../../jasmine_util'; import {expectArraysEqual} from '../../test_util'; async function expectResult( result: tf.NamedTensorMap, nGrams: string[], nGramsSplits: number[]) { expectArraysEqual(await result.nGrams.data(), nGrams); expectArraysEqual(await result.nGramsSplits.data(), nGramsSplits); expect(result.nGrams.shape).toEqual([nGrams.length]); expect(result.nGramsSplits.shape).toEqual([nGramsSplits.length]); expect(result.nGrams.dtype).toEqual('string'); expect(result.nGramsSplits.dtype).toEqual('int32'); } describeWithFlags('stringNGrams', ALL_ENVS, () => { it('padded trigrams', async () => { // Batch items are: // 0: "a", "b", "c", "d" // 1: "e", "f" const result = tf.string.stringNGrams( ['a', 'b', 'c', 'd', 'e', 'f'], tf.tensor1d([0, 4, 6], 'int32'), '|', [3], 'LP', 'RP', -1, false); const nGrams = [ 'LP|LP|a', 'LP|a|b', 'a|b|c', 'b|c|d', 'c|d|RP', 'd|RP|RP', // 0 'LP|LP|e', 'LP|e|f', 'e|f|RP', 'f|RP|RP' // 1 ]; const nGramsSplits = [0, 6, 10]; await expectResult(result, nGrams, nGramsSplits); }); it('padded bigrams and trigrams', async () => { // Batch items are: // 0: "a", "b", "c", "d" // 1: "e", "f" const result = tf.string.stringNGrams( ['a', 'b', 'c', 'd', 'e', 'f'], tf.tensor1d([0, 4, 6], 'int32'), '|', [2, 3], 'LP', 'RP', -1, false); const nGrams = [ 'LP|a', 'a|b', 'b|c', 'c|d', 'd|RP', 'LP|LP|a', 'LP|a|b', 'a|b|c', 'b|c|d', 'c|d|RP', 'd|RP|RP', // 0 'LP|e', 'e|f', 'f|RP', 'LP|LP|e', 'LP|e|f', 'e|f|RP', 'f|RP|RP' // 1 ]; const nGramsSplits = [0, 11, 18]; await expectResult(result, nGrams, nGramsSplits); }); it('padded bigrams', async () => { // Batch items are: // 0: "a", "b", "c", "d" // 1: "e", "f" const result = tf.string.stringNGrams( ['a', 'b', 'c', 'd', 'e', 'f'], tf.tensor1d([0, 4, 6], 'int32'), '|', [2], 'LP', 'RP', -1, false); const nGrams = [ 'LP|a', 'a|b', 'b|c', 'c|d', 'd|RP', // 0 'LP|e', 'e|f', 'f|RP' // 1 ]; const nGramsSplits = [0, 5, 8]; await expectResult(result, nGrams, nGramsSplits); }); it('padding is at most nGramSize - 1', async () => { // Batch items are: // 0: "a", "b", "c", "d" // 1: "e", "f" const result = tf.string.stringNGrams( ['a', 'b', 'c', 'd', 'e', 'f'], tf.tensor1d([0, 4, 6], 'int32'), '|', [2], 'LP', 'RP', 4, false); const nGrams = [ 'LP|a', 'a|b', 'b|c', 'c|d', 'd|RP', // 0 'LP|e', 'e|f', 'f|RP' // 1 ]; const nGramsSplits = [0, 5, 8]; await expectResult(result, nGrams, nGramsSplits); }); it('padded unigram and bigrams', async () => { // Batch items are: // 0: "a", "b", "c", "d" // 1: "e", "f" const result = tf.string.stringNGrams( ['a', 'b', 'c', 'd', 'e', 'f'], tf.tensor1d([0, 4, 6], 'int32'), '|', [1, 2], 'LP', 'RP', -1, false); const nGrams = [ 'a', 'b', 'c', 'd', 'LP|a', 'a|b', 'b|c', 'c|d', 'd|RP', // 0 'e', 'f', 'LP|e', 'e|f', 'f|RP' // 1 ]; const nGramsSplits = [0, 9, 14]; await expectResult(result, nGrams, nGramsSplits); }); it('overlapping padded nGrams', async () => { // This test validates that n-grams with both left and right padding in a // single ngram token are created correctly. // Batch items are: // 0: "a" // 1: "b", "c", "d" // 2: "e", "f" const result = tf.string.stringNGrams( ['a', 'b', 'c', 'd', 'e', 'f'], tf.tensor1d([0, 1, 4, 6], 'int32'), '|', [3], 'LP', 'RP', -1, false); const nGrams = [ 'LP|LP|a', 'LP|a|RP', 'a|RP|RP', // 0 'LP|LP|b', 'LP|b|c', 'b|c|d', 'c|d|RP', 'd|RP|RP', // 1 'LP|LP|e', 'LP|e|f', 'e|f|RP', 'f|RP|RP' // 2 ]; const nGramsSplits = [0, 3, 8, 12]; await expectResult(result, nGrams, nGramsSplits); }); it('overlapping padded multi char nGrams', async () => { // Batch items are: // 0: "a" // 1: "b", "c", "d" // 2: "e", "f" const result = tf.string.stringNGrams( ['aa', 'bb', 'cc', 'dd', 'ee', 'ff'], tf.tensor1d([0, 1, 4, 6], 'int32'), '|', [3], 'LP', 'RP', -1, false); const nGrams = [ 'LP|LP|aa', 'LP|aa|RP', 'aa|RP|RP', // 0 'LP|LP|bb', 'LP|bb|cc', 'bb|cc|dd', 'cc|dd|RP', 'dd|RP|RP', // 1 'LP|LP|ee', 'LP|ee|ff', 'ee|ff|RP', 'ff|RP|RP' // 2 ]; const nGramsSplits = [0, 3, 8, 12]; await expectResult(result, nGrams, nGramsSplits); }); it('multi overlapping padded nGrams', async () => { // This test validates that n-grams with more than 1 padding value on each // side are created correctly. // Batch items are: // 0: "a" const result = tf.string.stringNGrams( ['a'], tf.tensor1d([0, 1], 'int32'), '|', [5], 'LP', 'RP', -1, false); const nGrams = [ 'LP|LP|LP|LP|a', 'LP|LP|LP|a|RP', 'LP|LP|a|RP|RP', 'LP|a|RP|RP|RP', 'a|RP|RP|RP|RP' ]; const nGramsSplits = [0, 5]; await expectResult(result, nGrams, nGramsSplits); }); it('unpadded trigrams', async () => { // Batch items are: // 0: "a", "b", "c", "d" // 1: "e", "f" const result = tf.string.stringNGrams( ['a', 'b', 'c', 'd', 'e', 'f'], tf.tensor1d([0, 4, 6], 'int32'), '|', [3], '', '', 0, false); const nGrams = ['a|b|c', 'b|c|d']; const nGramsSplits = [0, 2, 2]; await expectResult(result, nGrams, nGramsSplits); }); it('unpadded trigrams with empty sequence', async () => { // Batch items are: // 0: "a", "b", "c", "d" // 1: "e", "f" const result = tf.string.stringNGrams( ['a', 'b', 'c', 'd', 'e', 'f'], tf.tensor1d([0, 4, 4, 6], 'int32'), '|', [3], '', '', 0, false); const nGrams = ['a|b|c', 'b|c|d']; const nGramsSplits = [0, 2, 2, 2]; await expectResult(result, nGrams, nGramsSplits); }); it('unpadded trigrams with preserve short', async () => { // Batch items are: // 0: "a", "b", "c", "d" // 1: "e", "f" const result = tf.string.stringNGrams( ['a', 'b', 'c', 'd', 'e', 'f'], tf.tensor1d([0, 4, 6], 'int32'), '|', [3], '', '', 0, true); const nGrams = ['a|b|c', 'b|c|d', 'e|f']; const nGramsSplits = [0, 2, 3]; await expectResult(result, nGrams, nGramsSplits); }); it('unpadded trigrams with preserve short and empty sequence', async () => { // Batch items are: // 0: "a", "b", "c", "d" // 1: "e", "f" const result = tf.string.stringNGrams( ['a', 'b', 'c', 'd', 'e', 'f'], tf.tensor1d([0, 4, 4, 6], 'int32'), '|', [3], '', '', 0, true); const nGrams = ['a|b|c', 'b|c|d', 'e|f']; const nGramsSplits = [0, 2, 2, 3]; await expectResult(result, nGrams, nGramsSplits); }); it('unpadded trigrams and quad grams with preserve short', async () => { // Batch items are: // 0: "a", "b", "c", "d" // 1: "e", "f" const result = tf.string.stringNGrams( ['a', 'b', 'c', 'd', 'e', 'f'], tf.tensor1d([0, 4, 6], 'int32'), '|', [4, 3], '', '', 0, true); const nGrams = ['a|b|c|d', 'a|b|c', 'b|c|d', 'e|f']; const nGramsSplits = [0, 3, 4]; await expectResult(result, nGrams, nGramsSplits); }); it('unpadded bigrams and trigrams', async () => { // Batch items are: // 0: "a", "b", "c", "d" // 1: "e", "f" const result = tf.string.stringNGrams( ['a', 'b', 'c', 'd', 'e', 'f'], tf.tensor1d([0, 4, 6], 'int32'), '|', [2, 3], '', '', 0, false); const nGrams = ['a|b', 'b|c', 'c|d', 'a|b|c', 'b|c|d', 'e|f']; const nGramsSplits = [0, 5, 6]; await expectResult(result, nGrams, nGramsSplits); }); it('unpadded bigrams and trigrams with preserve short', async () => { // Batch items are: // 0: "a", "b", "c", "d" // 1: "e", "f" const result = tf.string.stringNGrams( ['a', 'b', 'c', 'd', 'e', 'f'], tf.tensor1d([0, 4, 6], 'int32'), '|', [2, 3], '', '', 0, true); // Note that in this case, because the bigram 'e|f' was already generated, // the op will not generate a special preserveShort bigram. const nGrams = ['a|b', 'b|c', 'c|d', 'a|b|c', 'b|c|d', 'e|f']; const nGramsSplits = [0, 5, 6]; await expectResult(result, nGrams, nGramsSplits); }); it('unpadded trigrams and bigrams with preserve short', async () => { // Batch items are: // 0: "a", "b", "c", "d" // 1: "e", "f" const result = tf.string.stringNGrams( ['a', 'b', 'c', 'd', 'e', 'f'], tf.tensor1d([0, 4, 6], 'int32'), '|', [3, 2], '', '', 0, true); // Note that in this case, because the bigram 'e|f' was already generated, // the op will not generate a special preserveShort bigram. const nGrams = ['a|b|c', 'b|c|d', 'a|b', 'b|c', 'c|d', 'e|f']; const nGramsSplits = [0, 5, 6]; await expectResult(result, nGrams, nGramsSplits); }); it('unpadded bigrams', async () => { // Batch items are: // 0: "a", "b", "c", "d" // 1: "e", "f" const result = tf.string.stringNGrams( ['a', 'b', 'c', 'd', 'e', 'f'], tf.tensor1d([0, 4, 6], 'int32'), '|', [2], '', '', 0, false); const nGrams = ['a|b', 'b|c', 'c|d', 'e|f']; const nGramsSplits = [0, 3, 4]; await expectResult(result, nGrams, nGramsSplits); }); it('overlapping unpadded nGrams', async () => { // Batch items are: // 0: "a" // 1: "b", "c", "d" // 2: "e", "f" const result = tf.string.stringNGrams( ['a', 'b', 'c', 'd', 'e', 'f'], tf.tensor1d([0, 1, 4, 6], 'int32'), '|', [3], '', '', 0, false); const nGrams = ['b|c|d']; const nGramsSplits = [0, 0, 1, 1]; await expectResult(result, nGrams, nGramsSplits); }); it('overlapping unpadded nGrams no output', async () => { // Batch items are: // 0: "a" // 1: "b", "c", "d" // 2: "e", "f" const result = tf.string.stringNGrams( ['a', 'b', 'c', 'd', 'e', 'f'], tf.tensor1d([0, 1, 4, 6], 'int32'), '|', [5], '', '', 0, false); const nGrams: string[] = []; const nGramsSplits = [0, 0, 0, 0]; await expectResult(result, nGrams, nGramsSplits); }); it('singly padded trigrams', async () => { // Batch items are: // 0: "a", "b", "c", "d" // 1: "e", "f" const result = tf.string.stringNGrams( ['a', 'b', 'c', 'd', 'e', 'f'], tf.tensor1d([0, 4, 6], 'int32'), '|', [3], 'LP', 'RP', 1, false); const nGrams = [ 'LP|a|b', 'a|b|c', 'b|c|d', 'c|d|RP', // 0 'LP|e|f', 'e|f|RP' ]; const nGramsSplits = [0, 4, 6]; await expectResult(result, nGrams, nGramsSplits); }); it('singly padded bigrams', async () => { // Batch items are: // 0: "a", "b", "c", "d" // 1: "e", "f" const result = tf.string.stringNGrams( ['a', 'b', 'c', 'd', 'e', 'f'], tf.tensor1d([0, 4, 6], 'int32'), '|', [2], 'LP', 'RP', 1, false); const nGrams = [ 'LP|a', 'a|b', 'b|c', 'c|d', 'd|RP', // 0 'LP|e', 'e|f', 'f|RP' ]; const nGramsSplits = [0, 5, 8]; await expectResult(result, nGrams, nGramsSplits); }); it('singly padded bigrams and 5grams', async () => { // Batch items are: // 0: "a", "b", "c", "d" // 1: "e", "f" const result = tf.string.stringNGrams( ['a', 'b', 'c', 'd', 'e', 'f'], tf.tensor1d([0, 4, 6], 'int32'), '|', [2, 5], 'LP', 'RP', 1, false); const nGrams = [ 'LP|a', 'a|b', 'b|c', 'c|d', 'd|RP', 'LP|a|b|c|d', 'a|b|c|d|RP', // 0 'LP|e', 'e|f', 'f|RP' ]; const nGramsSplits = [0, 7, 10]; await expectResult(result, nGrams, nGramsSplits); }); it('singly padded 5grams with preserve short', async () => { // Batch items are: // 0: "a", "b", "c", "d" // 1: "e", "f" const result = tf.string.stringNGrams( ['a', 'b', 'c', 'd', 'e', 'f'], tf.tensor1d([0, 4, 6], 'int32'), '|', [5], 'LP', 'RP', 1, true); const nGrams = [ 'LP|a|b|c|d', 'a|b|c|d|RP', // 0 'LP|e|f|RP' ]; const nGramsSplits = [0, 2, 3]; await expectResult(result, nGrams, nGramsSplits); }); it('overlapping singly padded nGrams', async () => { // Batch items are: // 0: "a" // 1: "b", "c", "d" // 2: "e", "f" const result = tf.string.stringNGrams( ['a', 'b', 'c', 'd', 'e', 'f'], tf.tensor1d([0, 1, 4, 6], 'int32'), '|', [3], 'LP', 'RP', 1, false); const nGrams = [ 'LP|a|RP', // 0 'LP|b|c', 'b|c|d', 'c|d|RP', // 1 'LP|e|f', 'e|f|RP' ]; const nGramsSplits = [0, 1, 4, 6]; await expectResult(result, nGrams, nGramsSplits); }); it('overlapping singly padded nGrams no output', async () => { // Batch items are: // 0: "a" // 1: "b", "c", "d" // 2: "e", "f" const result = tf.string.stringNGrams( ['a', 'b', 'c', 'd', 'e', 'f'], tf.tensor1d([0, 1, 4, 6], 'int32'), '|', [5], 'LP', 'RP', 1, false); const nGrams = ['LP|b|c|d|RP']; const nGramsSplits = [0, 0, 1, 1]; await expectResult(result, nGrams, nGramsSplits); }); it('singly padded unigrams', async () => { // Batch items are: // 0: "a", "b", "c", "d" // 1: "e", "f" const result = tf.string.stringNGrams( ['a', 'b', 'c', 'd', 'e', 'f'], tf.tensor1d([0, 4, 6], 'int32'), '|', [1], 'LP', 'RP', 1, false); const nGrams = ['a', 'b', 'c', 'd', 'e', 'f']; const nGramsSplits = [0, 4, 6]; await expectResult(result, nGrams, nGramsSplits); }); it('empty input', async () => { const result = tf.string.stringNGrams( tf.tensor1d([], 'string'), tf.tensor1d([], 'int32'), '|', [1], 'LP', 'RP', 3, false); const nGrams: string[] = []; const nGramsSplits: number[] = []; await expectResult(result, nGrams, nGramsSplits); }); it('no tokens', async () => { // Batch items are: // 0: // 1: "a" const result = tf.string.stringNGrams( ['a'], tf.tensor1d([0, 0, 1], 'int32'), '|', [3], 'L', 'R', -1, false); const nGrams = [ 'L|L|R', 'L|R|R', // no input in first split 'L|L|a', 'L|a|R', 'a|R|R' // second split ]; const nGramsSplits = [0, 2, 5]; await expectResult(result, nGrams, nGramsSplits); }); it('no tokens no pad', async () => { // Batch items are: // 0: // 1: "a" const result = tf.string.stringNGrams( ['a'], tf.tensor1d([0, 0, 1], 'int32'), '|', [3], '', '', 0, false); const nGrams: string[] = []; const nGramsSplits = [0, 0, 0]; await expectResult(result, nGrams, nGramsSplits); }); it('throw error if first partition index is not 0', async () => { expect( () => tf.string.stringNGrams( ['a'], tf.tensor1d([1, 1, 1], 'int32'), '|', [3], '', '', 0, false)) .toThrowError(/First split value must be 0/); }); it('throw error if partition indices are decreasing', async () => { expect( () => tf.string.stringNGrams( ['a'], tf.tensor1d([0, 1, 0], 'int32'), '|', [3], '', '', 0, false)) .toThrowError(/must be in \[1, 1\]/); }); it('throw error if partition index is >= input size', async () => { expect( () => tf.string.stringNGrams( ['a'], tf.tensor1d([0, 2, 1], 'int32'), '|', [3], '', '', 0, false)) .toThrowError(/must be in \[0, 1\]/); }); it('throw error if last partition index is !== input size', async () => { expect( () => tf.string.stringNGrams( ['a'], tf.tensor1d([0, 0], 'int32'), '|', [3], '', '', 0, false)) .toThrowError(/Last split value must be data size/); }); });
the_stack
import { i18nMark } from "@lingui/react"; import { Trans } from "@lingui/macro"; import { Dropdown } from "reactjs-components"; import mixin from "reactjs-mixin"; import { Link } from "react-router"; import * as React from "react"; import { Icon } from "@dcos/ui-kit"; import { ProductIcons } from "@dcos/ui-kit/dist/packages/icons/dist/product-icons-enum"; import { iconSizeS } from "@dcos/ui-kit/dist/packages/design-tokens/build/js/designTokens"; import Breadcrumb from "#SRC/js/components/Breadcrumb"; import BreadcrumbTextContent from "#SRC/js/components/BreadcrumbTextContent"; import FilterBar from "#SRC/js/components/FilterBar"; import FilterHeadline from "#SRC/js/components/FilterHeadline"; import FilterInputText from "#SRC/js/components/FilterInputText"; import Loader from "#SRC/js/components/Loader"; import Page from "#SRC/js/components/Page"; import RequestErrorMsg from "#SRC/js/components/RequestErrorMsg"; import StoreMixin from "#SRC/js/mixins/StoreMixin"; import StringUtil from "#SRC/js/utils/StringUtil"; import UserActions from "#SRC/js/constants/UserActions"; import SecretActionsModal from "../components/SecretActionsModal"; import SecretFormModal from "../components/SecretFormModal"; import SecretsTable from "../components/SecretsTable"; import getSecretStore from "../stores/SecretStore"; import SecretsError from "../components/SecretsError"; import EmptySecretsTable from "../components/EmptySecretsTable"; import AlertPanel from "#SRC/js/components/AlertPanel"; import AlertPanelHeader from "#SRC/js/components/AlertPanelHeader"; import MetadataStore from "#SRC/js/stores/MetadataStore"; const SealedStoreAlert = () => { const docsLink = MetadataStore.buildDocsURI( "/security/ent/secrets/unseal-store/" ); return ( <AlertPanel> <AlertPanelHeader> <Trans render="span">Secret store sealed</Trans> </AlertPanelHeader> <Trans render="p" className="flush-bottom"> The contents of this secret store cannot be accessed until it is unsealed. See{" "} <a href={docsLink} target="_blank"> instructions </a>{" "} on how to access sealed secret stores. </Trans> </AlertPanel> ); }; const SecretStore = getSecretStore(); const SECRET_DROPDOWN_ACTIONS = [ { html: StringUtil.capitalize(UserActions.DELETE), id: UserActions.DELETE, selectedHtml: "Actions", }, ]; const SecretsBreadcrumbs = () => { const crumbs = [ <Breadcrumb key={0} title="Secrets"> <BreadcrumbTextContent> <Trans render={<Link to="/secrets" />}>Secrets</Trans> </BreadcrumbTextContent> </Breadcrumb>, ]; return ( <Page.Header.Breadcrumbs iconID={ProductIcons.Lock} breadcrumbs={crumbs} /> ); }; const PermissionErrorMessage = () => { const header = "Permission denied"; const message = ( <Trans render="p" className="text-align-center flush-bottom"> You do not have permission to list this cluster's secrets. <br /> Please contact your super admin to learn more. </Trans> ); return <RequestErrorMsg header={header} message={message} />; }; class SecretsPage extends mixin(StoreMixin) { state = { checkedItems: {}, healthFilter: "all", isLoadingStores: true, isLoadingSecrets: true, requestErrorType: null, showActionDropdown: false, searchString: "", secretFormOpen: false, secretToRemove: null, selectedAction: "", }; // prettier-ignore store_listeners = [ { name: "secrets", events: ["storesSuccess", "secretsSuccess", "secretsError"] }, ]; componentDidMount() { super.componentDidMount(); SecretStore.fetchStores(); SecretStore.fetchSecrets(); } onSecretsStoreStoresSuccess() { this.setState({ isLoadingStores: false, requestErrorType: null }); } onSecretsStoreSecretsSuccess() { this.setState({ isLoadingSecrets: false, requestErrorType: null }); } onSecretsStoreSecretsError(error) { if (error.status === 403) { this.setState({ requestErrorType: "permission" }); } else { this.setState({ requestErrorType: "failure" }); } } handleActionSelection = (action) => { this.setState({ selectedAction: action.id }); }; handleHealthFilterChange = (healthFilter) => { this.setState({ healthFilter }); }; handleSearchStringChange = (searchString = "") => { this.setState({ searchString }); }; handleItemCheck = (idsChecked) => { this.setState({ checkedItems: idsChecked }); }; handleRemoveClick = (secret) => { this.setState({ selectedAction: UserActions.DELETE, secretToRemove: secret, }); }; handleSecretFormOpen = () => { this.setState({ secretFormOpen: true }); }; handleSecretFormClose = () => { this.setState({ secretFormOpen: false }); }; handleActionClose = () => { this.setState({ selectedAction: "", secretToRemove: false, }); }; handleActionSuccess = () => { const nextState = { selectedAction: "" }; if (this.state.secretToRemove) { nextState.secretToRemove = false; } else { nextState.checkedItems = {}; } SecretStore.fetchSecrets(); this.setState(nextState); }; resetFilter = () => { this.setState({ searchString: "", healthFilter: "all" }); }; getVisibleItems(items, searchString) { return items.filter((item) => item.getPath().includes(searchString)); } getCheckedItems(items) { const { checkedItems } = this.state; return items.filter((item) => checkedItems[item.getPath()]); } getActionDropdown(checkedItems) { if (Object.keys(checkedItems).length === 0) { return null; } if (SECRET_DROPDOWN_ACTIONS.length === 1) { const buttonAction = SECRET_DROPDOWN_ACTIONS[0]; return ( <button className="button" onClick={this.handleActionSelection.bind(this, buttonAction)} > {buttonAction.html} </button> ); } return ( <Dropdown buttonClassName="button dropdown-toggle" dropdownMenuClassName="dropdown-menu" dropdownMenuListClassName="dropdown-menu-list" dropdownMenuListItemClassName="clickable" initialID={UserActions.DELETE} items={SECRET_DROPDOWN_ACTIONS} onItemSelection={this.handleActionSelection} scrollContainer=".gm-scroll-view" scrollContainerParentSelector=".gm-prevented" transition={true} transitionName="dropdown-menu" wrapperClassName="dropdown" /> ); } getActionItems(secrets) { let actionItems = [this.state.secretToRemove]; if (!actionItems[0]) { actionItems = this.getCheckedItems(secrets); } return actionItems; } render() { const { checkedItems, healthFilter, isLoadingStores, isLoadingSecrets, requestErrorType, searchString, secretFormOpen, selectedAction, } = this.state; // the list-request will fail, thus this needs to be before the SecretsError-component if (SecretStore.getStores().some((s) => s.sealed)) { return ( <Page> <Page.Header breadcrumbs={<SecretsBreadcrumbs />} /> <SealedStoreAlert /> </Page> ); } if (requestErrorType !== null) { return ( <SecretsError type={requestErrorType} open={secretFormOpen} openModal={this.handleSecretFormOpen} closeModal={this.handleSecretFormClose} breadcrumbs={<SecretsBreadcrumbs />} permissionErrorMessage={<PermissionErrorMessage />} /> ); } if (isLoadingStores && isLoadingSecrets) { return ( <Page> <Page.Header breadcrumbs={<SecretsBreadcrumbs />} /> <Loader /> </Page> ); } const secrets = requestErrorType === "permission" ? [] : SecretStore.getSecrets(); const visibleItems = this.getVisibleItems(secrets, searchString); return ( <Page dontScroll={true} flushBottom={true}> <Page.Header breadcrumbs={<SecretsBreadcrumbs />} addButton={{ onItemSelect: this.handleSecretFormOpen, label: i18nMark("New Secret"), }} /> <div className="flex-item-grow-1 flex flex-direction-top-to-bottom"> {secrets.length ? ( <React.Fragment> <div className="users-table-header"> <FilterHeadline currentLength={visibleItems.length} isFiltering={healthFilter !== "all" || searchString !== ""} name="Secret" onReset={this.resetFilter} totalLength={secrets.length} /> <FilterBar> <FilterInputText className="flush-bottom" searchString={searchString} handleFilterChange={this.handleSearchStringChange} /> {this.getActionDropdown(checkedItems)} </FilterBar> </div> <div className="flex-grow flex-container-col table-wrapper"> <SecretsTable data={visibleItems} onChange={this.handleItemCheck} selected={checkedItems} onRemoveClick={this.handleRemoveClick} /> </div> </React.Fragment> ) : ( <EmptySecretsTable handleSecretFormOpen={this.handleSecretFormOpen} /> )} <SecretFormModal onClose={this.handleSecretFormClose} open={secretFormOpen} /> <SecretActionsModal itemID="path" action={selectedAction} onClose={this.handleActionClose} onSuccess={this.handleActionSuccess} selectedItems={this.getActionItems(secrets)} open={!!selectedAction} /> </div> </Page> ); } } SecretsPage.routeConfig = { icon: <Icon shape={ProductIcons.LockInverse} size={iconSizeS} />, label: i18nMark("Secrets"), matches: /^\/secrets/, }; export default SecretsPage;
the_stack
import { numberToBinUint16LE, numberToBinUint32LE, } from '../../../format/format'; import { range } from '../../../format/hex'; import { Operation } from '../../virtual-machine'; import { AuthenticationProgramStateError, AuthenticationProgramStateExecutionStack, AuthenticationProgramStateMinimum, AuthenticationProgramStateStack, } from '../../vm-types'; import { AuthenticationInstructionPush } from '../instruction-sets-types'; import { pushToStack } from './combinators'; import { applyError, AuthenticationErrorCommon } from './errors'; import { OpcodesCommon } from './opcodes'; import { bigIntToScriptNumber } from './types'; export enum PushOperationConstants { OP_0 = 0, /** * OP_PUSHBYTES_75 */ maximumPushByteOperationSize = 0x4b, OP_PUSHDATA_1 = 0x4c, OP_PUSHDATA_2 = 0x4d, OP_PUSHDATA_4 = 0x4e, /** * OP_PUSHDATA_4 */ highestPushDataOpcode = OP_PUSHDATA_4, /** * For OP_1 to OP_16, `opcode` is the number offset by `0x50` (80): * * `OP_N = 0x50 + N` * * OP_0 is really OP_PUSHBYTES_0 (`0x00`), so it does not follow this pattern. */ pushNumberOpcodesOffset = 0x50, /** OP_1 through OP_16 */ pushNumberOpcodes = 16, negativeOne = 0x81, OP_1NEGATE = 79, /** * 256 - 1 */ maximumPushData1Size = 255, /** * Standard consensus parameter for most Bitcoin forks. */ maximumPushSize = 520, /** * 256 ** 2 - 1 */ maximumPushData2Size = 65535, /** * 256 ** 4 - 1 */ maximumPushData4Size = 4294967295, } /** * Returns the minimal bytecode required to push the provided `data` to the * stack. * * @remarks * This method conservatively encodes a `Uint8Array` as a data push. For Script * Numbers which can be pushed using a single opcode (-1 through 16), the * equivalent bytecode value is returned. Other `data` values will be prefixed * with the proper opcode and push length bytes (if necessary) to create the * minimal push instruction. * * Note, while some single-byte Script Number pushes will be minimally-encoded * by this method, all larger inputs will be encoded as-is (it cannot be assumed * that inputs are intended to be used as Script Numbers). To encode the push of * a Script Number, minimally-encode the number before passing it to this * method, e.g.: * `encodeDataPush(bigIntToScriptNumber(parseBytesAsScriptNumber(nonMinimalNumber)))`. * * The maximum `bytecode` length which can be encoded for a push in the Bitcoin * system is `4294967295` (~4GB). This method assumes a smaller input – if * `bytecode` has the potential to be longer, it should be checked (and the * error handled) prior to calling this method. * * @param data - the Uint8Array to push to the stack */ // eslint-disable-next-line complexity export const encodeDataPush = (data: Uint8Array) => data.length <= PushOperationConstants.maximumPushByteOperationSize ? data.length === 0 ? Uint8Array.of(0) : data.length === 1 ? data[0] !== 0 && data[0] <= PushOperationConstants.pushNumberOpcodes ? Uint8Array.of( data[0] + PushOperationConstants.pushNumberOpcodesOffset ) : data[0] === PushOperationConstants.negativeOne ? Uint8Array.of(PushOperationConstants.OP_1NEGATE) : Uint8Array.from([1, ...data]) : Uint8Array.from([data.length, ...data]) : data.length <= PushOperationConstants.maximumPushData1Size ? Uint8Array.from([ PushOperationConstants.OP_PUSHDATA_1, data.length, ...data, ]) : data.length <= PushOperationConstants.maximumPushData2Size ? Uint8Array.from([ PushOperationConstants.OP_PUSHDATA_2, ...numberToBinUint16LE(data.length), ...data, ]) : Uint8Array.from([ PushOperationConstants.OP_PUSHDATA_4, ...numberToBinUint32LE(data.length), ...data, ]); /** * Returns true if the provided `data` is minimally-encoded by the provided * `opcode`. * @param opcode - the opcode used to push `data` * @param data - the contents of the push */ // eslint-disable-next-line complexity export const isMinimalDataPush = (opcode: number, data: Uint8Array) => data.length === 0 ? opcode === PushOperationConstants.OP_0 : data.length === 1 ? data[0] >= 1 && data[0] <= PushOperationConstants.pushNumberOpcodes ? opcode === data[0] + PushOperationConstants.pushNumberOpcodesOffset : data[0] === PushOperationConstants.negativeOne ? opcode === PushOperationConstants.OP_1NEGATE : true : data.length <= PushOperationConstants.maximumPushByteOperationSize ? opcode === data.length : data.length <= PushOperationConstants.maximumPushData1Size ? opcode === PushOperationConstants.OP_PUSHDATA_1 : data.length <= PushOperationConstants.maximumPushData2Size ? opcode === PushOperationConstants.OP_PUSHDATA_2 : true; export const pushByteOpcodes: readonly OpcodesCommon[] = [ OpcodesCommon.OP_PUSHBYTES_1, OpcodesCommon.OP_PUSHBYTES_2, OpcodesCommon.OP_PUSHBYTES_3, OpcodesCommon.OP_PUSHBYTES_4, OpcodesCommon.OP_PUSHBYTES_5, OpcodesCommon.OP_PUSHBYTES_6, OpcodesCommon.OP_PUSHBYTES_7, OpcodesCommon.OP_PUSHBYTES_8, OpcodesCommon.OP_PUSHBYTES_9, OpcodesCommon.OP_PUSHBYTES_10, OpcodesCommon.OP_PUSHBYTES_11, OpcodesCommon.OP_PUSHBYTES_12, OpcodesCommon.OP_PUSHBYTES_13, OpcodesCommon.OP_PUSHBYTES_14, OpcodesCommon.OP_PUSHBYTES_15, OpcodesCommon.OP_PUSHBYTES_16, OpcodesCommon.OP_PUSHBYTES_17, OpcodesCommon.OP_PUSHBYTES_18, OpcodesCommon.OP_PUSHBYTES_19, OpcodesCommon.OP_PUSHBYTES_20, OpcodesCommon.OP_PUSHBYTES_21, OpcodesCommon.OP_PUSHBYTES_22, OpcodesCommon.OP_PUSHBYTES_23, OpcodesCommon.OP_PUSHBYTES_24, OpcodesCommon.OP_PUSHBYTES_25, OpcodesCommon.OP_PUSHBYTES_26, OpcodesCommon.OP_PUSHBYTES_27, OpcodesCommon.OP_PUSHBYTES_28, OpcodesCommon.OP_PUSHBYTES_29, OpcodesCommon.OP_PUSHBYTES_30, OpcodesCommon.OP_PUSHBYTES_31, OpcodesCommon.OP_PUSHBYTES_32, OpcodesCommon.OP_PUSHBYTES_33, OpcodesCommon.OP_PUSHBYTES_34, OpcodesCommon.OP_PUSHBYTES_35, OpcodesCommon.OP_PUSHBYTES_36, OpcodesCommon.OP_PUSHBYTES_37, OpcodesCommon.OP_PUSHBYTES_38, OpcodesCommon.OP_PUSHBYTES_39, OpcodesCommon.OP_PUSHBYTES_40, OpcodesCommon.OP_PUSHBYTES_41, OpcodesCommon.OP_PUSHBYTES_42, OpcodesCommon.OP_PUSHBYTES_43, OpcodesCommon.OP_PUSHBYTES_44, OpcodesCommon.OP_PUSHBYTES_45, OpcodesCommon.OP_PUSHBYTES_46, OpcodesCommon.OP_PUSHBYTES_47, OpcodesCommon.OP_PUSHBYTES_48, OpcodesCommon.OP_PUSHBYTES_49, OpcodesCommon.OP_PUSHBYTES_50, OpcodesCommon.OP_PUSHBYTES_51, OpcodesCommon.OP_PUSHBYTES_52, OpcodesCommon.OP_PUSHBYTES_53, OpcodesCommon.OP_PUSHBYTES_54, OpcodesCommon.OP_PUSHBYTES_55, OpcodesCommon.OP_PUSHBYTES_56, OpcodesCommon.OP_PUSHBYTES_57, OpcodesCommon.OP_PUSHBYTES_58, OpcodesCommon.OP_PUSHBYTES_59, OpcodesCommon.OP_PUSHBYTES_60, OpcodesCommon.OP_PUSHBYTES_61, OpcodesCommon.OP_PUSHBYTES_62, OpcodesCommon.OP_PUSHBYTES_63, OpcodesCommon.OP_PUSHBYTES_64, OpcodesCommon.OP_PUSHBYTES_65, OpcodesCommon.OP_PUSHBYTES_66, OpcodesCommon.OP_PUSHBYTES_67, OpcodesCommon.OP_PUSHBYTES_68, OpcodesCommon.OP_PUSHBYTES_69, OpcodesCommon.OP_PUSHBYTES_70, OpcodesCommon.OP_PUSHBYTES_71, OpcodesCommon.OP_PUSHBYTES_72, OpcodesCommon.OP_PUSHBYTES_73, OpcodesCommon.OP_PUSHBYTES_74, OpcodesCommon.OP_PUSHBYTES_75, ]; const executionIsActive = < State extends AuthenticationProgramStateExecutionStack >( state: State ) => state.executionStack.every((item) => item); export const pushOperation = < Opcodes, State extends AuthenticationProgramStateStack & AuthenticationProgramStateMinimum<Opcodes> & AuthenticationProgramStateError<Errors> & AuthenticationProgramStateExecutionStack, Errors >( flags: { requireMinimalEncoding: boolean }, maximumPushSize = PushOperationConstants.maximumPushSize ): Operation<State> => (state: State) => { const instruction = state.instructions[ state.ip ] as AuthenticationInstructionPush<Opcodes>; return instruction.data.length > maximumPushSize ? applyError<State, Errors>( AuthenticationErrorCommon.exceedsMaximumPush, state ) : executionIsActive(state) ? flags.requireMinimalEncoding && !isMinimalDataPush( (instruction.opcode as unknown) as number, instruction.data ) ? applyError<State, Errors>( AuthenticationErrorCommon.nonMinimalPush, state ) : pushToStack(state, instruction.data) : state; }; export const pushOperations = < Opcodes, State extends AuthenticationProgramStateStack & AuthenticationProgramStateMinimum<Opcodes> & AuthenticationProgramStateError<Errors> & AuthenticationProgramStateExecutionStack, Errors >( flags: { requireMinimalEncoding: boolean }, maximumPushSize = PushOperationConstants.maximumPushSize ) => { const push = pushOperation<Opcodes, State, Errors>(flags, maximumPushSize); return range(PushOperationConstants.highestPushDataOpcode + 1).reduce<{ readonly [opcode: number]: Operation<State>; }>((group, i) => ({ ...group, [i]: push }), {}); }; export const pushNumberOpcodes: readonly OpcodesCommon[] = [ OpcodesCommon.OP_1NEGATE, OpcodesCommon.OP_1, OpcodesCommon.OP_2, OpcodesCommon.OP_3, OpcodesCommon.OP_4, OpcodesCommon.OP_5, OpcodesCommon.OP_6, OpcodesCommon.OP_7, OpcodesCommon.OP_8, OpcodesCommon.OP_9, OpcodesCommon.OP_10, OpcodesCommon.OP_11, OpcodesCommon.OP_12, OpcodesCommon.OP_13, OpcodesCommon.OP_14, OpcodesCommon.OP_15, OpcodesCommon.OP_16, ]; const op1NegateValue = -1; export const pushNumberOperations = < Opcodes, ProgramState extends AuthenticationProgramStateStack & AuthenticationProgramStateMinimum<Opcodes> >() => pushNumberOpcodes .map<[OpcodesCommon, Uint8Array]>((opcode, i) => [ opcode, [op1NegateValue, ...range(PushOperationConstants.pushNumberOpcodes, 1)] .map(BigInt) .map(bigIntToScriptNumber)[i], ]) .reduce<{ readonly [opcode: number]: Operation<ProgramState>; }>( (group, pair) => ({ ...group, [pair[0]]: (state: ProgramState) => pushToStack(state, pair[1].slice()), }), {} );
the_stack
import fs, { createReadStream } from 'fs'; import crypto from 'crypto'; import Blockweave from 'blockweave'; import mime from 'mime'; import clui from 'clui'; import clc from 'cli-color'; import PromisePool from '@supercharge/promise-pool'; import IPFS from '../utils/ipfs'; import Community from 'community-js'; import { pipeline } from 'stream/promises'; import { TxDetail } from '../faces/txDetail'; import { FileBundle, FileDataItem } from 'arbundles/file'; import Bundler from '../utils/bundler'; import Tags from '../lib/tags'; import { getPackageVersion } from '../utils/utils'; import { JWKInterface } from 'blockweave/dist/faces/lib/wallet'; import Transaction from 'blockweave/dist/lib/transaction'; import { createTransactionAsync, uploadTransactionAsync } from 'arweave-stream-tx'; import Arweave from 'arweave'; import Cache from '../utils/cache'; export default class Deploy { private wallet: JWKInterface; private blockweave: Blockweave; private arweave: Arweave; private bundler: Bundler; private ipfs: IPFS = new IPFS(); private cache: Cache; private txs: TxDetail[]; private duplicates: { hash: string; id: string; filePath: string }[] = []; private community: Community; private bundle: FileBundle; private bundledTx: Transaction; constructor( wallet: JWKInterface, blockweave: Blockweave, public readonly debug: boolean = false, public readonly threads: number = 0, public readonly logs: boolean = true, public readonly localBundle: boolean = false, ) { this.wallet = wallet; this.blockweave = blockweave; this.arweave = Arweave.init({ host: blockweave.config.host, port: blockweave.config.port, protocol: blockweave.config.protocol, timeout: blockweave.config.timeout, logging: blockweave.config.logging, }); this.cache = new Cache( debug, this.arweave.getConfig().api.host === 'localhost' || this.arweave.getConfig().api.host === '127.0.0.1', ); this.bundler = new Bundler(wallet, this.blockweave); try { // @ts-ignore this.community = new Community(blockweave, wallet); // tslint:disable-next-line: no-empty } catch {} } getBundler(): Bundler { return this.bundler; } getBundle(): FileBundle { return this.bundle; } getBundledTx(): Transaction { return this.bundledTx; } async prepare( dir: string, files: string[], index: string = 'index.html', tags: Tags = new Tags(), toIpfs: boolean = false, license?: string, useBundler?: string, feeMultiplier?: number, forceRedeploy: boolean = false, ) { this.txs = []; if (typeof license === 'string' && license.length > 0) { tags.addTag('License', license); } if (useBundler) { tags.addTag('Bundler', useBundler); tags.addTag('Bundle', 'ans104'); } let leftToPrepare = files.length; let countdown: clui.Spinner; if (this.logs) { countdown = new clui.Spinner(`Preparing ${leftToPrepare} files...`, ['⣾', '⣽', '⣻', '⢿', '⡿', '⣟', '⣯', '⣷']); countdown.start(); } await PromisePool.for(files) .withConcurrency(this.threads) .process(async (filePath: string) => { if (this.logs) countdown.message(`Preparing ${leftToPrepare--} files...`); let data: Buffer; try { data = fs.readFileSync(filePath); } catch (e) { console.log('Unable to read file ' + filePath); throw new Error(`Unable to read file: ${filePath}`); } if (!data || !data.length) { return; } const hash = await this.toHash(data); if (!forceRedeploy && this.cache.has(hash)) { const cached = this.cache.get(hash); let confirmed = cached.confirmed; if (!confirmed) { // tslint:disable-next-line: no-empty const res = await this.arweave.api.get(`tx/${cached.id}/status`).catch(() => {}); if (res && res.data && res.data.number_of_confirmations) { confirmed = true; } } if (confirmed) { this.cache.set(hash, { ...cached, confirmed: true }); this.duplicates.push({ hash, id: cached.id, filePath, }); return; } } const type = mime.getType(filePath) || 'application/octet-stream'; const newTags = new Tags(); for (const tag of newTags.tags) { newTags.addTag(tag.name, tag.value); } // Add/replace default tags if (toIpfs) { const ipfsHash = await this.ipfs.hash(data); newTags.addTag('IPFS-Add', ipfsHash); } newTags.addTag('User-Agent', `arkb`); newTags.addTag('User-Agent-Version', getPackageVersion()); newTags.addTag('Type', 'file'); if (type) newTags.addTag('Content-Type', type); newTags.addTag('File-Hash', hash); let tx: Transaction | FileDataItem; if (useBundler || this.localBundle) { tx = await this.bundler.createItem(data, newTags.tags); } else { tx = await this.buildTransaction(filePath, newTags); if (feeMultiplier && feeMultiplier > 1) { (tx as Transaction).reward = parseInt( (feeMultiplier * +(tx as Transaction).reward).toString(), 10, ).toString(); } } this.cache.set(hash, { id: tx.id, confirmed: false, }); this.txs.push({ filePath, hash, tx, type }); }); if (this.logs) countdown.stop(); const isFile = this.txs.length === 1 && this.txs[0].filePath === dir; if (isFile && this.duplicates.length) { console.log(clc.red('File already deployed:')); if (toIpfs) { const data = fs.readFileSync(files[0]); const cid = await this.ipfs.hash(data); console.log(`IPFS: ${clc.cyan(cid)}`); } console.log('Arweave: ' + clc.cyan(`${this.blockweave.config.url}/${this.duplicates[0].id}`)); return; } if (this.logs) { countdown = new clui.Spinner(`Building manifest...`, ['⣾', '⣽', '⣻', '⢿', '⡿', '⣟', '⣯', '⣷']); countdown.start(); } await this.buildManifest(dir, index, tags, useBundler, feeMultiplier); if (this.logs) countdown.stop(); if (useBundler || this.localBundle) { this.bundle = await this.bundler.bundleAndSign(this.txs.map((t) => t.tx) as FileDataItem[]); // @ts-ignore this.bundledTx = await this.bundle.toTransaction(this.arweave, this.wallet); // @ts-ignore await this.arweave.transactions.sign(this.bundledTx, this.wallet); } return this.txs; } async deploy(isFile: boolean = false, useBundler?: string): Promise<string> { let cTotal = this.localBundle ? 1 : this.txs.length; let countdown: clui.Spinner; if (this.logs) { countdown = new clui.Spinner(`Deploying ${cTotal} file${cTotal === 1 ? '' : 's'}...`, [ '⣾', '⣽', '⣻', '⢿', '⡿', '⣟', '⣯', '⣷', ]); countdown.start(); } let txid = this.txs[0].tx.id; if (!isFile) { for (let i = 0, j = this.txs.length; i < j; i++) { if (this.txs[i].filePath === '' && this.txs[i].hash === '') { txid = this.txs[i].tx.id; break; } } } try { const res = await this.arweave.api.get('cEQLlWFkoeFuO7dIsdFbMhsGPvkmRI9cuBxv0mdn0xU'); if (!res || res.status !== 200) { throw new Error('Unable to get cEQLlWFkoeFuO7dIsdFbMhsGPvkmRI9cuBxv0mdn0xU'); } await this.community.setCommunityTx('cEQLlWFkoeFuO7dIsdFbMhsGPvkmRI9cuBxv0mdn0xU'); const target = await this.community.selectWeightedHolder(); if (target && (await this.blockweave.wallets.jwkToAddress(this.wallet)) !== target) { let fee: number; if (useBundler || this.localBundle) { fee = +this.bundledTx.reward; } else { fee = this.txs.reduce((a, txData) => a + +(txData.tx as Transaction).reward, 0); } const quantity = parseInt((fee * 0.1).toString(), 10).toString(); if (target.length) { const tx = await this.blockweave.createTransaction( { target, quantity, }, this.wallet, ); let files = `${cTotal} file${isFile ? '' : 's'}`; if (useBundler) { files = `${cTotal} data item${isFile ? '' : 's'}`; } let actionMessage = `Deployed ${files} on https://arweave.net/${txid}`; if (this.localBundle) { actionMessage = `Deployed a bundle with ${files}, bundle ID ${this.bundledTx.id} on https://arweave.net/${txid}`; } tx.addTag('Action', 'Deploy'); tx.addTag('Message', actionMessage); tx.addTag('Service', 'arkb'); tx.addTag('App-Name', 'arkb'); tx.addTag('App-Version', getPackageVersion()); await tx.signAndPost(); } } // tslint:disable-next-line: no-empty } catch {} let toDeploy: TxDetail[] = this.txs; if (this.localBundle) { const hash = await this.toHash(await this.bundle.getRaw()); toDeploy = [ { filePath: '', hash, tx: this.bundledTx, type: 'Bundle', }, ]; } await PromisePool.for(toDeploy) .withConcurrency(this.threads) .process(async (txData) => { if (this.logs) countdown.message(`Deploying ${cTotal--} files...`); let deployed = false; if (useBundler) { try { await this.bundler.post(txData.tx as FileDataItem, useBundler); deployed = true; } catch (e) { console.log(e); console.log(clc.red('Failed to deploy data item:', txData.filePath)); } } else if (this.localBundle) { console.log('inside'); const txRes = await this.bundle.signAndSubmit(this.arweave, this.wallet); console.log(txRes); deployed = true; } if (txData.filePath === '' && txData.hash === '') { await (txData.tx as Transaction).post(0); deployed = true; } if (!deployed) { try { await pipeline( createReadStream(txData.filePath), // @ts-ignore uploadTransactionAsync(txData.tx as Transaction, this.blockweave), ); deployed = true; } catch (e) { if (this.debug) { console.log(e); console.log( clc.red(`Failed to upload ${txData.filePath} using uploadTransactionAsync, trying normal upload...`), ); } } } if (!deployed) { try { await (txData.tx as Transaction).post(0); deployed = true; } catch (e) { if (this.debug) { console.log(e); console.log(clc.red(`Failed to upload ${txData.filePath} using normal post!`)); } } } }); if (this.logs) countdown.stop(); await this.cache.save(); return txid; } private async buildTransaction(filePath: string, tags: Tags): Promise<Transaction> { const tx = await pipeline(createReadStream(filePath), createTransactionAsync({}, this.arweave, this.wallet)); tags.addTagsToTransaction(tx); await this.arweave.transactions.sign(tx, this.wallet); // @ts-ignore return tx; } private async buildManifest( dir: string, index: string = null, tags: Tags, useBundler: string, feeMultiplier: number, ) { const { results: pDuplicates } = await PromisePool.for(this.duplicates) .withConcurrency(this.threads) .process(async (txD) => { const filePath = txD.filePath.split(`${dir}/`)[1]; return [filePath, { id: txD.id }]; }); const { results: pTxs } = await PromisePool.for(this.txs) .withConcurrency(this.threads) .process(async (txD) => { const filePath = txD.filePath.split(`${dir}/`)[1]; return [filePath, { id: txD.tx.id }]; }); const paths = pDuplicates.concat(pTxs).reduce((acc, cur) => { // @ts-ignore acc[cur[0]] = cur[1]; return acc; }, {}); if (!index) { if (Object.keys(paths).includes('index.html')) { index = 'index.html'; } else { index = Object.keys(paths)[0]; } } else { if (!Object.keys(paths).includes(index)) { index = Object.keys(paths)[0]; } } const data = { manifest: 'arweave/paths', version: '0.1.0', index: { path: index, }, paths, }; tags.addTag('Type', 'manifest'); tags.addTag('Content-Type', 'application/x.arweave-manifest+json'); let tx: Transaction | FileDataItem; if (useBundler || this.localBundle) { tx = await this.bundler.createItem(JSON.stringify(data), tags.tags); } else { tx = await this.blockweave.createTransaction( { data: JSON.stringify(data), }, this.wallet, ); tags.addTagsToTransaction(tx as Transaction); if (feeMultiplier) { (tx as Transaction).reward = parseInt((feeMultiplier * +(tx as Transaction).reward).toString(), 10).toString(); } await tx.sign(); } this.txs.push({ filePath: '', hash: '', tx, type: 'application/x.arweave-manifest+json' }); return true; } private async toHash(data: Buffer): Promise<string> { const hash = crypto.createHash('sha256'); hash.update(data); return hash.digest('hex'); } }
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as Models from "../models"; import * as Mappers from "../models/volumeMappers"; import * as Parameters from "../models/parameters"; import { ServiceFabricMeshManagementClientContext } from "../serviceFabricMeshManagementClientContext"; /** Class representing a Volume. */ export class Volume { private readonly client: ServiceFabricMeshManagementClientContext; /** * Create a Volume. * @param {ServiceFabricMeshManagementClientContext} client Reference to the service client. */ constructor(client: ServiceFabricMeshManagementClientContext) { this.client = client; } /** * Creates a volume resource with the specified name, description and properties. If a volume * resource with the same name exists, then it is updated with the specified description and * properties. * @summary Creates or updates a volume resource. * @param resourceGroupName Azure resource group name * @param volumeResourceName The identity of the volume. * @param volumeResourceDescription Description for creating a Volume resource. * @param [options] The optional parameters * @returns Promise<Models.VolumeCreateResponse> */ create(resourceGroupName: string, volumeResourceName: string, volumeResourceDescription: Models.VolumeResourceDescription, options?: msRest.RequestOptionsBase): Promise<Models.VolumeCreateResponse>; /** * @param resourceGroupName Azure resource group name * @param volumeResourceName The identity of the volume. * @param volumeResourceDescription Description for creating a Volume resource. * @param callback The callback */ create(resourceGroupName: string, volumeResourceName: string, volumeResourceDescription: Models.VolumeResourceDescription, callback: msRest.ServiceCallback<Models.VolumeResourceDescription>): void; /** * @param resourceGroupName Azure resource group name * @param volumeResourceName The identity of the volume. * @param volumeResourceDescription Description for creating a Volume resource. * @param options The optional parameters * @param callback The callback */ create(resourceGroupName: string, volumeResourceName: string, volumeResourceDescription: Models.VolumeResourceDescription, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.VolumeResourceDescription>): void; create(resourceGroupName: string, volumeResourceName: string, volumeResourceDescription: Models.VolumeResourceDescription, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.VolumeResourceDescription>, callback?: msRest.ServiceCallback<Models.VolumeResourceDescription>): Promise<Models.VolumeCreateResponse> { return this.client.sendOperationRequest( { resourceGroupName, volumeResourceName, volumeResourceDescription, options }, createOperationSpec, callback) as Promise<Models.VolumeCreateResponse>; } /** * Gets the information about the volume resource with the given name. The information include the * description and other properties of the volume. * @summary Gets the volume resource with the given name. * @param resourceGroupName Azure resource group name * @param volumeResourceName The identity of the volume. * @param [options] The optional parameters * @returns Promise<Models.VolumeGetResponse> */ get(resourceGroupName: string, volumeResourceName: string, options?: msRest.RequestOptionsBase): Promise<Models.VolumeGetResponse>; /** * @param resourceGroupName Azure resource group name * @param volumeResourceName The identity of the volume. * @param callback The callback */ get(resourceGroupName: string, volumeResourceName: string, callback: msRest.ServiceCallback<Models.VolumeResourceDescription>): void; /** * @param resourceGroupName Azure resource group name * @param volumeResourceName The identity of the volume. * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, volumeResourceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.VolumeResourceDescription>): void; get(resourceGroupName: string, volumeResourceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.VolumeResourceDescription>, callback?: msRest.ServiceCallback<Models.VolumeResourceDescription>): Promise<Models.VolumeGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, volumeResourceName, options }, getOperationSpec, callback) as Promise<Models.VolumeGetResponse>; } /** * Deletes the volume resource identified by the name. * @summary Deletes the volume resource. * @param resourceGroupName Azure resource group name * @param volumeResourceName The identity of the volume. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteMethod(resourceGroupName: string, volumeResourceName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>; /** * @param resourceGroupName Azure resource group name * @param volumeResourceName The identity of the volume. * @param callback The callback */ deleteMethod(resourceGroupName: string, volumeResourceName: string, callback: msRest.ServiceCallback<void>): void; /** * @param resourceGroupName Azure resource group name * @param volumeResourceName The identity of the volume. * @param options The optional parameters * @param callback The callback */ deleteMethod(resourceGroupName: string, volumeResourceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, volumeResourceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> { return this.client.sendOperationRequest( { resourceGroupName, volumeResourceName, options }, deleteMethodOperationSpec, callback); } /** * Gets the information about all volume resources in a given resource group. The information * include the description and other properties of the Volume. * @summary Gets all the volume resources in a given resource group. * @param resourceGroupName Azure resource group name * @param [options] The optional parameters * @returns Promise<Models.VolumeListByResourceGroupResponse> */ listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.VolumeListByResourceGroupResponse>; /** * @param resourceGroupName Azure resource group name * @param callback The callback */ listByResourceGroup(resourceGroupName: string, callback: msRest.ServiceCallback<Models.VolumeResourceDescriptionList>): void; /** * @param resourceGroupName Azure resource group name * @param options The optional parameters * @param callback The callback */ listByResourceGroup(resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.VolumeResourceDescriptionList>): void; listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.VolumeResourceDescriptionList>, callback?: msRest.ServiceCallback<Models.VolumeResourceDescriptionList>): Promise<Models.VolumeListByResourceGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, options }, listByResourceGroupOperationSpec, callback) as Promise<Models.VolumeListByResourceGroupResponse>; } /** * Gets the information about all volume resources in a given resource group. The information * include the description and other properties of the volume. * @summary Gets all the volume resources in a given subscription. * @param [options] The optional parameters * @returns Promise<Models.VolumeListBySubscriptionResponse> */ listBySubscription(options?: msRest.RequestOptionsBase): Promise<Models.VolumeListBySubscriptionResponse>; /** * @param callback The callback */ listBySubscription(callback: msRest.ServiceCallback<Models.VolumeResourceDescriptionList>): void; /** * @param options The optional parameters * @param callback The callback */ listBySubscription(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.VolumeResourceDescriptionList>): void; listBySubscription(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.VolumeResourceDescriptionList>, callback?: msRest.ServiceCallback<Models.VolumeResourceDescriptionList>): Promise<Models.VolumeListBySubscriptionResponse> { return this.client.sendOperationRequest( { options }, listBySubscriptionOperationSpec, callback) as Promise<Models.VolumeListBySubscriptionResponse>; } /** * Gets the information about all volume resources in a given resource group. The information * include the description and other properties of the Volume. * @summary Gets all the volume resources in a given resource group. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.VolumeListByResourceGroupNextResponse> */ listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.VolumeListByResourceGroupNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listByResourceGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.VolumeResourceDescriptionList>): 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.VolumeResourceDescriptionList>): void; listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.VolumeResourceDescriptionList>, callback?: msRest.ServiceCallback<Models.VolumeResourceDescriptionList>): Promise<Models.VolumeListByResourceGroupNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listByResourceGroupNextOperationSpec, callback) as Promise<Models.VolumeListByResourceGroupNextResponse>; } /** * Gets the information about all volume resources in a given resource group. The information * include the description and other properties of the volume. * @summary Gets all the volume resources in a given subscription. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.VolumeListBySubscriptionNextResponse> */ listBySubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.VolumeListBySubscriptionNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listBySubscriptionNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.VolumeResourceDescriptionList>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listBySubscriptionNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.VolumeResourceDescriptionList>): void; listBySubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.VolumeResourceDescriptionList>, callback?: msRest.ServiceCallback<Models.VolumeResourceDescriptionList>): Promise<Models.VolumeListBySubscriptionNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listBySubscriptionNextOperationSpec, callback) as Promise<Models.VolumeListBySubscriptionNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const createOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabricMesh/volumes/{volumeResourceName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.volumeResourceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "volumeResourceDescription", mapper: { ...Mappers.VolumeResourceDescription, required: true } }, responses: { 200: { bodyMapper: Mappers.VolumeResourceDescription }, 201: { bodyMapper: Mappers.VolumeResourceDescription }, 202: {}, default: { bodyMapper: Mappers.ErrorModel } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabricMesh/volumes/{volumeResourceName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.volumeResourceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.VolumeResourceDescription }, default: { bodyMapper: Mappers.ErrorModel } }, serializer }; const deleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabricMesh/volumes/{volumeResourceName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.volumeResourceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.ErrorModel } }, serializer }; const listByResourceGroupOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabricMesh/volumes", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.VolumeResourceDescriptionList }, default: { bodyMapper: Mappers.ErrorModel } }, serializer }; const listBySubscriptionOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/providers/Microsoft.ServiceFabricMesh/volumes", urlParameters: [ Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.VolumeResourceDescriptionList }, default: { bodyMapper: Mappers.ErrorModel } }, serializer }; const listByResourceGroupNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.VolumeResourceDescriptionList }, default: { bodyMapper: Mappers.ErrorModel } }, serializer }; const listBySubscriptionNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.VolumeResourceDescriptionList }, default: { bodyMapper: Mappers.ErrorModel } }, serializer };
the_stack
import joynr from "../../../../main/js/joynr"; import * as RadioProxy from "../../../generated/joynr/vehicle/RadioProxy"; import RadioStation from "../../../generated/joynr/vehicle/radiotypes/RadioStation"; import ErrorList from "../../../generated/joynr/vehicle/radiotypes/ErrorList"; import Country from "../../../generated/joynr/datatypes/exampleTypes/Country"; import StringMap from "../../../generated/joynr/datatypes/exampleTypes/StringMap"; import ComplexStructMap from "../../../generated/joynr/datatypes/exampleTypes/ComplexStructMap"; import ComplexStruct from "../../../generated/joynr/datatypes/exampleTypes/ComplexStruct"; import ComplexTestType from "../../../generated/joynr/tests/testTypes/ComplexTestType"; import End2EndAbstractTest from "../End2EndAbstractTest"; import ProviderRuntimeException = require("joynr/joynr/exceptions/ProviderRuntimeException"); import { reversePromise } from "../../testUtil"; import ApplicationException = require("../../../../main/js/joynr/exceptions/ApplicationException"); describe("libjoynr-js.integration.end2end.rpc", () => { let subscriptionQosOnChange: any; let radioProxy: RadioProxy; const abstractTest = new End2EndAbstractTest("End2EndRPCTest", "TestEnd2EndCommProviderProcess"); beforeAll(async () => { const settings = await abstractTest.beforeEach(); subscriptionQosOnChange = new joynr.proxy.OnChangeSubscriptionQos({ minIntervalMs: 50 }); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion radioProxy = settings.radioProxy!; }); it("gets the attribute", async () => { await abstractTest.getAttribute("isOn", true); }); it("gets the enumAttribute", async () => { await abstractTest.getAttribute("enumAttribute", Country.GERMANY); }); it("gets the enumArrayAttribute", async () => { await abstractTest.getAttribute("enumArrayAttribute", [Country.GERMANY]); }); it("get/sets the complexStructMapAttribute", async () => { const complexStruct = new ComplexStruct({ num32: 1, num64: 2, data: [1, 2, 3], str: "string" }); const complexStructMap1 = new ComplexStructMap({ key1: complexStruct }); const complexStructMap2 = new ComplexStructMap({ key2: complexStruct }); await abstractTest.setAttribute("complexStructMapAttribute", complexStructMap1); await abstractTest.getAttribute("complexStructMapAttribute", complexStructMap1); await abstractTest.setAttribute("complexStructMapAttribute", complexStructMap2); await abstractTest.getAttribute("complexStructMapAttribute", complexStructMap2); }); it("gets an exception for failingSyncAttribute", async () => { await abstractTest.getFailingAttribute("failingSyncAttribute"); }); it("gets an exception for failingAsyncAttribute", async () => { await abstractTest.getFailingAttribute("failingAsyncAttribute"); }); it("sets the enumArrayAttribute", async () => { let value: Country[] = []; await abstractTest.setAttribute("enumArrayAttribute", value); await abstractTest.getAttribute("enumArrayAttribute", value); value = [Country.GERMANY, Country.AUSTRIA, Country.AUSTRALIA, Country.CANADA, Country.ITALY]; await abstractTest.setAttribute("enumArrayAttribute", value); await abstractTest.getAttribute("enumArrayAttribute", value); }); it("sets the typeDef attributes", async () => { const value = new RadioStation({ name: "TestEnd2EndComm.typeDefForStructAttribute.RadioStation", byteBuffer: [] }); await abstractTest.setAttribute("typeDefForStruct", value); await abstractTest.getAttribute("typeDefForStruct", value); const otherValue = 1234543; await abstractTest.setAttribute("typeDefForPrimitive", otherValue); await abstractTest.getAttribute("typeDefForPrimitive", otherValue); }); it("get/sets the attribute with starting capital letter", async () => { await abstractTest.setAttribute("StartWithCapitalLetter", true); await abstractTest.getAttribute("StartWithCapitalLetter", true); await abstractTest.setAttribute("StartWithCapitalLetter", false); await abstractTest.getAttribute("StartWithCapitalLetter", false); }); it("sets the attribute", async () => { await abstractTest.setAttribute("isOn", true); await abstractTest.getAttribute("isOn", true); await abstractTest.setAttribute("isOn", false); await abstractTest.getAttribute("isOn", false); }); it("sets the enumAttribute", async () => { await abstractTest.setAttribute("enumAttribute", Country.AUSTRIA); await abstractTest.getAttribute("enumAttribute", Country.AUSTRIA); await abstractTest.setAttribute("enumAttribute", Country.AUSTRALIA); await abstractTest.getAttribute("enumAttribute", Country.AUSTRALIA); }); it("sets the byteBufferAttribute", async () => { const testByteBuffer = [1, 2, 3, 4]; await abstractTest.setAttribute("byteBufferAttribute", testByteBuffer); await abstractTest.getAttribute("byteBufferAttribute", testByteBuffer); await abstractTest.setAttribute("byteBufferAttribute", testByteBuffer); await abstractTest.getAttribute("byteBufferAttribute", testByteBuffer); }); it("sets the stringMapAttribute", async () => { const stringMap = new StringMap({ key1: "value1" }); await abstractTest.setAttribute("stringMapAttribute", stringMap); await abstractTest.getAttribute("stringMapAttribute", stringMap); await abstractTest.setAttribute("stringMapAttribute", stringMap); await abstractTest.getAttribute("stringMapAttribute", stringMap); }); it("call methodFireAndForgetWithoutParams and expect to call the provider", async () => { const spy = await abstractTest.setupSubscriptionAndReturnSpy( "fireAndForgetCallArrived", subscriptionQosOnChange ); await abstractTest.callOperation("methodFireAndForgetWithoutParams", {}); await abstractTest.expectPublication(spy, (call: any) => { expect(call[0].methodName).toEqual("methodFireAndForgetWithoutParams"); }); }); it("call methodFireAndForget and expect to call the provider", async () => { const spy = await abstractTest.setupSubscriptionAndReturnSpy( "fireAndForgetCallArrived", subscriptionQosOnChange ); await abstractTest.callOperation("methodFireAndForget", { intIn: 0, stringIn: "methodFireAndForget", complexTestTypeIn: new ComplexTestType({ a: 0, b: 1 }) }); await abstractTest.expectPublication(spy, (call: any) => { expect(call[0].methodName).toEqual("methodFireAndForget"); }); }); it("checks whether the provider stores the attribute value", async () => { const recursions = 5; const value = await abstractTest.setAndTestAttribute("isOn", recursions - 1); expect(value).toEqual(0); }); it("can call an operation successfully (Provider sync, String parameter)", async () => { await abstractTest.callOperation("addFavoriteStation", { radioStation: "stringStation" }); }); it("can call an operation successfully (Complex map parameter)", async () => { await abstractTest.callOperation("methodWithComplexMap", { complexStructMap: new ComplexStructMap({}) }); }); it("can call an operation and get a ProviderRuntimeException (Provider sync, String parameter)", async () => { await expect( radioProxy.addFavoriteStation({ radioStation: "stringStationerror" }) ).rejects.toBeInstanceOf(ProviderRuntimeException); }); it("can call an operation and get an ApplicationException (Provider sync, String parameter)", async () => { const exception = await reversePromise( radioProxy.addFavoriteStation({ radioStation: "stringStationerrorApplicationException" }) ); expect(exception).toBeInstanceOf(ApplicationException); expect(exception.error).toEqual(ErrorList.EXAMPLE_ERROR_2); }); it("can call an operation successfully (Provider async, String parameter)", async () => { await radioProxy.addFavoriteStation({ radioStation: "stringStationasync" }); }); it("can call an operation and get a ProviderRuntimeException (Provider async, String parameter)", async () => { await expect( radioProxy.addFavoriteStation({ radioStation: "stringStationasyncerror" }) ).rejects.toBeInstanceOf(ProviderRuntimeException); }); it("can call an operation and get an ApplicationException (Provider async, String parameter)", async () => { const exception = await reversePromise( radioProxy.addFavoriteStation({ radioStation: "stringStationasyncerrorApplicationException" }) ); expect(exception).toBeInstanceOf(ApplicationException); expect(exception.error).toEqual(ErrorList.EXAMPLE_ERROR_1); }); it("can call an operation (parameter of complex type)", async () => { await abstractTest.callOperation("addFavoriteStation", { radioStation: "stringStation" }); }); it("can call an operation (parameter of byteBuffer type", async () => { await abstractTest.callOperation( "methodWithByteBuffer", { input: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] }, { result: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] } ); }); it("can call an operation with working parameters and return type", async () => { await abstractTest.callOperation( "addFavoriteStation", { radioStation: 'truelyContainingTheString"True"' }, { returnValue: true } ); await abstractTest.callOperation( "addFavoriteStation", { radioStation: "This is false!" }, { returnValue: false } ); await abstractTest.callOperation( "addFavoriteStation", { radioStation: new RadioStation({ name: 'truelyContainingTheRadioStationString"True"', byteBuffer: [] }) }, { returnValue: true } ); await abstractTest.callOperation( "addFavoriteStation", { radioStation: new RadioStation({ name: "This is a false RadioStation!", byteBuffer: [] }) }, { returnValue: false } ); }); it("can call an operation with typedef arguments", async () => { const typeDefStructInput = new RadioStation({ name: "TestEnd2EndComm.methodWithTypeDef.RadioStation", byteBuffer: [] }); const typeDefPrimitiveInput = 1234543; await abstractTest.callOperation( "methodWithTypeDef", { typeDefStructInput, typeDefPrimitiveInput }, { typeDefStructOutput: typeDefStructInput, typeDefPrimitiveOutput: typeDefPrimitiveInput } ); }); it("can call an operation with enum arguments and enum return type", async () => { await abstractTest.callOperation( "operationWithEnumsAsInputAndOutput", { enumInput: Country.GERMANY, enumArrayInput: [] }, { enumOutput: Country.GERMANY } ); await abstractTest.callOperation( "operationWithEnumsAsInputAndOutput", { enumInput: Country.GERMANY, enumArrayInput: [Country.AUSTRIA] }, { enumOutput: Country.AUSTRIA } ); await abstractTest.callOperation( "operationWithEnumsAsInputAndOutput", { enumInput: Country.GERMANY, enumArrayInput: [Country.AUSTRIA, Country.GERMANY, Country.AUSTRALIA] }, { enumOutput: Country.AUSTRIA } ); await abstractTest.callOperation( "operationWithEnumsAsInputAndOutput", { enumInput: Country.GERMANY, enumArrayInput: [Country.CANADA, Country.AUSTRIA, Country.ITALY] }, { enumOutput: Country.CANADA } ); }); it("can call an operation with multiple return values and async provider", async () => { const inputData = { enumInput: Country.GERMANY, enumArrayInput: [Country.GERMANY, Country.ITALY], stringInput: "StringTest", syncTest: false }; await abstractTest.callOperation("operationWithMultipleOutputParameters", inputData, { enumArrayOutput: inputData.enumArrayInput, enumOutput: inputData.enumInput, stringOutput: inputData.stringInput, booleanOutput: inputData.syncTest }); }); it("can call an operation with multiple return values and sync provider", async () => { const inputData = { enumInput: Country.GERMANY, enumArrayInput: [Country.GERMANY, Country.ITALY], stringInput: "StringTest", syncTest: true }; await abstractTest.callOperation("operationWithMultipleOutputParameters", inputData, { enumArrayOutput: inputData.enumArrayInput, enumOutput: inputData.enumInput, stringOutput: inputData.stringInput, booleanOutput: inputData.syncTest }); }); it("can call an operation with enum arguments and enum array as return type", async () => { await abstractTest.callOperation( "operationWithEnumsAsInputAndEnumArrayAsOutput", { enumInput: Country.GERMANY, enumArrayInput: [] }, { enumOutput: [Country.GERMANY] } ); await abstractTest.callOperation( "operationWithEnumsAsInputAndEnumArrayAsOutput", { enumInput: Country.GERMANY, enumArrayInput: [Country.AUSTRIA] }, { enumOutput: [Country.AUSTRIA, Country.GERMANY] } ); await abstractTest.callOperation( "operationWithEnumsAsInputAndEnumArrayAsOutput", { enumInput: Country.GERMANY, enumArrayInput: [Country.AUSTRIA, Country.GERMANY, Country.AUSTRALIA] }, { enumOutput: [Country.AUSTRIA, Country.GERMANY, Country.AUSTRALIA, Country.GERMANY] } ); await abstractTest.callOperation( "operationWithEnumsAsInputAndEnumArrayAsOutput", { enumInput: Country.GERMANY, enumArrayInput: [Country.CANADA, Country.AUSTRIA, Country.ITALY] }, { enumOutput: [Country.CANADA, Country.AUSTRIA, Country.ITALY, Country.GERMANY] } ); }); it("can call an operation with double array as argument and string array as return type", async () => { await abstractTest.callOperation( "methodWithSingleArrayParameters", { doubleArrayArg: [0.01, 1.1, 2.2, 3.3] }, { stringArrayOut: ["0.01", "1.1", "2.2", "3.3"] } ); }); it("attributes are working with predefined implementation on provider side", async () => { await abstractTest.setAndTestAttribute("attrProvidedImpl", 0); }); it("operation is working with predefined implementation on provider side", async () => { const testArgument = "This is my test argument"; await abstractTest.callOperation( "methodProvidedImpl", { arg: testArgument }, { returnValue: testArgument } ); }); afterAll(abstractTest.afterEach); });
the_stack
Component Name : Amexio Dropdown Component Selector : <amexio-dropdown> Component Description : Drop-Down component has been created to render N numbers of drop-down items based on data-set configured. Data-set can be configured using HTTP call OR Define fix number of dropdown-items. User can configure different attributes for enabling filter, multi-select, maximum selection in case of multi select. */ import { animate, state, style, transition, trigger } from '@angular/animations'; import { AfterViewInit, ChangeDetectorRef, Component, ContentChild, ElementRef, EventEmitter, forwardRef, Input, OnInit, Output, Renderer2, TemplateRef, ViewChild, } from '@angular/core'; import { ControlValueAccessor, FormControl, NG_VALIDATORS, NG_VALUE_ACCESSOR, NgModel, Validators } from '@angular/forms'; import { EventBaseComponent } from '../../base/event.base.component'; import { CommonDataService } from '../../services/data/common.data.service'; import { DisplayFieldService } from '../../services/data/display.field.service'; import { debounceTime } from 'rxjs/operators'; @Component({ selector: 'amexio-dropdown', templateUrl: './dropdown.component.html', animations: [ trigger('changeState', [ state('visible', style({ 'max-height': '200px', })), state('hidden', style({ 'max-height': '0px', })), transition('*=>*', animate('200ms')), ]), ], providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => AmexioDropDownComponent), multi: true, }, { provide: NG_VALIDATORS, useExisting: forwardRef(() => AmexioDropDownComponent), multi: true, }], }) export class AmexioDropDownComponent extends EventBaseComponent<any> implements OnInit, ControlValueAccessor, Validators { /* Properties name : field-label datatype : string version : 4.0 onwards default : description : The label of this field */ @Input('field-label') fieldlabel: string; /* Properties name : allow-blank datatype : string version : 4.0 onwards default : description : Sets if field is required */ @Input('allow-blank') allowblank = true; /* Properties name : data datatype : any version : 4.0 onwards default : description : Local data for dropdown. */ _data: any; componentLoaded: boolean; @Input('data') set data(value: any) { this._data = value; if (this.componentLoaded) { this.setData(this._data); } } get data(): any { return this._data; } /* Properties name : data-reader datatype : string version : 4.0 onwards default : description : Key in JSON datasource for records */ @Input('data-reader') datareader: string; /* Properties name : http-method datatype : string version : 4.0 onwards default : description : Type of HTTP call, POST,GET. */ @Input('http-method') httpmethod: string; /* Properties name : http-url datatype : string version : 4.0 onwards default : description : REST url for fetching datasource. */ @Input('http-url') httpurl: string; /* Properties name : display-field datatype : string version : 4.0 onwards default : description : Name of key inside response data to display on ui. */ @Input('display-field') displayfield: string; /* Properties name : value-field datatype : string version : 4.0 onwards default : description : Name of key inside response data.use to send to backend */ @Input('value-field') valuefield: string; /* Properties name : search datatype : boolean version : 4.0 onwards default : false description : true for search box enable */ @Input() search: boolean; /* Properties name : readonly datatype : boolean version : 4.2.1 onwards default : false description : true for set dropdown input readonly. */ @Input() readonly: boolean; /* Properties name : multi-select datatype : boolean version : 4.0 onwards default : false description : true for select multiple options */ @Input('multi-select') multiselect: boolean; @Input('button-label') buttonLabel = 'Ok'; @ViewChild('dropdownitems', { read: ElementRef }) public dropdownitems: ElementRef; displayValue = ''; filteredOptions: any[] = []; selectAllFlag = false; /* Events name : onBlur datatype : any version : 4.0 onwards default : description : On blur event */ @Output() onBlur: any = new EventEmitter<any>(); /* Events name : input datatype : any version : none default : description : On input event field. */ @Output() input: any = new EventEmitter<any>(); /* Events name : focus datatype : any version : none default : description : On field focus event */ @Output() focus: any = new EventEmitter<any>(); /* Events name : onSingleSelect datatype : any version : none default : description : Fire when drop down item selected. */ @Output() onSingleSelect: any = new EventEmitter<any>(); @Output() onRecordSelect: any = new EventEmitter<any>(); /* Events name : onMultiSelect datatype : any version :none default : description : Fire when multiple record select in drop down.this event is only applied when multi-select=true */ @Output() onMultiSelect: any = new EventEmitter<any>(); /* Events name : onClick datatype : any version :none default : description : On record select event.this event is only for normal dropdown. */ @Output() onClick: any = new EventEmitter<any>(); showToolTip: boolean; /* Properties name : place-holder datatype : string version : 4.0 onwards default : description : Show place-holder inside dropdown component*/ @Input('place-holder') placeholder = ''; /* Properties name : disabled datatype : boolean version : 4.0 onwards default : false description : If true will not react on any user events and show disable icon over*/ @Input() disabled: boolean; /* Properties name : icon-feedback datatype : boolean version : 4.0 onwards default : false description : */ @Input('icon-feedback') iconfeedback: boolean; /* Properties name : font-style datatype : string version : 4.0 onwards default : description : Set font-style to field */ @Input('font-style') fontstyle: string; /* Properties name : font-family datatype : string version : 4.0 onwards default : description : Set font-family to field */ @Input('font-family') fontfamily: string; /* Properties name : font-size datatype : string version : 4.0 onwards default : description : Set font-size to field */ @Input('font-size') fontsize: string; /* Properties name : has-label datatype : boolean version : 4.0 onwards default : false description : flag to set label */ @Input('has-label') haslabel = true; /* Properties name : enable-popover datatype : boolean version : 4.0 onwards default :false description : Set enable / disable popover. */ @Input('enable-popover') enablepopover: boolean; @Input('enable-sort') enablesort = false; @Input('sort') sort = ''; @Input('enable-checkbox') enablecheckbox = false; @Input('mask-loader') maskloader1 = false; helpInfoMsg: string; _errormsg: string; get errormsg(): string { return this._errormsg; } @Input('error-msg') set errormsg(value: string) { this.helpInfoMsg = value + '<br/>'; } @ContentChild('amexioBodyTmpl') bodyTemplate: TemplateRef<any>; posixUp: boolean; isValid: boolean; selectedindex = -1; responseData: any; previousData: any; viewData: any; componentId: string; multiselectValues: any[] = []; maskloader = true; activedescendant = 'aria-activedescendant'; key = 'index'; // The internal dataviews model @Output() isComponentValid: any = new EventEmitter<any>(); @Input('name') name: string; constructor( public dataService: CommonDataService, private displayFieldService: DisplayFieldService, public element: ElementRef, public renderer: Renderer2, _cd: ChangeDetectorRef, ) { super(renderer, element, _cd); } ngOnInit() { if (!this.enablecheckbox) { this.hideDropdown = true; } this.name = this.generateName(this.name, this.fieldlabel, 'dropdowninput'); this.componentId = this.createCompId('dropdown', this.name); this.isValid = this.allowblank; this.isComponentValid.emit(this.allowblank); if (this.httpmethod && this.httpurl) { this.dataService.fetchData(this.httpurl, this.httpmethod).subscribe((response: any) => { this.responseData = response; }, (error) => { }, () => { this.setData(this.responseData); }); } else if (this.data) { this.previousData = JSON.parse(JSON.stringify(this.data)); this.setData(this.data); } this.componentLoaded = true; } setData(httpResponse: any) { // Check if key is added? let responsedata = httpResponse; if (this.datareader != null) { this.multiselectValues = []; const dr = this.datareader.split('.'); if (dr) { for (const ir of dr) { responsedata = responsedata[ir]; } } } else { responsedata = httpResponse; } this.setResponseData(responsedata); this.multiSelection(); this.setUserSelection(); this.maskloader = false; } setResponseData(responsedata: any) { if (responsedata) { if (this.enablesort === true && (this.sort === '' || this.sort.toLowerCase() === 'asc')) { this.sortDataAscending(responsedata); } else if (this.enablesort === true && this.sort.toLowerCase() === 'desc') { this.sortDataDescending(responsedata); } else if (this.enablesort === false) { this.viewData = responsedata; this.filteredOptions = this.viewData; this.generateIndex(this.filteredOptions); } } } sortDataAscending(data: any) { this.viewData = data.sort((a: any, b: any) => this.displayFieldService.findValue(this.displayfield, a).toLowerCase() !== this.displayFieldService.findValue(this.displayfield, b).toLowerCase() ? this.displayFieldService.findValue(this.displayfield, a).toLowerCase() < this.displayFieldService.findValue(this.displayfield, b).toLowerCase() ? -1 : 1 : 0); this.filteredOptions = this.viewData; this.generateIndex(this.filteredOptions); } sortDataDescending(data: any) { this.viewData = data.sort((a: any, b: any) => this.displayFieldService.findValue(this.displayfield, a).toLowerCase() !== this.displayFieldService.findValue(this.displayfield, b).toLowerCase() ? this.displayFieldService.findValue(this.displayfield, a).toLowerCase() > this.displayFieldService.findValue(this.displayfield, b).toLowerCase() ? -1 : 1 : 0); this.filteredOptions = this.viewData; this.generateIndex(this.filteredOptions); } generateIndex(data: any) { data.forEach((element: any, index: number) => { element['index'] = this.componentId + 'listitem' + index; }); } multiSelection() { if (this.multiselect && this.viewData) { let preSelectedMultiValues = ''; const optionsChecked: any = []; this.viewData.forEach((row: any) => { if (row.hasOwnProperty('checked')) { if (row.checked) { optionsChecked.push(row[this.valuefield]); this.multiselectValues.push(row); preSelectedMultiValues === '' ? preSelectedMultiValues += this.displayFieldService.findValue(this.displayfield, row) : preSelectedMultiValues += ', ' + this.displayFieldService.findValue(this.displayfield, row); } } else { row['checked'] = false; } }); this.bindData(); } } bindData() { if (this.value && this.multiselect) { this.bindMultiselectModel(); } else { this.displayValue = this.setMultiSelect(); } } bindMultiselectModel() { if (this.value && this.multiselect && this.viewData.length > 0) { this.displayValue = this.value; this.bindMultiSelectModelData(this.value); } } splitData(): any { let data: any[] = []; if (this.value && this.multiselect) { this.displayValue = this.value; data = this.value.split(','); } return data; } bindMultiSelectModelData(valueArray: any[]) { let preSelectedValues = ''; let res: any[] = []; res = this.splitData(); this.viewData.forEach((row: any) => { if (res.length > 0) { res.forEach((valueData: any) => { if (row[this.valuefield] === valueData) { row['checked'] = true; preSelectedValues === '' ? preSelectedValues += this.displayFieldService.findValue(this.displayfield, row) : preSelectedValues += ', ' + this.displayFieldService.findValue(this.displayfield, row); } }); } else { if (row.checked) { row['checked'] = false; } } }); } setUserSelection() { // Set user selection if (this.innerValue != null) { const valueKey = this.valuefield; const displayKey = this.displayfield; const val = this.innerValue; if (this.viewData.length > 0) { this.viewData.forEach((item: any) => { if (item[valueKey] === val) { this.isValid = true; this.isComponentValid.emit(true); this.displayValue = item[displayKey]; delete item[this.key]; this.onSingleSelect.emit(item); } }); } } } enableChkbox() { debounceTime(300); if (this.enablecheckbox) { this.dropFlag = true; } } emitItem(selectedItem: any) { if (selectedItem.hasOwnProperty('item')) { this.value = selectedItem.item[this.valuefield]; this.displayValue = this.displayFieldService.findValue(this.displayfield, selectedItem.item); } else { this.value = selectedItem[this.valuefield]; this.displayValue = this.displayFieldService.findValue(this.displayfield, selectedItem); } this.multiselect ? this.showToolTip = true : this.showToolTip = false; if (selectedItem.hasOwnProperty('item')) { delete selectedItem.item[this.key]; } else { delete selectedItem[this.key]; } if (selectedItem.hasOwnProperty('item')) { this.onSingleSelect.emit(selectedItem.item); } else { this.onSingleSelect.emit(selectedItem); } if (selectedItem.hasOwnProperty('item')) { this.onRecordSelect.emit(selectedItem.item); } else { this.onRecordSelect.emit(selectedItem); } } validateChkbox() { this.isValid = true; if (!this.enablecheckbox) { this.hideDropdown = true; this.hide(); } this.isComponentValid.emit(true); } setFlags() { this.selectAllFlag = false; this.multiselectValues = []; } chkFlag(selectedItem: any) { if (selectedItem.hasOwnProperty('item')) { if (selectedItem.item.hasOwnProperty('checked')) { selectedItem.item.checked = !selectedItem.item.checked; } } else if (selectedItem.hasOwnProperty('checked')) { selectedItem.checked = !selectedItem.checked; } } onItemSelect(selectedItem: any) { this.enableChkbox(); if (this.multiselect) { this.setFlags(); const optionsChecked: any = []; if ((selectedItem.hasOwnProperty('item')) || (selectedItem.hasOwnProperty('checked'))) { this.chkFlag(selectedItem); this.filteredOptions.forEach((row: any) => { if (row.checked) { optionsChecked.push(row[this.valuefield]); this.multiselectValues.push(row); } }); this.innerValue = optionsChecked; this.checkboxMethod(selectedItem); if (!this.enablecheckbox) { this.onMultiSelect.emit(this.multiselectValues); } } // if ends here } else { this.emitItem(selectedItem); } // else ends here this.validateChkbox(); } checkboxMethod(selectedItem: any) { if (!this.enablecheckbox) { this.displayValue = this.setMultiSelect(); } if (this.enablecheckbox) { this.onBaseFocusEvent(selectedItem); } } setMultiSelectData() { this.multiselectValues = []; if (this.innerValue && this.innerValue.length > 0) { const modelValue = this.innerValue; this.filteredOptions.forEach((test) => { if (modelValue.length > 0) { this.modelCheck(modelValue, test); } }); } } modelCheck(modelValue: any, test: any) { modelValue.forEach((mdValue: any) => { if (test[this.valuefield] === mdValue) { if (test.hasOwnProperty('checked')) { test.checked = true; } this.multiselectValues.push(test); } }); } navigateKey(event: any) { } getDisplayText() { if (this.innerValue != null || this.innerValue !== '') { if (this.multiselect) { this.displayValue = this.setMultiSelect(); } else { this.displayValue = ''; this.filteredOptions.forEach((test) => { if (test[this.valuefield] === this.innerValue) { this.displayValue = this.displayFieldService.findValue(this.displayfield, test); } }); this.displayValue = this.displayValue === undefined ? '' : this.displayValue; } } } setMultiSelect() { this.setMultiSelectData(); let multiselectDisplayString: any = ''; let multiselectValueModel: any = ''; this.multiselectValues.forEach((row: any) => { multiselectDisplayString === '' ? multiselectDisplayString += this.displayFieldService.findValue(this.displayfield, row) : multiselectDisplayString += ', ' + this.displayFieldService.findValue(this.displayfield, row); }); this.multiselectValues.forEach((row: any) => { multiselectValueModel === '' ? multiselectValueModel += this.displayFieldService.findValue(this.valuefield, row) : multiselectValueModel += ', ' + this.displayFieldService.findValue(this.valuefield, row); }); this.value = multiselectValueModel; if (this.multiselectValues.length > 0) { return multiselectDisplayString; } else { return ''; } } onDropDownClick(event: any) { if (!this.enablecheckbox) { this.hideDropdown = true; } this.onBaseFocusEvent(event); this.showToolTip = true; this.onClick.emit(event); if (!this.multiselect && this.selectedindex > -1) { this.filteredOptions[this.selectedindex].selected = false; this.selectedindex = -1; this.selectedindex = this.selectedindex + 1; this.filteredOptions[this.selectedindex].selected = true; const inputid = document.getElementById(this.componentId); inputid.setAttribute(this.activedescendant, this.filteredOptions[this.selectedindex].index); this.generateScroll(this.selectedindex); } } generateScroll(index: any) { const listitems = this.element.nativeElement.getElementsByClassName('list-items')[index]; if (listitems) { listitems.scrollIntoView({ behavior: 'smooth' }); } } focusToLast(event: any) { if (this.selectedindex > -1) { this.filteredOptions[this.selectedindex].selected = false; this.selectedindex = this.filteredOptions.length - 1; this.filteredOptions[this.filteredOptions.length - 1].selected = true; const inputid = document.getElementById(this.componentId); inputid.setAttribute(this.activedescendant, this.filteredOptions[this.filteredOptions.length - 1].index); this.generateScroll(this.selectedindex); } } closeOnEScape(event: any) { this.showToolTip = false; if (!this.enablecheckbox) { this.hideDropdown = true; this.hide(); } } onChange(event: string) { this.innerValue = event; this.isValid = true; this.getDisplayText(); this.isComponentValid.emit(true); } onInput(input: any, event: any) { if (event.target.value.length === 0) { this.value = ''; this.displayValue = ''; this.onChangeCallback(this.value); } this.input.emit(); this.isValid = input.valid; this.isComponentValid.emit(input.valid); } onDropDownSearchKeyUp(event: any) { if (this.search && this.viewData) { const keyword = event.target.value; if (keyword != null && keyword !== '' && keyword !== ' ') { this.filteredOptions = []; const search_Term = keyword.toLowerCase(); this.viewData.forEach((row: any) => { if (this.displayFieldService.findValue(this.displayfield, row).toLowerCase().startsWith(search_Term)) { this.filteredOptions.push(row); } }); } if (keyword === '') { this.filteredOptions = this.viewData; } } if (event.keyCode === 8) { this.innerValue = ''; this.displayValue = event.target.value; } if (event.keyCode === 40 || event.keyCode === 38 || event.keyCode === 13) { this.navigateUsingKey(event); } this.onBaseFocusEvent({}); } // navigate using keys navigateUsingKey(event: any) { if (!this.showToolTip) { this.showToolTip = true; } if (this.selectedindex > this.filteredOptions.length) { this.selectedindex = 0; } if (event.keyCode === 40 || event.keyCode === 38 && this.selectedindex < this.filteredOptions.length) { let prevselectedindex = -1; prevselectedindex = this.selectedindex; if (event.keyCode === 40) { this.selectedindex++; } else if (event.keyCode === 38) { this.selectedindex--; } this.navigateFilterOptions(prevselectedindex); } if (event.keyCode === 13 && this.filteredOptions[this.selectedindex]) { this.onItemSelect(this.filteredOptions[this.selectedindex]); } } // for highlight navigated options navigateFilterOptions(previndex: number) { if (this.filteredOptions[this.selectedindex]) { this.filteredOptions[this.selectedindex].selected = true; const inputid = document.getElementById(this.componentId); inputid.setAttribute(this.activedescendant, this.filteredOptions[this.selectedindex].index); } if (this.filteredOptions[previndex]) { this.filteredOptions[previndex].selected = false; this.toNavigateFirstAndLastOption(); } this.generateScroll(this.selectedindex); } // to navigate first and last option toNavigateFirstAndLastOption() { if (this.selectedindex === -1) { this.selectedindex = this.filteredOptions.length - 1; this.filteredOptions[this.filteredOptions.length - 1].selected = true; const inputid = document.getElementById(this.componentId); inputid.setAttribute(this.activedescendant, this.filteredOptions[this.filteredOptions.length - 1].index); } else if (this.selectedindex === this.filteredOptions.length) { this.selectedindex = 0; this.filteredOptions[this.selectedindex].selected = true; const inputid = document.getElementById(this.componentId); inputid.setAttribute(this.activedescendant, this.filteredOptions[this.selectedindex].index); } } // get accessor get value(): any { return this.innerValue; } // set accessor including call the onchange callback set value(v: any) { if (v != null && v !== this.innerValue) { this.innerValue = v; this.onChangeCallback(v); } } // Set touched on blur onblur(event: any) { if (this.self) { this.self = false; } this.hideDropdown = true; if (event.target && event.target.value && this.filteredOptions && this.filteredOptions.length === 1) { const fvalue = event.target.value; const row = this.filteredOptions[0]; const rvalue = this.displayFieldService.findValue(this.displayfield, row); if (fvalue && rvalue && (fvalue.toLowerCase() === rvalue.toLowerCase())) { this.onItemSelect(row); } this.onBaseBlurEvent(event); } if (this.showToolTip) { this.showToolTip = !this.showToolTip; } let flag: any; if (event.target.value !== '') { const result = this.filteredOptions.find((o: any) => o[this.displayfield] === event.target.value); if (result !== undefined) { flag = false; } else { flag = true; } } else { flag = true; } this.onTouchedCallback(); this.onBlur.emit({ event, flag }); } onFocus(elem: any, event: /* */any) { this.hideDropdown = true; this.onBaseFocusEvent(elem); this.showToolTip = true; this.posixUp = this.getListPosition(elem); this.focus.emit(event); } getListPosition(elementRef: any): boolean { const dropdownHeight = 325; // must be same in dropdown.scss if (window.screen.height - (elementRef.getBoundingClientRect().bottom) < dropdownHeight) { return true; } else { return false; } } // From ControlValueAccessor interface writeValue(value: any) { if (value != null) { this.writeChangedValue(value); if (this.value && this.multiselect) { this.bindMultiselectModel(); } } else { this.innerValue = ''; if (this.allowblank) { this.isValid = true; } } } writeChangedValue(value: any) { if (value !== this.innerValue) { let status = false; if (this.viewData && this.viewData.length > 0) { this.viewData.forEach((item: any) => { if (item[this.valuefield] === value) { this.isValid = true; this.displayValue = this.displayFieldService.findValue(this.displayfield, item); status = true; return; } }); } if (!status) { this.displayValue = ''; } this.value = value; } } // From ControlValueAccessor interface registerOnChange(fn: any) { this.onChangeCallback = fn; } // From ControlValueAccessor interface registerOnTouched(fn: any) { this.onTouchedCallback = fn; } onIconClick() { if (!this.enablecheckbox) { this.hideDropdown = true; } if (this.dropdownstyle.visibility === 'hidden') { this.showToolTip = false; } if (!this.disabled) { if (this.showToolTip === undefined || this.showToolTip === false) { this.onBaseFocusEvent({}); } else { this.onBaseBlurEvent({}); } this.showToolTip = !this.showToolTip; } } // THIS MEHTOD CHECK INPUT IS VALID OR NOT checkValidity(): boolean { return this.isValid; } public validate(c: FormControl) { return ((!this.allowblank && (this.value || this.value === 0)) || this.allowblank) ? null : { jsonParseError: { valid: true, }, }; } selectAll(event: any) { this.selectAllFlag = !this.selectAllFlag; const optionsChecked: any = []; this.multiselectValues = []; this.filteredOptions.forEach((row: any) => { if (this.selectAllFlag) { row.checked = true; optionsChecked.push(row[this.valuefield]); this.multiselectValues.push(row); } else { row.checked = false; } }); this.innerValue = optionsChecked; if (!this.enablecheckbox) { this.displayValue = this.setMultiSelect(); } if (this.enablecheckbox) { this.onBaseFocusEvent(event); } this.onMultiSelect.emit(this.multiselectValues); } onSaveClick(event: any) { this.displayValue = this.setMultiSelect(); this.onMultiSelect.emit(this.multiselectValues); this.hideDropdown = true; this.dropFlag = false; this.hide(); } }
the_stack
import { AbiItem, BurnAndReleaseTransaction, getRenNetworkDetails, LockAndMintTransaction, LockChain, Logger, MintChain, NullLogger, RenJSErrors, RenNetwork, RenNetworkDetails, RenNetworkString, TxStatus, } from "@renproject/interfaces"; import { HttpProvider, Provider } from "@renproject/provider"; import { assertType, extractError, fromBase64, isDefined, keccak256, parseV1Selector, SECONDS, sleep, strip0x, toBase64, } from "@renproject/utils"; import BigNumber from "bignumber.js"; import { List } from "immutable"; import { AbstractRenVMProvider } from "../abstract"; import { ParamsQueryBlock, ParamsQueryBlocks, ParamsQueryTx, ParamsQueryTxs, ParamsSubmitBurn, ParamsSubmitMint, RenVMParams, RenVMResponses, ResponseQueryBurnTx, ResponseQueryMintTx, RPCMethod, } from "./methods"; import { unmarshalBurnTx, unmarshalFees, unmarshalMintTx } from "./unmarshal"; import { RenVMType } from "./value"; export const generateMintTxHash = ( selector: string, encodedID: string, deposit: string, logger: Logger = NullLogger, ): Buffer => { // Type validation assertType<string>("string", { encodedID, deposit }); const message = `txHash_${selector}_${encodedID}_${deposit}`; const digest = keccak256(Buffer.from(message)); logger.debug("Mint txHash", toBase64(digest), message); return digest; }; export class RenVMProvider implements AbstractRenVMProvider<RenVMParams, RenVMResponses> { public version = () => 1; private readonly network: RenNetwork; public readonly provider: Provider<RenVMParams, RenVMResponses>; sendMessage: RenVMProvider["provider"]["sendMessage"]; private readonly logger: Logger; constructor( network: RenNetwork | RenNetworkString | RenNetworkDetails, provider?: Provider<RenVMParams, RenVMResponses>, logger: Logger = NullLogger, ) { if (!provider) { const rpcUrl = (getRenNetworkDetails(network) || {}).lightnode; try { provider = new HttpProvider<RenVMParams, RenVMResponses>( rpcUrl, logger, ); } catch (error) { if (/Invalid node URL/.exec(String(error && error.message))) { throw new Error( `Invalid network or provider URL: "${ (getRenNetworkDetails(network) || {}).name || String(network) }"`, ); } throw error; } } this.network = network as RenNetwork; this.logger = logger; this.provider = provider; this.sendMessage = async <Method extends keyof RenVMParams & string>( method: Method, request: RenVMParams[Method], retry = 2, timeout = 120 * SECONDS, ) => { try { return await this.provider.sendMessage( method, request, retry, timeout, ); } catch (error) { const errorString = extractError(error); if (/(tx hash=[a-zA-Z0-9+\/=]+ not found)/.exec(errorString)) { error.code = RenJSErrors.RenVMTransactionNotFound; } if (/(insufficient funds)/.exec(errorString)) { error.code = RenJSErrors.AmountTooSmall; } if (/(utxo spent or invalid index)/.exec(errorString)) { error.code = RenJSErrors.DepositSpentOrNotFound; } throw error; } }; } public selector = ({ asset, from, to, }: { asset: string; // eslint-disable-next-line @typescript-eslint/no-explicit-any from: LockChain<any, any, any> | MintChain<any, any>; // eslint-disable-next-line @typescript-eslint/no-explicit-any to: LockChain<any, any, any> | MintChain<any, any>; }): string => { return `${asset}0${from.legacyName || from.name}2${ to.legacyName || from.name }`; }; public queryBlock = async ( blockHeight: ParamsQueryBlock["blockHeight"], retry?: number, ) => this.sendMessage<RPCMethod.MethodQueryBlock>( RPCMethod.MethodQueryBlock, { blockHeight }, retry, ); public queryBlocks = async ( blockHeight: ParamsQueryBlocks["blockHeight"], n: ParamsQueryBlocks["n"], retry?: number, ) => this.sendMessage<RPCMethod.MethodQueryBlocks>( RPCMethod.MethodQueryBlocks, { blockHeight, n }, retry, ); public submitTx = async ( tx: ParamsSubmitBurn["tx"] | ParamsSubmitMint["tx"], retry?: number, ) => this.sendMessage<RPCMethod.MethodSubmitTx>( RPCMethod.MethodSubmitTx, { tx } as ParamsSubmitBurn | ParamsSubmitMint, retry, ); public queryTx = async (txHash: ParamsQueryTx["txHash"], retry?: number) => this.sendMessage<RPCMethod.MethodQueryTx>( RPCMethod.MethodQueryTx, { txHash }, retry, ); public queryTxs = async ( tags: ParamsQueryTxs["tags"], page?: number, pageSize?: number, txStatus?: ParamsQueryTxs["txStatus"], retry?: number, ) => this.sendMessage<RPCMethod.MethodQueryTxs>( RPCMethod.MethodQueryTxs, { tags, page: (page || 0).toString(), pageSize: (pageSize || 0).toString(), txStatus, }, retry, ); public queryNumPeers = async (retry?: number) => this.sendMessage<RPCMethod.MethodQueryNumPeers>( RPCMethod.MethodQueryNumPeers, {}, retry, ); public queryPeers = async (retry?: number) => this.sendMessage<RPCMethod.MethodQueryPeers>( RPCMethod.MethodQueryPeers, {}, retry, ); public queryShards = async (retry?: number) => this.sendMessage<RPCMethod.MethodQueryShards>( RPCMethod.MethodQueryShards, {}, retry, ); public queryStat = async (retry?: number) => this.sendMessage<RPCMethod.MethodQueryStat>( RPCMethod.MethodQueryStat, {}, retry, ); public queryFees = async (retry?: number) => this.sendMessage<RPCMethod.MethodQueryFees>( RPCMethod.MethodQueryFees, {}, retry, ); public getFees = async () => unmarshalFees(await this.queryFees()); public mintTxHash = ({ selector, gHash, outputHashFormat, }: { selector: string; gHash: Buffer; outputHashFormat: string; }): Buffer => { assertType<Buffer>("Buffer", { gHash }); assertType<string>("string", { outputHashFormat }); return generateMintTxHash( selector, toBase64(gHash), outputHashFormat, this.logger, ); }; public submitMint = async ({ selector, nonce, output, payload, to, token, fn, fnABI, tags, }: { selector: string; nonce: Buffer; output: { txindex: string; txid: Buffer }; payload: Buffer; to: string; token: string; fn: string; fnABI: AbiItem[]; tags: [string] | []; }): Promise<Buffer> => { const { txindex, txid } = output; assertType<Buffer>("Buffer", { nonce, payload, txid }); assertType<string>("string", { to, token, fn, txindex }); const response = await this.sendMessage<RPCMethod.MethodSubmitTx>( RPCMethod.MethodSubmitTx, { tx: { to: selector, in: [ // { name: "p" as const, type: RenVMType.ExtEthCompatPayload, value: { abi: toBase64( Buffer.from(JSON.stringify(fnABI)), ), value: toBase64(payload), fn: toBase64(Buffer.from(fn)), }, }, // The hash of the payload data // { name: "phash" as const, type: RenVMType.B32 as const, value: toBase64(pHash) }, // The amount of BTC (in SATs) that has be transferred to the gateway // { name: "amount" as const, type: "u64", as const value: amount }, // The ERC20 contract address on Ethereum for BTC { name: "token" as const, type: RenVMType.ExtTypeEthCompatAddress, value: strip0x(token), }, // The address on the Ethereum blockchain to which BTC will be transferred { name: "to" as const, type: RenVMType.ExtTypeEthCompatAddress, value: strip0x(to), }, // The nonce is used to randomize the gateway { name: "n" as const, type: RenVMType.B32, value: toBase64(nonce), }, // UTXO { name: "utxo" as const, type: RenVMType.ExtTypeBtcCompatUTXO, value: { txHash: toBase64(txid), vOut: txindex, }, }, ], }, tags, }, ); return fromBase64(response.tx.hash); }; public submitBurn = async (params: { selector: string; tags: [string] | []; // v1 burnNonce: BigNumber; }): Promise<Buffer> => { const { selector, burnNonce, tags } = params; const response = await this.sendMessage(RPCMethod.MethodSubmitTx, { tx: { to: selector, in: [ { name: "ref", type: RenVMType.U64, value: burnNonce.decimalPlaces(0).toFixed(), }, ], }, tags, }); return fromBase64(response.tx.hash); }; public readonly queryMintOrBurn = async < T extends LockAndMintTransaction | BurnAndReleaseTransaction, >( _selector: string, utxoTxHash: Buffer, retries?: number, ): Promise<T> => { const response = await this.queryTx(toBase64(utxoTxHash), retries); // Unmarshal transaction. const { asset, from } = parseV1Selector(response.tx.to); if (asset.toUpperCase() === from.toUpperCase()) { return unmarshalMintTx(response as ResponseQueryMintTx) as T; } else { return unmarshalBurnTx(response as ResponseQueryBurnTx) as T; } }; public readonly waitForTX = async < T extends LockAndMintTransaction | BurnAndReleaseTransaction, >( selector: string, utxoTxHash: Buffer, onStatus?: (status: TxStatus) => void, _cancelRequested?: () => boolean, timeout?: number, ): Promise<T> => { assertType<Buffer>("Buffer", { utxoTxHash }); let rawResponse; while (true) { if (_cancelRequested && _cancelRequested()) { throw new Error(`waitForTX cancelled`); } try { const result = await this.queryMintOrBurn<T>( selector, utxoTxHash, ); if (result && result.txStatus === TxStatus.TxStatusDone) { rawResponse = result; break; } else if (onStatus && result && result.txStatus) { onStatus(result.txStatus); } } catch (error) { if ( /(not found)|(not available)/.exec( String((error || {}).message), ) ) { // ignore } else { this.logger.error(String(error)); // TODO: throw unexpected errors } } await sleep(isDefined(timeout) ? timeout : 15 * SECONDS); } return rawResponse as unknown as T; }; /** * selectPublicKey fetches the public key for the RenVM shard handling * the provided contract. * * @param asset The asset for which the public key should be fetched. * @returns The public key hash (20 bytes) as a string. */ public readonly selectPublicKey = async ( _selector: string, asset: string, ): Promise<Buffer> => { // Call the ren_queryShards RPC. const response = await this.queryShards(5); // Prioritize primary shards. const chosenShard = response.shards.sort((a, b) => a.primary && b.primary ? -1 : a.primary ? -1 : b.primary ? 1 : 0, )[0]; if (!chosenShard) { throw new Error( "Unable to load public key from RenVM: no shards found", ); } // Get the gateway pubKey from the gateway with the right asset within // the shard with the lowest total value locked. const tokenGateway = List(chosenShard.gateways) .filter((gateway) => gateway.asset === asset) .first(undefined); if (!tokenGateway) { throw new Error( `Unable to load public key from RenVM: no gateway for the asset ${asset}`, ); } // Use this gateway pubKey to build the gateway address. // return hash160( return fromBase64(tokenGateway.pubKey); }; // In the future, this will be asynchronous. It returns a promise for // compatibility. // eslint-disable-next-line @typescript-eslint/require-await public getNetwork = async (_selector: string): Promise<RenNetwork> => { return this.network; }; public getConfirmationTarget = async ( selector: string, _chain: { name: string }, // eslint-disable-next-line @typescript-eslint/require-await ) => { const { asset } = parseV1Selector(selector); switch (this.network) { case "mainnet": switch (asset) { case "BTC": return 6; case "ZEC": return 24; case "BCH": return 15; case "ETH": return 30; } break; case "testnet": switch (asset) { case "BTC": return 2; case "ZEC": return 6; case "BCH": return 2; case "ETH": return 12; } break; } return undefined; }; public estimateTransactionFee = async ( _asset: string, _lockChain: { name: string; legacyName?: string }, hostChain: { name: string; legacyName?: string }, ): Promise<{ lock: BigNumber; release: BigNumber; mint: number; burn: number; }> => { const allFees = await this.getFees(); const fees = allFees[ hostChain.legacyName ? hostChain.legacyName.toLowerCase() : hostChain.name.toLowerCase() ]; return { ...fees, mint: 25, burn: 15, }; }; }
the_stack
export const WasmOpcode = { // Control flow operators UNREACHABLE : 0x00, NOP : 0x01, BLOCK : 0x02, LOOP : 0x03, IF : 0x04, IF_ELSE : 0x05, END : 0x0b, BR : 0x0c, BR_IF : 0x0d, BR_TABLE : 0x0e, RETURN : 0x0f, // Call operators CALL : 0x10, CALL_INDIRECT : 0x11, //Parametric operators DROP : 0x1a, SELECT : 0x1b, //Variable access GET_LOCAL : 0x20, SET_LOCAL : 0x21, TEE_LOCAL : 0x22, GET_GLOBAL : 0x23, SET_GLOBAL : 0x24, // Memory-related operators I32_LOAD : 0x28, I64_LOAD : 0x29, F32_LOAD : 0x2a, F64_LOAD : 0x2b, I32_LOAD8_S : 0x2c, I32_LOAD8_U : 0x2d, I32_LOAD16_S : 0x2e, I32_LOAD16_U : 0x2f, I64_LOAD8_S : 0x30, I64_LOAD8_U : 0x31, I64_LOAD16_S : 0x32, I64_LOAD16_U : 0x33, I64_LOAD32_S : 0x34, I64_LOAD32_U : 0x35, I32_STORE : 0x36, I64_STORE : 0x37, F32_STORE : 0x38, F64_STORE : 0x39, I32_STORE8 : 0x3a, I32_STORE16 : 0x3b, I64_STORE8 : 0x3c, I64_STORE16 : 0x3d, I64_STORE32 : 0x3e, MEMORY_SIZE : 0x3f, //query the size of memory GROW_MEMORY : 0x40, // Constants I32_CONST : 0x41, I64_CONST : 0x42, F32_CONST : 0x43, F64_CONST : 0x44, //Comparison operators I32_EQZ : 0x45, I32_EQ : 0x46, I32_NE : 0x47, I32_LT_S : 0x48, I32_LT_U : 0x49, I32_GT_S : 0x4a, I32_GT_U : 0x4b, I32_LE_S : 0x4c, I32_LE_U : 0x4d, I32_GE_S : 0x4e, I32_GE_U : 0x4f, I64_EQZ : 0x50, I64_EQ : 0x51, I64_NE : 0x52, I64_LT_S : 0x53, I64_LT_U : 0x54, I64_GT_S : 0x55, I64_GT_U : 0x56, I64_LE_S : 0x57, I64_LE_U : 0x58, I64_GE_S : 0x59, I64_GE_U : 0x5a, F32_EQ : 0x5b, F32_NE : 0x5c, F32_LT : 0x5d, F32_GT : 0x5e, F32_LE : 0x5f, F32_GE : 0x60, F64_EQ : 0x61, F64_NE : 0x62, F64_LT : 0x63, F64_GT : 0x64, F64_LE : 0x65, F64_GE : 0x66, //Numeric operators I32_CLZ : 0x67, I32_CTZ : 0x68, I32_POPCNT : 0x69, I32_ADD : 0x6a, I32_SUB : 0x6b, I32_MUL : 0x6c, I32_DIV_S : 0x6d, I32_DIV_U : 0x6e, I32_REM_S : 0x6f, I32_REM_U : 0x70, I32_AND : 0x71, I32_OR : 0x72, I32_XOR : 0x73, I32_SHL : 0x74, I32_SHR_S : 0x75, I32_SHR_U : 0x76, I32_ROTL : 0x77, I32_ROTR : 0x78, I64_CLZ : 0x79, I64_CTZ : 0x7a, I64_POPCNT : 0x7b, I64_ADD : 0x7c, I64_SUB : 0x7d, I64_MUL : 0x7e, I64_DIV_S : 0x7f, I64_DIV_U : 0x80, I64_REM_S : 0x81, I64_REM_U : 0x82, I64_AND : 0x83, I64_OR : 0x84, I64_XOR : 0x85, I64_SHL : 0x86, I64_SHR_S : 0x87, I64_SHR_U : 0x88, I64_ROTL : 0x89, I64_ROTR : 0x8a, F32_ABS : 0x8b, F32_NEG : 0x8c, F32_CEIL : 0x8d, F32_FLOOR : 0x8e, F32_TRUNC : 0x8f, F32_NEAREST : 0x90, F32_SQRT : 0x91, F32_ADD : 0x92, F32_SUB : 0x93, F32_MUL : 0x94, F32_DIV : 0x95, F32_MIN : 0x96, F32_MAX : 0x97, F32_COPYSIGN : 0x98, F64_ABS : 0x99, F64_NEG : 0x9a, F64_CEIL : 0x9b, F64_FLOOR : 0x9c, F64_TRUNC : 0x9d, F64_NEAREST : 0x9e, F64_SQRT : 0x9f, F64_ADD : 0xa0, F64_SUB : 0xa1, F64_MUL : 0xa2, F64_DIV : 0xa3, F64_MIN : 0xa4, F64_MAX : 0xa5, F64_COPYSIGN : 0xa6, //Conversions I32_WRAP_I64 : 0xa7, I32_TRUNC_S_F32 : 0xa8, I32_TRUNC_U_F32 : 0xa9, I32_TRUNC_S_F64 : 0xaa, I32_TRUNC_U_F64 : 0xab, I64_EXTEND_S_I32 : 0xac, I64_EXTEND_U_I32 : 0xad, I64_TRUNC_S_F32 : 0xae, I64_TRUNC_U_F32 : 0xaf, I64_TRUNC_S_F64 : 0xb0, I64_TRUNC_U_F64 : 0xb1, F32_CONVERT_S_I32 : 0xb2, F32_CONVERT_U_I32 : 0xb3, F32_CONVERT_S_I64 : 0xb4, F32_CONVERT_U_I64 : 0xb5, F32_DEMOTE_F64 : 0xb6, F64_CONVERT_S_I32 : 0xb7, F64_CONVERT_U_I32 : 0xb8, F64_CONVERT_S_I64 : 0xb9, F64_CONVERT_U_I64 : 0xba, F64_PROMOTE_F32 : 0xbb, //Reinterpretations I32_REINTERPRET_F32 : 0xbc, I64_REINTERPRET_F64 : 0xbd, F32_REINTERPRET_I32 : 0xbe, F64_REINTERPRET_I64 : 0xbf, }; WasmOpcode[WasmOpcode.UNREACHABLE] = "unreachable"; WasmOpcode[WasmOpcode.NOP] = "nop"; WasmOpcode[WasmOpcode.BLOCK] = "block"; WasmOpcode[WasmOpcode.LOOP] = "loop"; WasmOpcode[WasmOpcode.IF] = "if"; WasmOpcode[WasmOpcode.IF_ELSE] = "else"; WasmOpcode[WasmOpcode.END] = "end"; WasmOpcode[WasmOpcode.BR] = "br"; WasmOpcode[WasmOpcode.BR_IF] = "br_if"; WasmOpcode[WasmOpcode.BR_TABLE] = "br_table"; WasmOpcode[WasmOpcode.RETURN] = "return"; // Call operators WasmOpcode[WasmOpcode.CALL] = "call"; WasmOpcode[WasmOpcode.CALL_INDIRECT] = "call_indirect"; //Parametric operators WasmOpcode[WasmOpcode.DROP] = "drop"; WasmOpcode[WasmOpcode.SELECT] = "select"; //Variable access WasmOpcode[WasmOpcode.GET_LOCAL] = "get_local"; WasmOpcode[WasmOpcode.SET_LOCAL] = "set_local"; WasmOpcode[WasmOpcode.TEE_LOCAL] = "tee_local"; WasmOpcode[WasmOpcode.GET_GLOBAL] = "get_global"; WasmOpcode[WasmOpcode.SET_GLOBAL] = "set_global"; // Memory-related operators WasmOpcode[WasmOpcode.I32_LOAD] = "i32.load"; WasmOpcode[WasmOpcode.I64_LOAD] = "i64.load"; WasmOpcode[WasmOpcode.F32_LOAD] = "f32.load"; WasmOpcode[WasmOpcode.F64_LOAD] = "f64.load"; WasmOpcode[WasmOpcode.I32_LOAD8_S] = "i32.load8_s"; WasmOpcode[WasmOpcode.I32_LOAD8_U] = "i32_load8_u"; WasmOpcode[WasmOpcode.I32_LOAD16_S] = "i32_load16_s"; WasmOpcode[WasmOpcode.I32_LOAD16_U] = "i32_load16_u"; WasmOpcode[WasmOpcode.I64_LOAD8_S] = "i64.load8_s"; WasmOpcode[WasmOpcode.I64_LOAD8_U] = "i64.load8_u"; WasmOpcode[WasmOpcode.I64_LOAD16_S] = "i64.load16_s"; WasmOpcode[WasmOpcode.I64_LOAD16_U] = "i64.load16_u"; WasmOpcode[WasmOpcode.I64_LOAD32_S] = "i64.load32_s"; WasmOpcode[WasmOpcode.I64_LOAD32_U] = "i64.load32_u"; WasmOpcode[WasmOpcode.I32_STORE] = "i32.store"; WasmOpcode[WasmOpcode.I64_STORE] = "i64.store"; WasmOpcode[WasmOpcode.F32_STORE] = "f32.store"; WasmOpcode[WasmOpcode.F64_STORE] = "f64.store"; WasmOpcode[WasmOpcode.I32_STORE8] = "i32.store8"; WasmOpcode[WasmOpcode.I32_STORE16] = "i32.store16"; WasmOpcode[WasmOpcode.I64_STORE8] = "i64.store8"; WasmOpcode[WasmOpcode.I64_STORE16] = "i64.store16"; WasmOpcode[WasmOpcode.I64_STORE32] = "i64.store32"; WasmOpcode[WasmOpcode.MEMORY_SIZE] = "current_memory"; WasmOpcode[WasmOpcode.GROW_MEMORY] = "grow_memory"; // Constants WasmOpcode[WasmOpcode.I32_CONST] = "i32.const"; WasmOpcode[WasmOpcode.I64_CONST] = "i64.const"; WasmOpcode[WasmOpcode.F32_CONST] = "f32.const"; WasmOpcode[WasmOpcode.F64_CONST] = "f64.const"; //Comparison operators WasmOpcode[WasmOpcode.I32_EQZ] = "i32.eqz"; WasmOpcode[WasmOpcode.I32_EQ] = "i32.eq"; WasmOpcode[WasmOpcode.I32_NE] = "i32.ne"; WasmOpcode[WasmOpcode.I32_LT_S] = "i32.lt_s"; WasmOpcode[WasmOpcode.I32_LT_U] = "i32.lt_u"; WasmOpcode[WasmOpcode.I32_GT_S] = "i32.gt_s"; WasmOpcode[WasmOpcode.I32_GT_U] = "i32.gt_u"; WasmOpcode[WasmOpcode.I32_LE_S] = "i32.le_s"; WasmOpcode[WasmOpcode.I32_LE_U] = "i32.le_u"; WasmOpcode[WasmOpcode.I32_GE_S] = "i32.ge_s"; WasmOpcode[WasmOpcode.I32_GE_U] = "i32.ge_u"; WasmOpcode[WasmOpcode.I64_EQZ] = "i64.eqz"; WasmOpcode[WasmOpcode.I64_EQ] = "i64.eq"; WasmOpcode[WasmOpcode.I64_NE] = "i64.ne"; WasmOpcode[WasmOpcode.I64_LT_S] = "i64.lt_s"; WasmOpcode[WasmOpcode.I64_LT_U] = "i64.lt_u"; WasmOpcode[WasmOpcode.I64_GT_S] = "i64.gt_s"; WasmOpcode[WasmOpcode.I64_GT_U] = "i64.gt_u"; WasmOpcode[WasmOpcode.I64_LE_S] = "i64.le_s"; WasmOpcode[WasmOpcode.I64_LE_U] = "i64.le_u"; WasmOpcode[WasmOpcode.I64_GE_S] = "i64.ge_s"; WasmOpcode[WasmOpcode.I64_GE_U] = "i64.ge_u"; WasmOpcode[WasmOpcode.F32_EQ] = "f32.eq"; WasmOpcode[WasmOpcode.F32_NE] = "f32.ne"; WasmOpcode[WasmOpcode.F32_LT] = "f32.lt"; WasmOpcode[WasmOpcode.F32_GT] = "f32.gt"; WasmOpcode[WasmOpcode.F32_LE] = "f32.le"; WasmOpcode[WasmOpcode.F32_GE] = "f32.ge"; WasmOpcode[WasmOpcode.F64_EQ] = "f64.eq"; WasmOpcode[WasmOpcode.F64_NE] = "f64.ne"; WasmOpcode[WasmOpcode.F64_LT] = "f64.lt"; WasmOpcode[WasmOpcode.F64_GT] = "f64.gt"; WasmOpcode[WasmOpcode.F64_LE] = "f64.le"; WasmOpcode[WasmOpcode.F64_GE] = "f64.ge"; //Numeric operators WasmOpcode[WasmOpcode.I32_CLZ] = "i32.clz"; WasmOpcode[WasmOpcode.I32_CTZ] = "i32.ctz"; WasmOpcode[WasmOpcode.I32_POPCNT] = "i32.popcnt"; WasmOpcode[WasmOpcode.I32_ADD] = "i32.add"; WasmOpcode[WasmOpcode.I32_SUB] = "i32.sub"; WasmOpcode[WasmOpcode.I32_MUL] = "i32.mul"; WasmOpcode[WasmOpcode.I32_DIV_S] = "i32.div_s"; WasmOpcode[WasmOpcode.I32_DIV_U] = "i32.div_u"; WasmOpcode[WasmOpcode.I32_REM_S] = "i32.rem_s"; WasmOpcode[WasmOpcode.I32_REM_U] = "i32.rem_u"; WasmOpcode[WasmOpcode.I32_AND] = "i32.and"; WasmOpcode[WasmOpcode.I32_OR] = "i32.or"; WasmOpcode[WasmOpcode.I32_XOR] = "i32.xor"; WasmOpcode[WasmOpcode.I32_SHL] = "i32.shl"; WasmOpcode[WasmOpcode.I32_SHR_S] = "i32.shr_s"; WasmOpcode[WasmOpcode.I32_SHR_U] = "i32.shr_u"; WasmOpcode[WasmOpcode.I32_ROTL] = "i32.rotl"; WasmOpcode[WasmOpcode.I32_ROTR] = "i32.rotr"; WasmOpcode[WasmOpcode.I64_CLZ] = "i64.clz"; WasmOpcode[WasmOpcode.I64_CTZ] = "i64.ctz"; WasmOpcode[WasmOpcode.I64_POPCNT] = "i64.popcnt"; WasmOpcode[WasmOpcode.I64_ADD] = "i64.add"; WasmOpcode[WasmOpcode.I64_SUB] = "i64.sub"; WasmOpcode[WasmOpcode.I64_MUL] = "i64.mul"; WasmOpcode[WasmOpcode.I64_DIV_S] = "i64.div_s"; WasmOpcode[WasmOpcode.I64_DIV_U] = "i64.div_u"; WasmOpcode[WasmOpcode.I64_REM_S] = "i64.rem_s"; WasmOpcode[WasmOpcode.I64_REM_U] = "i64.rem_u"; WasmOpcode[WasmOpcode.I64_AND] = "i64.and"; WasmOpcode[WasmOpcode.I64_OR] = "i64.or"; WasmOpcode[WasmOpcode.I64_XOR] = "i64.xor"; WasmOpcode[WasmOpcode.I64_SHL] = "i64.shl"; WasmOpcode[WasmOpcode.I64_SHR_S] = "i64.shr_s"; WasmOpcode[WasmOpcode.I64_SHR_U] = "i64.shr_u"; WasmOpcode[WasmOpcode.I64_ROTL] = "i64.rotl"; WasmOpcode[WasmOpcode.I64_ROTR] = "i64.rotr"; WasmOpcode[WasmOpcode.F32_ABS] = "f32.abs"; WasmOpcode[WasmOpcode.F32_NEG] = "f32.neg"; WasmOpcode[WasmOpcode.F32_CEIL] = "f32.ceil"; WasmOpcode[WasmOpcode.F32_FLOOR] = "f32.floor"; WasmOpcode[WasmOpcode.F32_TRUNC] = "f32.trunc"; WasmOpcode[WasmOpcode.F32_NEAREST] = "f32.nearest"; WasmOpcode[WasmOpcode.F32_SQRT] = "f32.sqrt"; WasmOpcode[WasmOpcode.F32_ADD] = "f32.add"; WasmOpcode[WasmOpcode.F32_SUB] = "f32.sub"; WasmOpcode[WasmOpcode.F32_MUL] = "f32.mul"; WasmOpcode[WasmOpcode.F32_DIV] = "f32.div"; WasmOpcode[WasmOpcode.F32_MIN] = "f32.min"; WasmOpcode[WasmOpcode.F32_MAX] = "f32.max"; WasmOpcode[WasmOpcode.F32_COPYSIGN] = "f32.copysign"; WasmOpcode[WasmOpcode.F64_ABS] = "f64.abs"; WasmOpcode[WasmOpcode.F64_NEG] = "f64.neg"; WasmOpcode[WasmOpcode.F64_CEIL] = "f64.ceil"; WasmOpcode[WasmOpcode.F64_FLOOR] = "f64.floor"; WasmOpcode[WasmOpcode.F64_TRUNC] = "f64.trunc"; WasmOpcode[WasmOpcode.F64_NEAREST] = "f64.nearest"; WasmOpcode[WasmOpcode.F64_SQRT] = "f64.sqrt"; WasmOpcode[WasmOpcode.F64_ADD] = "f64.add"; WasmOpcode[WasmOpcode.F64_SUB] = "f64.sub"; WasmOpcode[WasmOpcode.F64_MUL] = "f64.mul"; WasmOpcode[WasmOpcode.F64_DIV] = "f64.div"; WasmOpcode[WasmOpcode.F64_MIN] = "f64.min"; WasmOpcode[WasmOpcode.F64_MAX] = "f64.max"; WasmOpcode[WasmOpcode.F64_COPYSIGN] = "f64.copysign"; //Conversions WasmOpcode[WasmOpcode.I32_WRAP_I64] = "i32.wrap/i64"; WasmOpcode[WasmOpcode.I32_TRUNC_S_F32] = "i32.trunc_s/f32"; WasmOpcode[WasmOpcode.I32_TRUNC_U_F32] = "i32.trunc_u/f32"; WasmOpcode[WasmOpcode.I32_TRUNC_S_F64] = "i32.trunc_s/f64"; WasmOpcode[WasmOpcode.I32_TRUNC_U_F64] = "i32.trunc_u/f64"; WasmOpcode[WasmOpcode.I64_EXTEND_S_I32] = "i64.extend_s/i32"; WasmOpcode[WasmOpcode.I64_EXTEND_U_I32] = "i64.extend_u/i32"; WasmOpcode[WasmOpcode.I64_TRUNC_S_F32] = "i64.trunc_s/f32"; WasmOpcode[WasmOpcode.I64_TRUNC_U_F32] = "i64.trunc_u/f32"; WasmOpcode[WasmOpcode.I64_TRUNC_S_F64] = "i64.trunc_s/f64"; WasmOpcode[WasmOpcode.I64_TRUNC_U_F64] = "i64.trunc_u/f64"; WasmOpcode[WasmOpcode.F32_CONVERT_S_I32] = "f32.convert_s/i32"; WasmOpcode[WasmOpcode.F32_CONVERT_U_I32] = "f32.convert_u/i32"; WasmOpcode[WasmOpcode.F32_CONVERT_S_I64] = "f32.convert_s/i64"; WasmOpcode[WasmOpcode.F32_CONVERT_U_I64] = "f32.convert_u/i64"; WasmOpcode[WasmOpcode.F32_DEMOTE_F64] = "f32.demote/f64"; WasmOpcode[WasmOpcode.F64_CONVERT_S_I32] = "f64.convert_s/i32"; WasmOpcode[WasmOpcode.F64_CONVERT_U_I32] = "f64.convert_u/i32"; WasmOpcode[WasmOpcode.F64_CONVERT_S_I64] = "f64.convert_s/i64"; WasmOpcode[WasmOpcode.F64_CONVERT_U_I64] = "f64.convert_u/i64"; WasmOpcode[WasmOpcode.F64_PROMOTE_F32] = "f64.promote/f32"; //Reinterpretations WasmOpcode[WasmOpcode.I32_REINTERPRET_F32] = "i32.reinterpret/f32"; WasmOpcode[WasmOpcode.I64_REINTERPRET_F64] = "i64.reinterpret/f64"; WasmOpcode[WasmOpcode.F32_REINTERPRET_I32] = "f32.reinterpret/i32"; WasmOpcode[WasmOpcode.F64_REINTERPRET_I64] = "f64.reinterpret/i64"; Object.freeze(WasmOpcode);
the_stack
module BABYLON { /** * A class storing a Matrix2D for 2D transformations * The stored matrix is a 3*3 Matrix2D * I [0,1] [mX, mY] R [ CosZ, SinZ] T [ 0, 0] S [Sx, 0] * D = [2,3] = [nX, nY] O = [-SinZ, CosZ] R = [ 0, 0] C = [ 0, Sy] * X [4,5] [tX, tY] T [ 0 , 0 ] N [Tx, Ty] L [ 0, 0] * * IDX = index, zero based. ROT = Z axis Rotation. TRN = Translation. SCL = Scale. */ export class Matrix2D { public static Zero(): Matrix2D { return new Matrix2D(); } public static FromValuesToRef(m0: number, m1: number, m2: number, m3: number, m4: number, m5: number, result: Matrix2D) { result.m[0] = m0; result.m[1] = m1; result.m[2] = m2; result.m[3] = m3; result.m[4] = m4; result.m[5] = m5; } public static FromMatrix(source: Matrix): Matrix2D { let result = new Matrix2D(); Matrix2D.FromMatrixToRef(source, result); return result; } public static FromMatrixToRef(source: Matrix, result: Matrix2D) { result.m[0] = source.m[0]; result.m[1] = source.m[1]; result.m[2] = source.m[4]; result.m[3] = source.m[5]; result.m[4] = source.m[8]; result.m[5] = source.m[9]; } public static Rotation(angle: number): Matrix2D { var result = new Matrix2D(); Matrix2D.RotationToRef(angle, result); return result; } public static RotationToRef(angle: number, result: Matrix2D): void { var s = Math.sin(angle); var c = Math.cos(angle); result.m[0] = c; result.m[1] = s; result.m[2] = -s; result.m[3] = c; result.m[4] = 0; result.m[5] = 0; } public static Translation(x: number, y: number): Matrix2D { var result = new Matrix2D(); Matrix2D.TranslationToRef(x, y, result); return result; } public static TranslationToRef(x: number, y: number, result: Matrix2D): void { result.m[0] = 1; result.m[1] = 0; result.m[2] = 0; result.m[3] = 1; result.m[4] = x; result.m[5] = y; } public static Scaling(x: number, y: number): Matrix2D { var result = new Matrix2D(); Matrix2D.ScalingToRef(x, y, result); return result; } public static ScalingToRef(x: number, y: number, result: Matrix2D): void { result.m[0] = x; result.m[1] = 0; result.m[2] = 0; result.m[3] = y; result.m[4] = 0; result.m[5] = 0; } public m = new Float32Array(6); public static Identity(): Matrix2D { let res = new Matrix2D(); Matrix2D.IdentityToRef(res); return res; } public static IdentityToRef(res: Matrix2D) { res.m[1] = res.m[2] = res.m[4] = res[5] = 0; res.m[0] = res.m[3] = 1; } public static FromQuaternion(quaternion: Quaternion): Matrix2D { let result = new Matrix2D(); Matrix2D.FromQuaternionToRef(quaternion, result); return result; } public static FromQuaternionToRef(quaternion: Quaternion, result: Matrix2D) { var xx = quaternion.x * quaternion.x; var yy = quaternion.y * quaternion.y; var zz = quaternion.z * quaternion.z; var xy = quaternion.x * quaternion.y; var zw = quaternion.z * quaternion.w; //var zx = quaternion.z * quaternion.x; //var yw = quaternion.y * quaternion.w; //var yz = quaternion.y * quaternion.z; //var xw = quaternion.x * quaternion.w; result.m[0] = 1.0 - (2.0 * (yy + zz)); result.m[1] = 2.0 * (xy + zw); //result.m[2] = 2.0 * (zx - yw); //result.m[3] = 0; result.m[2] = 2.0 * (xy - zw); result.m[3] = 1.0 - (2.0 * (zz + xx)); //result.m[6] = 2.0 * (yz + xw); //result.m[7] = 0; //result.m[8] = 2.0 * (zx + yw); //result.m[9] = 2.0 * (yz - xw); //result.m[10] = 1.0 - (2.0 * (yy + xx)); //result.m[11] = 0; //result.m[12] = 0; //result.m[13] = 0; //result.m[14] = 0; //result.m[15] = 1.0; } public static Compose(scale: Vector2, rotation: number, translation: Vector2): Matrix2D { var result = Matrix2D.Scaling(scale.x, scale.y); var rotationMatrix = Matrix2D.Rotation(rotation); result = result.multiply(rotationMatrix); result.setTranslation(translation); return result; } public static Invert(source: Matrix2D): Matrix2D { let result = new Matrix2D(); source.invertToRef(result); return result; } public clone(): Matrix2D { let result = new Matrix2D(); result.copyFrom(this); return result; } public copyFrom(other: Matrix2D) { for (let i = 0; i < 6; i++) { this.m[i] = other.m[i]; } } public getTranslation(): Vector2 { return new Vector2(this.m[4], this.m[5]); } public setTranslation(translation: Vector2) { this.m[4] = translation.x; this.m[5] = translation.y; } public determinant(): number { return this.m[0] * this.m[3] - this.m[1] * this.m[2]; } public invertToThis() { this.invertToRef(this); } public invert(): Matrix2D { let res = new Matrix2D(); this.invertToRef(res); return res; } // http://mathworld.wolfram.com/MatrixInverse.html public invertToRef(res: Matrix2D) { let l0 = this.m[0]; let l1 = this.m[1]; let l2 = this.m[2]; let l3 = this.m[3]; let l4 = this.m[4]; let l5 = this.m[5]; let det = this.determinant(); if (det < (Epsilon * Epsilon)) { throw new Error("Can't invert matrix, near null determinant"); } let detDiv = 1 / det; let det4 = l2 * l5 - l3 * l4; let det5 = l1 * l4 - l0 * l5; res.m[0] = l3 * detDiv; res.m[1] = -l1 * detDiv; res.m[2] = -l2 * detDiv; res.m[3] = l0 * detDiv; res.m[4] = det4 * detDiv; res.m[5] = det5 * detDiv; } public multiplyToThis(other: Matrix2D) { this.multiplyToRef(other, this); } public multiply(other: Matrix2D): Matrix2D { let res = new Matrix2D(); this.multiplyToRef(other, res); return res; } public multiplyToRef(other: Matrix2D, result: Matrix2D) { let l0 = this.m[0]; let l1 = this.m[1]; let l2 = this.m[2]; let l3 = this.m[3]; let l4 = this.m[4]; let l5 = this.m[5]; let r0 = other.m[0]; let r1 = other.m[1]; let r2 = other.m[2]; let r3 = other.m[3]; let r4 = other.m[4]; let r5 = other.m[5]; result.m[0] = l0 * r0 + l1 * r2; result.m[1] = l0 * r1 + l1 * r3; result.m[2] = l2 * r0 + l3 * r2; result.m[3] = l2 * r1 + l3 * r3; result.m[4] = l4 * r0 + l5 * r2 + r4; result.m[5] = l4 * r1 + l5 * r3 + r5; } public transformFloats(x: number, y: number): Vector2 { let res = Vector2.Zero(); this.transformFloatsToRef(x, y, res); return res; } public transformFloatsToRef(x: number, y: number, r: Vector2) { r.x = x * this.m[0] + y * this.m[2] + this.m[4]; r.y = x * this.m[1] + y * this.m[3] + this.m[5]; } public transformPoint(p: Vector2): Vector2 { let res = Vector2.Zero(); this.transformFloatsToRef(p.x, p.y, res); return res; } public transformPointToRef(p: Vector2, r: Vector2) { this.transformFloatsToRef(p.x, p.y, r); } private static _decomp: Matrix2D = new Matrix2D(); public decompose(scale: Vector2, translation: Vector2): number { translation.x = this.m[4]; translation.y = this.m[5]; scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1]); scale.y = Math.sqrt(this.m[2] * this.m[2] + this.m[3] * this.m[3]); if (scale.x === 0 || scale.y === 0) { return null; } return Math.atan2(-this.m[2] / scale.y, this.m[0] / scale.x); } } /** * Stores information about a 2D Triangle. * This class stores the 3 vertices but also the center and radius of the triangle */ export class Tri2DInfo { /** * Construct an instance of Tri2DInfo, you can either pass null to a, b and c and the instance will be allocated "clear", or give actual triangle info and the center/radius will be computed */ constructor(a: Vector2, b: Vector2, c: Vector2) { if (a === null && b === null && c === null) { this.a = Vector2.Zero(); this.b = Vector2.Zero(); this.c = Vector2.Zero(); this.center = Vector2.Zero(); this.radius = 0; return; } this.a = a.clone(); this.b = b.clone(); this.c = c.clone(); this._updateCenterRadius(); } a: Vector2; b: Vector2; c: Vector2; center: Vector2; radius: number; public static Zero() { return new Tri2DInfo(null, null, null); } public set(a: Vector2, b: Vector2, c: Vector2) { this.a.copyFrom(a); this.b.copyFrom(b); this.c.copyFrom(c); this._updateCenterRadius(); } public transformInPlace(transform: Matrix2D) { transform.transformPointToRef(this.a, this.a); transform.transformPointToRef(this.b, this.b); transform.transformPointToRef(this.c, this.c); //Vector2.TransformToRef(this.a, transform, this.a); //Vector2.TransformToRef(this.b, transform, this.b); //Vector2.TransformToRef(this.c, transform, this.c); this._updateCenterRadius(); } public doesContain(p: Vector2): boolean { return Vector2.PointInTriangle(p, this.a, this.b, this.c); } private _updateCenterRadius() { this.center.x = (this.a.x + this.b.x + this.c.x) / 3; this.center.y = (this.a.y + this.b.y + this.c.y) / 3; let la = Vector2.DistanceSquared(this.a, this.center); let lb = Vector2.DistanceSquared(this.b, this.center); let lc = Vector2.DistanceSquared(this.c, this.center); let rs = Math.max(Math.max(la, lb), lc); this.radius = Math.sqrt(rs); } } /** * Stores an array of 2D Triangles. * Internally the data is stored as a Float32Array to minimize the memory footprint. * This can use the Tri2DInfo class as proxy for storing/retrieving data. * The array can't grow, it's fixed size. */ export class Tri2DArray { constructor(count: number) { this._count = count; this._array = new Float32Array(9 * count); } /** * Clear the content and allocate a new array to store the given count of triangles * @param count The new count of triangles to store */ public clear(count: number) { if (this._count === count) { return; } this._count = count; this._array = new Float32Array(9 * count); } /** * Store a given triangle at the given index * @param index the 0 based index to store the triangle in the array * @param a the A vertex of the triangle * @param b the B vertex of the triangle * @param c the C vertex of the triangle */ public storeTriangle(index: number, a: Vector2, b: Vector2, c: Vector2) { let center = new Vector2((a.x + b.x + c.x) / 3, (a.y + b.y + c.y) / 3); let la = Vector2.DistanceSquared(a, center); let lb = Vector2.DistanceSquared(b, center); let lc = Vector2.DistanceSquared(c, center); let rs = Math.max(Math.max(la, lb), lc); let radius = Math.sqrt(rs); let offset = index * 9; this._array[offset + 0] = a.x; this._array[offset + 1] = a.y; this._array[offset + 2] = b.x; this._array[offset + 3] = b.y; this._array[offset + 4] = c.x; this._array[offset + 5] = c.y; this._array[offset + 6] = center.x; this._array[offset + 7] = center.y; this._array[offset + 8] = radius; } /** * Store a triangle in a Tri2DInfo object * @param index the index of the triangle to store * @param tri2dInfo the instance that will contain the data, it must be already allocated with its inner object also allocated */ public storeToTri2DInfo(index: number, tri2dInfo: Tri2DInfo) { if (index >= this._count) { throw new Error(`Can't fetch the triangle at index ${index}, max index is ${this._count - 1}`); } let offset = index * 9; tri2dInfo.a.x = this._array[offset + 0]; tri2dInfo.a.y = this._array[offset + 1]; tri2dInfo.b.x = this._array[offset + 2]; tri2dInfo.b.y = this._array[offset + 3]; tri2dInfo.c.x = this._array[offset + 4]; tri2dInfo.c.y = this._array[offset + 5]; tri2dInfo.center.x = this._array[offset + 6]; tri2dInfo.center.y = this._array[offset + 7]; tri2dInfo.radius = this._array[offset + 8]; } /** * Transform the given triangle and store its result in the array * @param index The index to store the result to * @param tri2dInfo The triangle to transform * @param transform The transformation matrix */ public transformAndStoreToTri2DInfo(index: number, tri2dInfo: Tri2DInfo, transform: Matrix2D) { if (index >= this._count) { throw new Error(`Can't fetch the triangle at index ${index}, max index is ${this._count - 1}`); } let offset = index * 9; tri2dInfo.a.x = this._array[offset + 0]; tri2dInfo.a.y = this._array[offset + 1]; tri2dInfo.b.x = this._array[offset + 2]; tri2dInfo.b.y = this._array[offset + 3]; tri2dInfo.c.x = this._array[offset + 4]; tri2dInfo.c.y = this._array[offset + 5]; tri2dInfo.transformInPlace(transform); } /** * Get the element count that can be stored in this array * @returns {} */ public get count(): number { return this._count; } /** * Check if a given point intersects with at least one of the triangles stored in the array. * If true is returned the point is intersecting with at least one triangle, false if it doesn't intersect with any of them * @param p The point to check */ public doesContain(p: Vector2): boolean { Tri2DArray._checkInitStatics(); let a = Tri2DArray.tempT[0]; for (let i = 0; i < this.count; i++) { this.storeToTri2DInfo(i, a); if (a.doesContain(p)) { return true; } } return false; } /** * Make a intersection test between two sets of triangles. The triangles of setB will be transformed to the frame of reference of the setA using the given bToATransform matrix. * If true is returned at least one triangle intersects with another of the other set, otherwise false is returned. * @param setA The first set of triangles * @param setB The second set of triangles * @param bToATransform The transformation matrix to transform the setB triangles into the frame of reference of the setA */ public static doesIntersect(setA: Tri2DArray, setB: Tri2DArray, bToATransform: Matrix2D): boolean { Tri2DArray._checkInitStatics(); let a = Tri2DArray.tempT[0]; let b = Tri2DArray.tempT[1]; let v0 = Tri2DArray.tempV[0]; for (let curB = 0; curB < setB.count; curB++) { setB.transformAndStoreToTri2DInfo(curB, b, bToATransform); for (let curA = 0; curA < setA.count; curA++) { setA.storeToTri2DInfo(curA, a); // Fast rejection first v0.x = a.center.x - b.center.x; v0.y = a.center.y - b.center.y; if (v0.lengthSquared() > ((a.radius * a.radius) + (b.radius * b.radius))) { continue; } // Actual intersection test if (Math2D.TriangleTriangleDosIntersect(a.a, a.b, a.c, b.a, b.b, b.c)) { return true; } } } return false; } private static _checkInitStatics() { if (Tri2DArray.tempT !== null) { return; } Tri2DArray.tempT = new Array<Tri2DInfo>(2); Tri2DArray.tempT[0] = new Tri2DInfo(null, null, null); Tri2DArray.tempT[1] = new Tri2DInfo(null, null, null); Tri2DArray.tempV = new Array<Vector2>(6); for (let i = 0; i < 6; i++) { Tri2DArray.tempV[i] = Vector2.Zero(); } } private _count: number; private _array: Float32Array; private static tempV: Vector2[] = null; private static tempT: Tri2DInfo[] = null; } /** * Some 2D Math helpers functions */ class Math2D { static Dot(a: Vector2, b: Vector2): number { return a.x * b.x + a.y * b.y; } // From http://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect // Note: this one might also be considered with the above one proves to not be good enough: http://jsfiddle.net/justin_c_rounds/Gd2S2/light/ static LineLineDoesIntersect(segA1: Vector2, segA2: Vector2, segB1: Vector2, segB2: Vector2): boolean { let s1_x = segA2.x - segA1.x; let s1_y = segA2.y - segA1.y; let s2_x = segB2.x - segB1.x; let s2_y = segB2.y - segB1.y; let s = (-s1_y * (segA1.x - segB1.x) + s1_x * (segA1.y - segB1.y)) / (-s2_x * s1_y + s1_x * s2_y); let t = ( s2_x * (segA1.y - segB1.y) - s2_y * (segA1.x - segB1.x)) / (-s2_x * s1_y + s1_x * s2_y); if (s >= 0 && s <= 1 && t >= 0 && t <= 1) { return true; } return false; } // From http://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect static LineLineIntersection(p0: Vector2, p1: Vector2, p2: Vector2, p3: Vector2): { res: boolean, xr: number, yr: number } { let s1_x = p1.x - p0.x; let s1_y = p1.y - p0.y; let s2_x = p3.x - p2.x; let s2_y = p3.y - p2.y; let s = (-s1_y * (p0.x - p2.x) + s1_x * (p0.y - p2.y)) / (-s2_x * s1_y + s1_x * s2_y); let t = (s2_x * (p0.y - p2.y) - s2_y * (p0.x - p2.x)) / (-s2_x * s1_y + s1_x * s2_y); if (s >= 0 && s <= 1 && t >= 0 && t <= 1) { return { res: true, xr: p0.x + (t * s1_x), yr: p0.y + (t * s1_y) }; } return { res: false, xr: 0, yr: 0 }; } private static v0 = Vector2.Zero(); private static v1 = Vector2.Zero(); private static v2 = Vector2.Zero(); // Tell me that it's slow and I'll answer: yes it is! // If you fancy to implement the SAT (Separating Axis Theorem) version: BE MY VERY WELCOMED GUEST! static TriangleTriangleDosIntersect(tri1A: Vector2, tri1B: Vector2, tri1C: Vector2, tri2A: Vector2, tri2B: Vector2, tri2C: Vector2): boolean { if (Math2D.LineLineDoesIntersect(tri1A, tri1B, tri2A, tri2B)) return true; if (Math2D.LineLineDoesIntersect(tri1A, tri1B, tri2A, tri2C)) return true; if (Math2D.LineLineDoesIntersect(tri1A, tri1B, tri2B, tri2C)) return true; if (Math2D.LineLineDoesIntersect(tri1A, tri1C, tri2A, tri2B)) return true; if (Math2D.LineLineDoesIntersect(tri1A, tri1C, tri2A, tri2C)) return true; if (Math2D.LineLineDoesIntersect(tri1A, tri1C, tri2B, tri2C)) return true; if (Math2D.LineLineDoesIntersect(tri1B, tri1C, tri2A, tri2B)) return true; if (Math2D.LineLineDoesIntersect(tri1B, tri1C, tri2A, tri2C)) return true; if (Math2D.LineLineDoesIntersect(tri1B, tri1C, tri2B, tri2C)) return true; if (Vector2.PointInTriangle(tri2A, tri1A, tri1B, tri1C) && Vector2.PointInTriangle(tri2B, tri1A, tri1B, tri1C) && Vector2.PointInTriangle(tri2C, tri1A, tri1B, tri1C)) return true; if (Vector2.PointInTriangle(tri1A, tri2A, tri2B, tri2C) && Vector2.PointInTriangle(tri1B, tri2A, tri2B, tri2C) && Vector2.PointInTriangle(tri1C, tri2A, tri2B, tri2C)) return true; return false; } } }
the_stack
import infoIcon from '@iconify/icons-mdi/information-circle-outline'; import searchIcon from '@iconify/icons-mdi/search'; import Icon from '@iconify/react'; import { makeStyles, Theme } from '@material-ui/core'; import Box from '@material-ui/core/Box'; import Button from '@material-ui/core/Button'; import FormControl from '@material-ui/core/FormControl'; import Grid from '@material-ui/core/Grid'; import IconButton from '@material-ui/core/IconButton'; import Input from '@material-ui/core/Input'; import InputAdornment from '@material-ui/core/InputAdornment'; import InputLabel from '@material-ui/core/InputLabel'; import MenuItem from '@material-ui/core/MenuItem'; import Paper from '@material-ui/core/Paper'; import Select from '@material-ui/core/Select'; import TablePagination from '@material-ui/core/TablePagination'; import { useTheme } from '@material-ui/styles'; import PropTypes from 'prop-types'; import React, { ChangeEvent } from 'react'; import { useTranslation } from 'react-i18next'; import { useHistory, useLocation } from 'react-router-dom'; import _ from 'underscore'; import API from '../../api/API'; import { Application, Group, Instance, Instances } from '../../api/apiDataTypes'; import { getInstanceStatus, getKeyByValue, InstanceSortFilters, SearchFilterClassifiers, useGroupVersionBreakdown, } from '../../utils/helpers'; import Empty from '../Common/EmptyContent'; import LightTooltip from '../Common/LightTooltip'; import ListHeader from '../Common/ListHeader'; import SearchInput from '../Common/ListSearch'; import Loader from '../Common/Loader'; import TimeIntervalLinks from '../Common/TimeIntervalLinks'; import { InstanceCountLabel } from './Common'; import makeStatusDefs from './StatusDefs'; import Table from './Table'; // The indexes for the sorting names match the backend index for that criteria as well. const SORT_ORDERS = ['asc', 'desc']; const useStyles = makeStyles(theme => ({ root: { backgroundColor: theme.palette.lightSilverShade, }, })); interface InstanceFilterProps { versions: any[]; onFiltersChanged: (newFilters: any) => void; filter: { [key: string]: any; }; disabled?: boolean; } function InstanceFilter(props: InstanceFilterProps) { const statusDefs = makeStatusDefs(useTheme()); const { t } = useTranslation(); const { onFiltersChanged, versions } = props; function changeFilter(filterName: string, filterValue: string) { if (filterValue === props.filter[filterName]) { return; } const filter = { ...props.filter }; filter[filterName] = filterValue; onFiltersChanged(filter); } return ( <Box pr={2}> <Grid container spacing={2} justify="flex-end"> <Grid item xs={5}> <FormControl fullWidth disabled={props.disabled}> <InputLabel htmlFor="select-status" shrink> {t('instances|Filter Status')} </InputLabel> <Select onChange={(event: any) => changeFilter('status', event.target.value)} input={<Input id="select-status" />} renderValue={(selected: any) => selected ? statusDefs[selected].label : t('instances|Show All') } value={props.filter.status} displayEmpty > <MenuItem key="" value=""> {t('instances|Show All')} </MenuItem> {Object.keys(statusDefs).map(statusType => { const label = statusDefs[statusType].label; return ( <MenuItem key={statusType} value={statusType}> {label} </MenuItem> ); })} </Select> </FormControl> </Grid> <Grid item xs={5}> <FormControl fullWidth disabled={props.disabled}> <InputLabel htmlFor="select-versions" shrink> {t('instances|Filter Version')} </InputLabel> <Select onChange={(event: ChangeEvent<{ name?: string | undefined; value: any }>) => changeFilter('version', event.target.value) } input={<Input id="select-versions" />} renderValue={(selected: any) => (selected ? selected : t('instances|Show All'))} value={props.filter.version} displayEmpty > <MenuItem key="" value=""> {t('instances|Show All')} </MenuItem> {(versions || []).map(({ version }) => { return ( <MenuItem key={version} value={version}> {version} </MenuItem> ); })} </Select> </FormControl> </Grid> </Grid> </Box> ); } function ListView(props: { application: Application; group: Group }) { const classes = useStyles(); const theme = useTheme(); const { t } = useTranslation(); const statusDefs = makeStatusDefs(useTheme()); const { application, group } = props; const versionBreakdown = useGroupVersionBreakdown(group); /*TODO: use the URL as the single source of truth and remove states */ const [page, setPage] = React.useState(0); const [rowsPerPage, setRowsPerPage] = React.useState(10); const [isDescSortOrder, setIsDescSortOrder] = React.useState(false); const [sortQuery, setSortQuery] = React.useState(InstanceSortFilters['last-check']); const [filters, setFilters] = React.useState<{ [key: string]: any }>({ status: '', version: '', sortOrder: SORT_ORDERS[1], }); const [instancesObj, setInstancesObj] = React.useState<Instances>({ instances: [], total: -1, }); const [instanceFetchLoading, setInstanceFetchLoading] = React.useState(false); const [totalInstances, setTotalInstances] = React.useState(-1); const [searchObject, setSearchObject] = React.useState<{ searchFilter?: string; searchValue?: string; }>({}); const location = useLocation(); const history = useHistory(); function getDuration() { return new URLSearchParams(location.search).get('period') || '1d'; } function fetchFiltersFromURL(callback: (...args: any) => void) { let status = ''; const queryParams = new URLSearchParams(location.search); if (queryParams.has('status')) { const statusValue = queryParams.get('status'); if (statusValue !== 'ShowAll') { for (const key in statusDefs) { if (statusDefs[key].label === statusValue) { status = key; break; } } } } const version = queryParams.get('version') || ''; const sort = InstanceSortFilters[queryParams.get('sort') || 'last-check']; const pageFromURL = queryParams.get('page'); const pageQueryParam = ((pageFromURL && parseInt(pageFromURL)) || 1) - 1; const perPage = parseInt(queryParams.get('perPage') as string) || 10; const sortOrder = SORT_ORDERS[1] === (queryParams.get('sortOrder') as string) ? 1 : 0; const duration = getDuration(); callback(status, version, sort, sortOrder, pageQueryParam, perPage, duration); } function addQuery(queryObj: { [key: string]: any }) { const pathname = location.pathname; const searchParams = new URLSearchParams(location.search); for (const key in queryObj) { const value = queryObj[key]; if (value) { searchParams.set(key, value); } else { searchParams.delete(key); } } history.push({ pathname: pathname, search: searchParams.toString(), }); } function fetchInstances( filters: { [key: string]: any }, page: number, perPage: number, duration: string, searchObject: { searchFilter?: string; searchValue?: string } ) { setInstanceFetchLoading(true); const fetchFilters = { ...filters }; if (filters.status === '') { fetchFilters.status = '0'; } else { const statusDefinition = statusDefs[fetchFilters.status]; fetchFilters.status = statusDefinition.queryValue; } API.getInstances(application.id, group.id, { ...fetchFilters, sortOrder: Number(isDescSortOrder), page: page + 1, perpage: perPage, duration, ...searchObject, }) .then(result => { setInstanceFetchLoading(false); // Since we have retrieved the instances without a filter (i.e. all instances) // we update the total. if (!fetchFilters.status && !fetchFilters.version) { setTotalInstances(result.total); } if (result.instances) { const massagedInstances = result.instances.map((instance: Instance) => { instance.statusInfo = getInstanceStatus(instance.application.status); return instance; }); setInstancesObj({ instances: massagedInstances, total: result.total }); } else { setInstancesObj({ instances: [], total: result.total }); } }) .catch(() => { setInstanceFetchLoading(false); }); } function handleChangePage( event: React.MouseEvent<HTMLButtonElement, MouseEvent> | null, newPage: number ) { addQuery({ page: newPage + 1 }); } function handleChangeRowsPerPage(event: React.ChangeEvent<{ value: string }>) { addQuery({ page: 1, perPage: +event.target.value }); } function onFiltersChanged(newFilters: { [key: string]: any }) { applyFilters(newFilters); } function applyFilters(_filters = {}) { const newFilters: { [key: string]: any } = Object.keys(_filters).length !== 0 ? _filters : { status: '', version: '' }; const statusQueryParam = newFilters.status ? statusDefs[newFilters.status].label : ''; addQuery({ status: statusQueryParam, version: newFilters.version }); setFilters(newFilters); } function resetFilters() { applyFilters(); } function handleInstanceFetch(searchObject: { searchFilter?: string | undefined; searchValue?: string | undefined; }) { fetchFiltersFromURL( ( status: string, version: string, sort: string, isDescSortOrder: boolean, pageParam: number, perPageParam: number, duration: string ) => { setFilters({ status, version, sort }); setPage(pageParam); setIsDescSortOrder(isDescSortOrder); setSortQuery(sort); setRowsPerPage(perPageParam); fetchInstances({ status, version, sort }, pageParam, perPageParam, duration, searchObject); } ); } React.useEffect(() => { handleInstanceFetch(searchObject); }, [location]); React.useEffect(() => { // We want to run it only if the searchValue is empty and once for change in totalInstances. if (totalInstances > 0 && searchObject.searchValue) { return; } // We use this function without any filter to get the total number of instances // in the group. const queryParams = new URLSearchParams(window.location.search); const duration = queryParams.get('period'); API.getInstancesCount(application.id, group.id, duration as string) .then(result => { setTotalInstances(result); }) .catch(err => console.error('Error loading total instances in Instances/List', err)); }, [totalInstances, searchObject]); function getInstanceCount() { const total = totalInstances > -1 ? totalInstances : '…'; const instancesTotal = instancesObj.total > -1 ? instancesObj.total : '...'; if ( (!searchObject.searchValue && !filters.status && !filters.version) || instancesTotal === total ) { return total; } return `${instancesTotal}/${total}`; } function isFiltered() { return filters.status || filters.version; } function sortHandler(isDescSortOrder: boolean, sortQuery: string) { setIsDescSortOrder(isDescSortOrder); setSortQuery(sortQuery); const sortAliasKey = getKeyByValue(InstanceSortFilters, sortQuery); addQuery({ sort: sortAliasKey, sortOrder: SORT_ORDERS[Number(isDescSortOrder)] }); } function searchHandler(e: React.ChangeEvent<{ value: string }>) { const value = e.target.value; // This means user has reseted the input field, and now we need to fetch all the instances if (value === '') { handleInstanceFetch({}); } // handle if a classifier is present const [classifierName] = value.split(':'); const classifierVal = value.substring(value.indexOf(':') + 1); const classifiedFilter = SearchFilterClassifiers.find( classifier => classifier.name === classifierName ); if (classifierVal !== undefined && classifiedFilter) { setSearchObject({ searchValue: classifierVal, searchFilter: classifiedFilter.queryValue, }); return; } if (!classifiedFilter) { // this means user is trying to search without any classifier setSearchObject({ searchFilter: 'All', searchValue: value, }); } } function handleSearchSubmit(e: any) { if (e.key === 'Enter' && Object.keys(searchObject).length !== 0) { const debouncedFetch = _.debounce(handleInstanceFetch, 100); debouncedFetch(searchObject); } } function getSearchTooltipText() { return t(`instances|You can search by typing and pressing enter. The search will show matches for the instances id, alias, and ip fields, in this order. It is also possible to match only one field by using its classifier, for example: id:0001 alias:"My instance" ip:256.0.0.1`); } const searchInputRef = React.createRef<HTMLInputElement>(); return ( <> <ListHeader title={t('instances|Instance List')} /> <Paper> <Box padding="1em"> <Grid container spacing={1}> <Grid item container justify="space-between" alignItems="stretch"> <Grid item> <Box mb={2} color={(theme as Theme).palette.greyShadeColor} fontSize={30} fontWeight={700} > {group.name} </Box> </Grid> <Grid item> <InputLabel htmlFor="instance-search-filter" shrink> {t('frequent|Search')} </InputLabel> <SearchInput id="instance-search-filter" startAdornment={ <InputAdornment position="start"> <IconButton onClick={() => searchInputRef.current?.focus()} title="Search Icon" > <Icon icon={searchIcon} width="15" height="15" /> </IconButton> </InputAdornment> } endAdornment={ <InputAdornment position="end"> <LightTooltip title={getSearchTooltipText()}> <IconButton> <Icon icon={infoIcon} width="20" height="20" /> </IconButton> </LightTooltip> </InputAdornment> } onChange={searchHandler} onKeyPress={handleSearchSubmit} inputRef={searchInputRef} ariaLabel="Search" /> </Grid> <Grid item> <TimeIntervalLinks intervalChangeHandler={duration => addQuery({ period: duration.queryValue })} selectedInterval={getDuration()} appID={application.id} groupID={group.id} /> </Grid> </Grid> <Box width="100%" borderTop={1} borderColor={'#E0E0E0'} className={classes.root}> <Grid item container md={12} alignItems="stretch" justify="space-between"> <Grid item md> <Box display="flex" alignItems="center"> <Box ml={2}> <InstanceCountLabel countText={getInstanceCount()} instanceListView /> </Box> </Box> </Grid> <Grid item md> <Box mt={2}> <InstanceFilter versions={versionBreakdown} onFiltersChanged={onFiltersChanged} filter={filters} /> </Box> </Grid> </Grid> </Box> {isFiltered() && ( <Grid item md={12} container justify="center"> <Grid item> <Button variant="outlined" color="secondary" onClick={resetFilters}> {t('instances|Reset filters')} </Button> </Grid> </Grid> )} <Grid item md={12}> {!instanceFetchLoading ? ( instancesObj.instances.length > 0 ? ( <React.Fragment> <Table channel={group.channel} instances={instancesObj.instances} isDescSortOrder={isDescSortOrder} sortQuery={sortQuery} sortHandler={sortHandler} /> <TablePagination rowsPerPageOptions={[10, 25, 50, 100]} component="div" count={instancesObj.total} rowsPerPage={rowsPerPage} page={page} backIconButtonProps={{ 'aria-label': t('frequent|previous page'), }} nextIconButtonProps={{ 'aria-label': t('frequent|next page'), }} onChangePage={handleChangePage} onChangeRowsPerPage={handleChangeRowsPerPage} /> </React.Fragment> ) : ( <Empty>{t('frequent|No instances.')}</Empty> ) ) : ( <Loader /> )} </Grid> </Grid> </Box> </Paper> </> ); } ListView.propTypes = { application: PropTypes.object.isRequired, group: PropTypes.object.isRequired, }; export default ListView;
the_stack
import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; import {SinonStub} from 'sinon'; import {describe, it, beforeEach, afterEach} from 'mocha'; import * as projectsModule from '../src'; import {PassThrough} from 'stream'; import {GoogleAuth, protobuf} from 'google-gax'; function generateSampleMessage<T extends object>(instance: T) { const filledObject = ( instance.constructor as typeof protobuf.Message ).toObject(instance as protobuf.Message<T>, {defaults: true}); return (instance.constructor as typeof protobuf.Message).fromObject( filledObject ) as T; } function stubSimpleCall<ResponseType>(response?: ResponseType, error?: Error) { return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); } function stubSimpleCallWithCallback<ResponseType>( response?: ResponseType, error?: Error ) { return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); } function stubPageStreamingCall<ResponseType>( responses?: ResponseType[], error?: Error ) { const pagingStub = sinon.stub(); if (responses) { for (let i = 0; i < responses.length; ++i) { pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } } const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; const mockStream = new PassThrough({ objectMode: true, transform: transformStub, }); // trigger as many responses as needed if (responses) { for (let i = 0; i < responses.length; ++i) { setImmediate(() => { mockStream.write({}); }); } setImmediate(() => { mockStream.end(); }); } else { setImmediate(() => { mockStream.write({}); }); setImmediate(() => { mockStream.end(); }); } return sinon.stub().returns(mockStream); } function stubAsyncIterationCall<ResponseType>( responses?: ResponseType[], error?: Error ) { let counter = 0; const asyncIterable = { [Symbol.asyncIterator]() { return { async next() { if (error) { return Promise.reject(error); } if (counter >= responses!.length) { return Promise.resolve({done: true, value: undefined}); } return Promise.resolve({done: false, value: responses![counter++]}); }, }; }, }; return sinon.stub().returns(asyncIterable); } describe('v1.ProjectsClient', () => { let googleAuth: GoogleAuth; beforeEach(() => { googleAuth = { getClient: sinon.stub().resolves({ getRequestHeaders: sinon .stub() .resolves({Authorization: 'Bearer SOME_TOKEN'}), }), } as unknown as GoogleAuth; }); afterEach(() => { sinon.restore(); }); it('has servicePath', () => { const servicePath = projectsModule.v1.ProjectsClient.servicePath; assert(servicePath); }); it('has apiEndpoint', () => { const apiEndpoint = projectsModule.v1.ProjectsClient.apiEndpoint; assert(apiEndpoint); }); it('has port', () => { const port = projectsModule.v1.ProjectsClient.port; assert(port); assert(typeof port === 'number'); }); it('should create a client with no option', () => { const client = new projectsModule.v1.ProjectsClient(); assert(client); }); it('should create a client with gRPC fallback', () => { const client = new projectsModule.v1.ProjectsClient({ fallback: true, }); assert(client); }); it('has initialize method and supports deferred initialization', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); assert.strictEqual(client.projectsStub, undefined); await client.initialize(); assert(client.projectsStub); }); it('has close method', () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.close(); }); it('has getProjectId method', async () => { const fakeProjectId = 'fake-project-id'; const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); const result = await client.getProjectId(); assert.strictEqual(result, fakeProjectId); assert((client.auth.getProjectId as SinonStub).calledWithExactly()); }); it('has getProjectId method with callback', async () => { const fakeProjectId = 'fake-project-id'; const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.auth.getProjectId = sinon .stub() .callsArgWith(0, null, fakeProjectId); const promise = new Promise((resolve, reject) => { client.getProjectId((err?: Error | null, projectId?: string | null) => { if (err) { reject(err); } else { resolve(projectId); } }); }); const result = await promise; assert.strictEqual(result, fakeProjectId); }); describe('disableXpnHost', () => { it('invokes disableXpnHost without error', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.DisableXpnHostProjectRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.disableXpnHost = stubSimpleCall(expectedResponse); const [response] = await client.disableXpnHost(request); assert.deepStrictEqual(response.latestResponse, expectedResponse); assert( (client.innerApiCalls.disableXpnHost as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes disableXpnHost without error using callback', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.DisableXpnHostProjectRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.disableXpnHost = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.disableXpnHost( request, ( err?: Error | null, result?: protos.google.cloud.compute.v1.IOperation | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.disableXpnHost as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes disableXpnHost with error', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.DisableXpnHostProjectRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedError = new Error('expected'); client.innerApiCalls.disableXpnHost = stubSimpleCall( undefined, expectedError ); await assert.rejects(client.disableXpnHost(request), expectedError); assert( (client.innerApiCalls.disableXpnHost as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); }); describe('disableXpnResource', () => { it('invokes disableXpnResource without error', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.DisableXpnResourceProjectRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.disableXpnResource = stubSimpleCall(expectedResponse); const [response] = await client.disableXpnResource(request); assert.deepStrictEqual(response.latestResponse, expectedResponse); assert( (client.innerApiCalls.disableXpnResource as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes disableXpnResource without error using callback', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.DisableXpnResourceProjectRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.disableXpnResource = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.disableXpnResource( request, ( err?: Error | null, result?: protos.google.cloud.compute.v1.IOperation | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.disableXpnResource as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes disableXpnResource with error', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.DisableXpnResourceProjectRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedError = new Error('expected'); client.innerApiCalls.disableXpnResource = stubSimpleCall( undefined, expectedError ); await assert.rejects(client.disableXpnResource(request), expectedError); assert( (client.innerApiCalls.disableXpnResource as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); }); describe('enableXpnHost', () => { it('invokes enableXpnHost without error', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.EnableXpnHostProjectRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.enableXpnHost = stubSimpleCall(expectedResponse); const [response] = await client.enableXpnHost(request); assert.deepStrictEqual(response.latestResponse, expectedResponse); assert( (client.innerApiCalls.enableXpnHost as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes enableXpnHost without error using callback', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.EnableXpnHostProjectRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.enableXpnHost = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.enableXpnHost( request, ( err?: Error | null, result?: protos.google.cloud.compute.v1.IOperation | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.enableXpnHost as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes enableXpnHost with error', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.EnableXpnHostProjectRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedError = new Error('expected'); client.innerApiCalls.enableXpnHost = stubSimpleCall( undefined, expectedError ); await assert.rejects(client.enableXpnHost(request), expectedError); assert( (client.innerApiCalls.enableXpnHost as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); }); describe('enableXpnResource', () => { it('invokes enableXpnResource without error', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.EnableXpnResourceProjectRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.enableXpnResource = stubSimpleCall(expectedResponse); const [response] = await client.enableXpnResource(request); assert.deepStrictEqual(response.latestResponse, expectedResponse); assert( (client.innerApiCalls.enableXpnResource as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes enableXpnResource without error using callback', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.EnableXpnResourceProjectRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.enableXpnResource = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.enableXpnResource( request, ( err?: Error | null, result?: protos.google.cloud.compute.v1.IOperation | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.enableXpnResource as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes enableXpnResource with error', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.EnableXpnResourceProjectRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedError = new Error('expected'); client.innerApiCalls.enableXpnResource = stubSimpleCall( undefined, expectedError ); await assert.rejects(client.enableXpnResource(request), expectedError); assert( (client.innerApiCalls.enableXpnResource as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); }); describe('get', () => { it('invokes get without error', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.GetProjectRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Project() ); client.innerApiCalls.get = stubSimpleCall(expectedResponse); const [response] = await client.get(request); assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.get as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes get without error using callback', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.GetProjectRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Project() ); client.innerApiCalls.get = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.get( request, ( err?: Error | null, result?: protos.google.cloud.compute.v1.IProject | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.get as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes get with error', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.GetProjectRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedError = new Error('expected'); client.innerApiCalls.get = stubSimpleCall(undefined, expectedError); await assert.rejects(client.get(request), expectedError); assert( (client.innerApiCalls.get as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); }); describe('getXpnHost', () => { it('invokes getXpnHost without error', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.GetXpnHostProjectRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Project() ); client.innerApiCalls.getXpnHost = stubSimpleCall(expectedResponse); const [response] = await client.getXpnHost(request); assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.getXpnHost as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes getXpnHost without error using callback', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.GetXpnHostProjectRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Project() ); client.innerApiCalls.getXpnHost = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.getXpnHost( request, ( err?: Error | null, result?: protos.google.cloud.compute.v1.IProject | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.getXpnHost as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes getXpnHost with error', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.GetXpnHostProjectRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedError = new Error('expected'); client.innerApiCalls.getXpnHost = stubSimpleCall( undefined, expectedError ); await assert.rejects(client.getXpnHost(request), expectedError); assert( (client.innerApiCalls.getXpnHost as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); }); describe('moveDisk', () => { it('invokes moveDisk without error', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.MoveDiskProjectRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.moveDisk = stubSimpleCall(expectedResponse); const [response] = await client.moveDisk(request); assert.deepStrictEqual(response.latestResponse, expectedResponse); assert( (client.innerApiCalls.moveDisk as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes moveDisk without error using callback', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.MoveDiskProjectRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.moveDisk = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.moveDisk( request, ( err?: Error | null, result?: protos.google.cloud.compute.v1.IOperation | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.moveDisk as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes moveDisk with error', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.MoveDiskProjectRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedError = new Error('expected'); client.innerApiCalls.moveDisk = stubSimpleCall(undefined, expectedError); await assert.rejects(client.moveDisk(request), expectedError); assert( (client.innerApiCalls.moveDisk as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); }); describe('moveInstance', () => { it('invokes moveInstance without error', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.MoveInstanceProjectRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.moveInstance = stubSimpleCall(expectedResponse); const [response] = await client.moveInstance(request); assert.deepStrictEqual(response.latestResponse, expectedResponse); assert( (client.innerApiCalls.moveInstance as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes moveInstance without error using callback', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.MoveInstanceProjectRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.moveInstance = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.moveInstance( request, ( err?: Error | null, result?: protos.google.cloud.compute.v1.IOperation | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.moveInstance as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes moveInstance with error', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.MoveInstanceProjectRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedError = new Error('expected'); client.innerApiCalls.moveInstance = stubSimpleCall( undefined, expectedError ); await assert.rejects(client.moveInstance(request), expectedError); assert( (client.innerApiCalls.moveInstance as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); }); describe('setCommonInstanceMetadata', () => { it('invokes setCommonInstanceMetadata without error', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.SetCommonInstanceMetadataProjectRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.setCommonInstanceMetadata = stubSimpleCall(expectedResponse); const [response] = await client.setCommonInstanceMetadata(request); assert.deepStrictEqual(response.latestResponse, expectedResponse); assert( (client.innerApiCalls.setCommonInstanceMetadata as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes setCommonInstanceMetadata without error using callback', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.SetCommonInstanceMetadataProjectRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.setCommonInstanceMetadata = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.setCommonInstanceMetadata( request, ( err?: Error | null, result?: protos.google.cloud.compute.v1.IOperation | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.setCommonInstanceMetadata as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes setCommonInstanceMetadata with error', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.SetCommonInstanceMetadataProjectRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedError = new Error('expected'); client.innerApiCalls.setCommonInstanceMetadata = stubSimpleCall( undefined, expectedError ); await assert.rejects( client.setCommonInstanceMetadata(request), expectedError ); assert( (client.innerApiCalls.setCommonInstanceMetadata as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); }); describe('setDefaultNetworkTier', () => { it('invokes setDefaultNetworkTier without error', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.SetDefaultNetworkTierProjectRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.setDefaultNetworkTier = stubSimpleCall(expectedResponse); const [response] = await client.setDefaultNetworkTier(request); assert.deepStrictEqual(response.latestResponse, expectedResponse); assert( (client.innerApiCalls.setDefaultNetworkTier as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes setDefaultNetworkTier without error using callback', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.SetDefaultNetworkTierProjectRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.setDefaultNetworkTier = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.setDefaultNetworkTier( request, ( err?: Error | null, result?: protos.google.cloud.compute.v1.IOperation | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.setDefaultNetworkTier as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes setDefaultNetworkTier with error', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.SetDefaultNetworkTierProjectRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedError = new Error('expected'); client.innerApiCalls.setDefaultNetworkTier = stubSimpleCall( undefined, expectedError ); await assert.rejects( client.setDefaultNetworkTier(request), expectedError ); assert( (client.innerApiCalls.setDefaultNetworkTier as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); }); describe('setUsageExportBucket', () => { it('invokes setUsageExportBucket without error', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.SetUsageExportBucketProjectRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.setUsageExportBucket = stubSimpleCall(expectedResponse); const [response] = await client.setUsageExportBucket(request); assert.deepStrictEqual(response.latestResponse, expectedResponse); assert( (client.innerApiCalls.setUsageExportBucket as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes setUsageExportBucket without error using callback', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.SetUsageExportBucketProjectRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1.Operation() ); client.innerApiCalls.setUsageExportBucket = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.setUsageExportBucket( request, ( err?: Error | null, result?: protos.google.cloud.compute.v1.IOperation | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.setUsageExportBucket as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes setUsageExportBucket with error', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.SetUsageExportBucketProjectRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedError = new Error('expected'); client.innerApiCalls.setUsageExportBucket = stubSimpleCall( undefined, expectedError ); await assert.rejects(client.setUsageExportBucket(request), expectedError); assert( (client.innerApiCalls.setUsageExportBucket as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); }); describe('getXpnResources', () => { it('invokes getXpnResources without error', async () => { const client = new projectsModule.v1.ProjectsClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.GetXpnResourcesProjectsRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = [ generateSampleMessage( new protos.google.cloud.compute.v1.XpnResourceId() ), generateSampleMessage( new protos.google.cloud.compute.v1.XpnResourceId() ), generateSampleMessage( new protos.google.cloud.compute.v1.XpnResourceId() ), ]; client.innerApiCalls.getXpnResources = stubSimpleCall(expectedResponse); const [response] = await client.getXpnResources(request); assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.getXpnResources as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes getXpnResources without error using callback', async () => { const client = new projectsModule.v1.ProjectsClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.GetXpnResourcesProjectsRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = [ generateSampleMessage( new protos.google.cloud.compute.v1.XpnResourceId() ), generateSampleMessage( new protos.google.cloud.compute.v1.XpnResourceId() ), generateSampleMessage( new protos.google.cloud.compute.v1.XpnResourceId() ), ]; client.innerApiCalls.getXpnResources = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.getXpnResources( request, ( err?: Error | null, result?: protos.google.cloud.compute.v1.IXpnResourceId[] | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.getXpnResources as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes getXpnResources with error', async () => { const client = new projectsModule.v1.ProjectsClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.GetXpnResourcesProjectsRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedError = new Error('expected'); client.innerApiCalls.getXpnResources = stubSimpleCall( undefined, expectedError ); await assert.rejects(client.getXpnResources(request), expectedError); assert( (client.innerApiCalls.getXpnResources as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes getXpnResourcesStream without error', async () => { const client = new projectsModule.v1.ProjectsClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.GetXpnResourcesProjectsRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedResponse = [ generateSampleMessage( new protos.google.cloud.compute.v1.XpnResourceId() ), generateSampleMessage( new protos.google.cloud.compute.v1.XpnResourceId() ), generateSampleMessage( new protos.google.cloud.compute.v1.XpnResourceId() ), ]; client.descriptors.page.getXpnResources.createStream = stubPageStreamingCall(expectedResponse); const stream = client.getXpnResourcesStream(request); const promise = new Promise((resolve, reject) => { const responses: protos.google.cloud.compute.v1.XpnResourceId[] = []; stream.on( 'data', (response: protos.google.cloud.compute.v1.XpnResourceId) => { responses.push(response); } ); stream.on('end', () => { resolve(responses); }); stream.on('error', (err: Error) => { reject(err); }); }); const responses = await promise; assert.deepStrictEqual(responses, expectedResponse); assert( (client.descriptors.page.getXpnResources.createStream as SinonStub) .getCall(0) .calledWith(client.innerApiCalls.getXpnResources, request) ); assert.strictEqual( ( client.descriptors.page.getXpnResources.createStream as SinonStub ).getCall(0).args[2].otherArgs.headers['x-goog-request-params'], expectedHeaderRequestParams ); }); it('invokes getXpnResourcesStream with error', async () => { const client = new projectsModule.v1.ProjectsClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.GetXpnResourcesProjectsRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedError = new Error('expected'); client.descriptors.page.getXpnResources.createStream = stubPageStreamingCall(undefined, expectedError); const stream = client.getXpnResourcesStream(request); const promise = new Promise((resolve, reject) => { const responses: protos.google.cloud.compute.v1.XpnResourceId[] = []; stream.on( 'data', (response: protos.google.cloud.compute.v1.XpnResourceId) => { responses.push(response); } ); stream.on('end', () => { resolve(responses); }); stream.on('error', (err: Error) => { reject(err); }); }); await assert.rejects(promise, expectedError); assert( (client.descriptors.page.getXpnResources.createStream as SinonStub) .getCall(0) .calledWith(client.innerApiCalls.getXpnResources, request) ); assert.strictEqual( ( client.descriptors.page.getXpnResources.createStream as SinonStub ).getCall(0).args[2].otherArgs.headers['x-goog-request-params'], expectedHeaderRequestParams ); }); it('uses async iteration with getXpnResources without error', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.GetXpnResourcesProjectsRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedResponse = [ generateSampleMessage( new protos.google.cloud.compute.v1.XpnResourceId() ), generateSampleMessage( new protos.google.cloud.compute.v1.XpnResourceId() ), generateSampleMessage( new protos.google.cloud.compute.v1.XpnResourceId() ), ]; client.descriptors.page.getXpnResources.asyncIterate = stubAsyncIterationCall(expectedResponse); const responses: protos.google.cloud.compute.v1.IXpnResourceId[] = []; const iterable = client.getXpnResourcesAsync(request); for await (const resource of iterable) { responses.push(resource!); } assert.deepStrictEqual(responses, expectedResponse); assert.deepStrictEqual( ( client.descriptors.page.getXpnResources.asyncIterate as SinonStub ).getCall(0).args[1], request ); assert.strictEqual( ( client.descriptors.page.getXpnResources.asyncIterate as SinonStub ).getCall(0).args[2].otherArgs.headers['x-goog-request-params'], expectedHeaderRequestParams ); }); it('uses async iteration with getXpnResources with error', async () => { const client = new projectsModule.v1.ProjectsClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.GetXpnResourcesProjectsRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedError = new Error('expected'); client.descriptors.page.getXpnResources.asyncIterate = stubAsyncIterationCall(undefined, expectedError); const iterable = client.getXpnResourcesAsync(request); await assert.rejects(async () => { const responses: protos.google.cloud.compute.v1.IXpnResourceId[] = []; for await (const resource of iterable) { responses.push(resource!); } }); assert.deepStrictEqual( ( client.descriptors.page.getXpnResources.asyncIterate as SinonStub ).getCall(0).args[1], request ); assert.strictEqual( ( client.descriptors.page.getXpnResources.asyncIterate as SinonStub ).getCall(0).args[2].otherArgs.headers['x-goog-request-params'], expectedHeaderRequestParams ); }); }); describe('listXpnHosts', () => { it('invokes listXpnHosts without error', async () => { const client = new projectsModule.v1.ProjectsClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListXpnHostsProjectsRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = [ generateSampleMessage(new protos.google.cloud.compute.v1.Project()), generateSampleMessage(new protos.google.cloud.compute.v1.Project()), generateSampleMessage(new protos.google.cloud.compute.v1.Project()), ]; client.innerApiCalls.listXpnHosts = stubSimpleCall(expectedResponse); const [response] = await client.listXpnHosts(request); assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.listXpnHosts as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes listXpnHosts without error using callback', async () => { const client = new projectsModule.v1.ProjectsClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListXpnHostsProjectsRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedResponse = [ generateSampleMessage(new protos.google.cloud.compute.v1.Project()), generateSampleMessage(new protos.google.cloud.compute.v1.Project()), generateSampleMessage(new protos.google.cloud.compute.v1.Project()), ]; client.innerApiCalls.listXpnHosts = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { client.listXpnHosts( request, ( err?: Error | null, result?: protos.google.cloud.compute.v1.IProject[] | null ) => { if (err) { reject(err); } else { resolve(result); } } ); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.listXpnHosts as SinonStub) .getCall(0) .calledWith(request, expectedOptions /*, callback defined above */) ); }); it('invokes listXpnHosts with error', async () => { const client = new projectsModule.v1.ProjectsClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListXpnHostsProjectsRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedOptions = { otherArgs: { headers: { 'x-goog-request-params': expectedHeaderRequestParams, }, }, }; const expectedError = new Error('expected'); client.innerApiCalls.listXpnHosts = stubSimpleCall( undefined, expectedError ); await assert.rejects(client.listXpnHosts(request), expectedError); assert( (client.innerApiCalls.listXpnHosts as SinonStub) .getCall(0) .calledWith(request, expectedOptions, undefined) ); }); it('invokes listXpnHostsStream without error', async () => { const client = new projectsModule.v1.ProjectsClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListXpnHostsProjectsRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedResponse = [ generateSampleMessage(new protos.google.cloud.compute.v1.Project()), generateSampleMessage(new protos.google.cloud.compute.v1.Project()), generateSampleMessage(new protos.google.cloud.compute.v1.Project()), ]; client.descriptors.page.listXpnHosts.createStream = stubPageStreamingCall(expectedResponse); const stream = client.listXpnHostsStream(request); const promise = new Promise((resolve, reject) => { const responses: protos.google.cloud.compute.v1.Project[] = []; stream.on( 'data', (response: protos.google.cloud.compute.v1.Project) => { responses.push(response); } ); stream.on('end', () => { resolve(responses); }); stream.on('error', (err: Error) => { reject(err); }); }); const responses = await promise; assert.deepStrictEqual(responses, expectedResponse); assert( (client.descriptors.page.listXpnHosts.createStream as SinonStub) .getCall(0) .calledWith(client.innerApiCalls.listXpnHosts, request) ); assert.strictEqual( ( client.descriptors.page.listXpnHosts.createStream as SinonStub ).getCall(0).args[2].otherArgs.headers['x-goog-request-params'], expectedHeaderRequestParams ); }); it('invokes listXpnHostsStream with error', async () => { const client = new projectsModule.v1.ProjectsClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListXpnHostsProjectsRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedError = new Error('expected'); client.descriptors.page.listXpnHosts.createStream = stubPageStreamingCall( undefined, expectedError ); const stream = client.listXpnHostsStream(request); const promise = new Promise((resolve, reject) => { const responses: protos.google.cloud.compute.v1.Project[] = []; stream.on( 'data', (response: protos.google.cloud.compute.v1.Project) => { responses.push(response); } ); stream.on('end', () => { resolve(responses); }); stream.on('error', (err: Error) => { reject(err); }); }); await assert.rejects(promise, expectedError); assert( (client.descriptors.page.listXpnHosts.createStream as SinonStub) .getCall(0) .calledWith(client.innerApiCalls.listXpnHosts, request) ); assert.strictEqual( ( client.descriptors.page.listXpnHosts.createStream as SinonStub ).getCall(0).args[2].otherArgs.headers['x-goog-request-params'], expectedHeaderRequestParams ); }); it('uses async iteration with listXpnHosts without error', async () => { const client = new projectsModule.v1.ProjectsClient({ auth: googleAuth, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListXpnHostsProjectsRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedResponse = [ generateSampleMessage(new protos.google.cloud.compute.v1.Project()), generateSampleMessage(new protos.google.cloud.compute.v1.Project()), generateSampleMessage(new protos.google.cloud.compute.v1.Project()), ]; client.descriptors.page.listXpnHosts.asyncIterate = stubAsyncIterationCall(expectedResponse); const responses: protos.google.cloud.compute.v1.IProject[] = []; const iterable = client.listXpnHostsAsync(request); for await (const resource of iterable) { responses.push(resource!); } assert.deepStrictEqual(responses, expectedResponse); assert.deepStrictEqual( ( client.descriptors.page.listXpnHosts.asyncIterate as SinonStub ).getCall(0).args[1], request ); assert.strictEqual( ( client.descriptors.page.listXpnHosts.asyncIterate as SinonStub ).getCall(0).args[2].otherArgs.headers['x-goog-request-params'], expectedHeaderRequestParams ); }); it('uses async iteration with listXpnHosts with error', async () => { const client = new projectsModule.v1.ProjectsClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); client.initialize(); const request = generateSampleMessage( new protos.google.cloud.compute.v1.ListXpnHostsProjectsRequest() ); request.project = ''; const expectedHeaderRequestParams = 'project='; const expectedError = new Error('expected'); client.descriptors.page.listXpnHosts.asyncIterate = stubAsyncIterationCall(undefined, expectedError); const iterable = client.listXpnHostsAsync(request); await assert.rejects(async () => { const responses: protos.google.cloud.compute.v1.IProject[] = []; for await (const resource of iterable) { responses.push(resource!); } }); assert.deepStrictEqual( ( client.descriptors.page.listXpnHosts.asyncIterate as SinonStub ).getCall(0).args[1], request ); assert.strictEqual( ( client.descriptors.page.listXpnHosts.asyncIterate as SinonStub ).getCall(0).args[2].otherArgs.headers['x-goog-request-params'], expectedHeaderRequestParams ); }); }); });
the_stack
import { deepStrictEqual as eq, notDeepStrictEqual as neq, ok } from 'assert'; import sinon = require('sinon'); import Lifecycle from '../../main/lifecycle'; import { reset } from './mock'; const { globalShortcut } = require('electron') as any; // mocked describe('Lifecycle', function () { beforeEach(reset); function waitForWindowOpen(lifecycle: Lifecycle) { return new Promise<void>(resolve => { const ipc = (lifecycle as any).ipc; const send = ipc.send.bind(ipc); (lifecycle as any).ipc.send = function (...args: any[]) { if (args[0] === 'tweetapp:action-after-tweet') { resolve(); } send(...args); }; }); } it('creates window instance for default account but does not open yet', function () { const cfg = { default_account: 'foo' }; const opts = { text: '' }; const life = new Lifecycle(cfg, opts); const win = (life as any).currentWin; ok(win); eq(win.screenName, 'foo'); }); it('opens window when starting its lifecycle', async function () { const cfg = { default_account: 'foo', other_accounts: ['bar'] }; const opts = { text: '' }; const life = new Lifecycle(cfg, opts); life.runUntilQuit(); await waitForWindowOpen(life); neq((life as any).currentWin.win, null); eq((life as any).currentWin.screenName, 'foo'); }); it('run until quit after start', async function () { const cfg = { default_account: 'foo', other_accounts: ['bar'] }; const opts = { text: '' }; const life = new Lifecycle(cfg, opts); const dispose = sinon.fake(); (life as any).ipc.dispose = dispose; const onQuit = life.runUntilQuit(); await waitForWindowOpen(life); await life.quit(); eq((life as any).currentWin.win, null); ok(dispose.calledOnce); await onQuit; await life.didQuit; }); it('quits when window wants to quit', async function () { const cfg = { default_account: 'foo', other_accounts: ['bar'], after_tweet: 'quit' as const, }; const opts = { text: '' }; const life = new Lifecycle(cfg, opts); const onQuit = life.runUntilQuit(); await waitForWindowOpen(life); // Get callback of onCompleted which handles action after quit const callback = (life as any).currentWin.win.webContents.session.webRequest.onCompleted.lastCall.args[1]; callback({ url: 'https://api.twitter.com/1.1/statuses/update.json', statusCode: 200, method: 'POST', fromCache: false, }); await onQuit; await life.didQuit; }); it('quits when window is closed if quit_on_close is set to true', async function () { const cfg = { default_account: 'foo', other_accounts: ['bar'], after_tweet: 'quit' as const, quit_on_close: true, }; const opts = { text: '' }; const life = new Lifecycle(cfg, opts); const onQuit = life.runUntilQuit(); await waitForWindowOpen(life); await (life as any).currentWin.close(); // App quits await onQuit; await life.didQuit; }); it('restarts window without new options', async function () { const cfg = { default_account: 'foo' }; const opts = { text: '' }; const life = new Lifecycle(cfg, opts); life.runUntilQuit(); await waitForWindowOpen(life); // With no argument, it just focuses an existing window or reopen a new window await life.restart(); neq((life as any).currentWin.win, null); // On Linux or Windows app quits on close if (process.platform === 'darwin') { // Restart after closing window reopens window const prevUrl = (life as any).currentWin.win.webContents.url; await (life as any).currentWin.close(); eq((life as any).currentWin.win, null); await life.restart(); neq((life as any).currentWin.win, null); eq((life as any).currentWin.win.webContents.url, prevUrl); } await life.quit(); await life.didQuit; }); it('restarts window with new options for second instance', async function () { const cfg = { default_account: 'foo' }; const opts = { text: '' }; const life = new Lifecycle(cfg, opts); const ipc = (life as any).ipc; life.runUntilQuit(); await waitForWindowOpen(life); eq((life as any).currentWin.win.webContents.url, 'https://mobile.twitter.com/compose/tweet'); let send = sinon.fake(); ipc.send = send; let restarted = life.restart({ text: 'this is test', }); // Reopen website, but not close window (life as any).currentWin.win.webContents.emit('dom-ready'); await restarted; let call = send.getCalls().find((c: any) => c.args[0] === 'tweetapp:open'); ok(call); eq(call!.args[1], 'https://mobile.twitter.com/compose/tweet?text=this%20is%20test'); send = sinon.fake(); ipc.send = send; restarted = life.restart({ text: '', hashtags: ['foo', 'bar'], }); // Reopen website, but not close window (life as any).currentWin.win.webContents.emit('dom-ready'); await restarted; call = send.getCalls().find((c: any) => c.args[0] === 'tweetapp:open'); ok(call); eq(call!.args[1], 'https://mobile.twitter.com/compose/tweet?hashtags=foo%2Cbar'); await life.quit(); await life.didQuit; }); it('registers and unregisters hot key as global shortcut', async function () { const hotkey = 'CmdOrCtrl+Shift+X'; const cfg = { hotkey }; const life = new Lifecycle(cfg, { text: '' }); life.runUntilQuit(); await waitForWindowOpen(life); ok(globalShortcut.register.calledOnce); eq(globalShortcut.register.lastCall.args[0], hotkey); await life.quit(); await life.didQuit; ok(globalShortcut.unregisterAll.calledOnce); }); describe('Actions', function () { it('switches account reopens window for next account', async function () { const cfg = { default_account: 'foo', other_accounts: ['bar', 'piyo'] }; const opts = { text: '' }; const life = new Lifecycle(cfg, opts); life.runUntilQuit(); await waitForWindowOpen(life); // Assume it posted a tweet (life as any).currentWin.prevTweetId = '114514'; let previous = (life as any).currentWin; for (let name of ['bar', '@piyo', 'foo']) { let prevWindowClosed = false; (life as any).currentWin.win.once('closed', () => { prevWindowClosed = true; }); await life.switchAccount(name); if (name.startsWith('@')) { name = name.slice(1); // Omit @ } ok(prevWindowClosed, name); const current = (life as any).currentWin; neq(current, previous); neq(current.win, null, name); eq(current.screenName, name); previous = current; } ok((life as any).prevTweetIds.has('foo')); ok((life as any).prevTweetIds.has('bar')); ok((life as any).prevTweetIds.has('piyo')); eq((life as any).prevTweetIds.get('foo'), '114514'); eq((life as any).currentWin.prevTweetId, '114514'); // switching to the same account should cause nothing let prevWindowClosed = false; (life as any).currentWin.win.once('closed', () => { prevWindowClosed = true; }); await life.switchAccount('foo'); ok(!prevWindowClosed); // Previous tweet ID is cleared when the tweet is deleted from this app (life as any).currentWin.prevTweetId = null; await life.switchAccount('bar'); // Previous tweet ID cache should also be updated eq((life as any).prevTweetIds.get('foo'), null); await life.quit(); await life.didQuit; }); it('maintains previous tweet ID even after account switch', async function () { const cfg = { default_account: 'foo', other_accounts: ['bar', 'piyo'] }; const opts = { text: '' }; const life = new Lifecycle(cfg, opts); life.runUntilQuit(); await waitForWindowOpen(life); eq((life as any).currentWin.prevTweetId, null); (life as any).currentWin.prevTweetId = '114514'; await life.switchAccount('bar'); eq((life as any).currentWin.prevTweetId, null); (life as any).currentWin.prevTweetId = '530000'; await life.switchAccount('foo'); eq((life as any).currentWin.prevTweetId, '114514'); await life.switchAccount('bar'); eq((life as any).currentWin.prevTweetId, '530000'); await life.quit(); await life.didQuit; }); it('clicks tweet button via IPC', async function () { const life = new Lifecycle({}, { text: '' }); life.runUntilQuit(); await waitForWindowOpen(life); life.clickTweetButton(); const { send } = (life as any).currentWin.win.webContents; ok(send.called); eq(send.lastCall.args[0], 'tweetapp:click-tweet-button'); }); it('shows "new tweet" window', async function () { const life = new Lifecycle({}, { text: '' }); life.runUntilQuit(); await waitForWindowOpen(life); await (life as any).currentWin.close(); const opened = life.newTweet(); (life as any).currentWin.win.webContents.emit('dom-ready'); await opened; eq((life as any).currentWin.win.webContents.url, 'https://mobile.twitter.com/compose/tweet'); }); it('shows "reply to previous" window', async function () { const life = new Lifecycle({ default_account: 'foo' }, { text: '' }); life.runUntilQuit(); await waitForWindowOpen(life); (life as any).currentWin.prevTweetId = '114514'; await (life as any).currentWin.close(); const opened = life.replyToPrevTweet(); (life as any).currentWin.win.webContents.emit('dom-ready'); await opened; eq( (life as any).currentWin.win.webContents.url, 'https://mobile.twitter.com/compose/tweet?in_reply_to=114514', ); }); it('opens account settings page', async function () { const life = new Lifecycle({}, { text: '' }); life.runUntilQuit(); await waitForWindowOpen(life); life.openAccountSettings(); const { send } = (life as any).currentWin.win.webContents; ok(send.called); eq(send.lastCall.args, ['tweetapp:open', 'https://mobile.twitter.com/settings/account']); }); it('opens profile page for debugging', async function () { const life = new Lifecycle({ default_account: 'foo' }, { text: '' }); life.runUntilQuit(); await waitForWindowOpen(life); life.openProfilePageForDebug(); const { send } = (life as any).currentWin.win.webContents; ok(send.called); eq(send.lastCall.args, ['tweetapp:open', 'https://mobile.twitter.com/foo']); }); it('toggles window', async function () { const life = new Lifecycle({ default_account: 'foo' }, { text: '' }); life.runUntilQuit(); await waitForWindowOpen(life); const w = (life as any).currentWin; ok(w.isOpen()); await life.toggleWindow(); ok(!w.isOpen()); await life.toggleWindow(); ok(w.isOpen()); }); it('opens previous tweet page', async function () { const life = new Lifecycle({ default_account: 'foo' }, { text: '' }); life.runUntilQuit(); await waitForWindowOpen(life); const w = (life as any).currentWin; w.prevTweetId = '114514'; const opened = life.openPreviousTweet(); w.win.webContents.emit('dom-ready'); await opened; const call = w.win.webContents.send .getCalls() .reverse() .find((c: any) => c.args[0] === 'tweetapp:open'); ok(call); eq(call.args[1], 'https://mobile.twitter.com/foo/status/114514'); }); }); });
the_stack
import CommonStatistics from 'goog:proto.featureStatistics.CommonStatistics'; import DatasetFeatureStatistics from 'goog:proto.featureStatistics.DatasetFeatureStatistics'; import DatasetFeatureStatisticsList from 'goog:proto.featureStatistics.DatasetFeatureStatisticsList'; import FeatureNameStatistics from 'goog:proto.featureStatistics.FeatureNameStatistics'; import Histogram from 'goog:proto.featureStatistics.Histogram'; import NumericStatistics from 'goog:proto.featureStatistics.NumericStatistics'; import RankHistogram from 'goog:proto.featureStatistics.RankHistogram'; import StringStatistics from 'goog:proto.featureStatistics.StringStatistics'; /** * Each data point is a map of feature names to feature values, where each * feature value is a number, string, or array of numbers or strings. */ export type DataValue = number|string; export type DataPoint = {[feature: string]: DataValue|DataValue[]}; class FeatureCollector { vals: DataValue[] = []; counts: number[] = []; missing: number; type: FeatureNameStatistics.Type; } /** * Datapoints and name for a dataset, used for generating a * complete DatasetFeatureStatisticsList proto from a number * of datasets. */ export interface DataForStatsProto { data: DataPoint[]; name: string } /** * Creates DatasetFeatureStatisticsList from an array of datasets. * @param datasets An array of DataForStatsProto, one for each * dataset. * @returns The resulting DatasetFeatureStatisticsList proto. */ export function getStatsProto(datasets: DataForStatsProto[]): DatasetFeatureStatisticsList { const list = new DatasetFeatureStatisticsList(); datasets.forEach(dataset => { const stats = generateStats(dataset.data); stats.setName(dataset.name); list.getDatasetsList().push(stats); }); return list; } /** * Creates DatasetFeatureStatistics proto from a dataset. * @param items An array of DataPoints, each array entry describing an example * from the dataset. The DataPoint for an example contains numeric or * string values for each feature in the map. * @returns The resulting DatasetFeatureStatistics proto. */ export function generateStats(items?: DataPoint[]): DatasetFeatureStatistics { // TODO(jwexler): Add ability to generate weighted feature stats // if there is a specified weight feature in the dataset. const features: {[f: string]: FeatureCollector} = {}; if (items == null) { return new DatasetFeatureStatistics(); } items.forEach((item: DataPoint, i: number) => { if (item == null) { return; } const keys = Object.keys(item); const featuresSeen: {[f: string]: boolean} = {}; for (let j = 0; j < keys.length; j++) { const key = keys[j]; const value = item[key]; featuresSeen[key] = true; if (!(key in features)) { // For new features not seen in previous examples, add the feature // collector and update the missing count to include the previous // examples that didn't include the feature. features[key] = new FeatureCollector(); features[key].missing = i; features[key].counts = []; } if (typeof value === 'number' || typeof value === 'string') { features[key].vals.push(value); features[key].counts.push(1); } else if (value instanceof Array) { features[key].counts.push(value.length); features[key].vals.push(...value); } } const allFeatures = Object.keys(features); allFeatures.forEach(f => { if (!(f in featuresSeen)) { features[f].missing += 1; } }); }); const feats = Object.keys(features); feats.forEach(feat => { let numString = 0; let numNum = 0; let hasFloats = false; features[feat].vals.forEach(val => { if (typeof val === 'string') { numString += 1; } else { numNum += 1; hasFloats = hasFloats || !isInteger(val); } }); if (numNum > numString) { features[feat].type = hasFloats ? FeatureNameStatistics.Type.FLOAT : FeatureNameStatistics.Type.INT; } else { features[feat].type = FeatureNameStatistics.Type.STRING; } }); return statsFromFeatures(features, items.length); } function isInteger(n: number) { return n === +n && n === (n | 0); } function statsFromFeatures( features: {[f: string]: FeatureCollector}, numExamples: number): DatasetFeatureStatistics { const stats = new DatasetFeatureStatistics(); stats.setNumExamples(numExamples); for (const feat in features) { if (!features.hasOwnProperty(feat)) { continue; } const feature = new FeatureNameStatistics(); stats.getFeaturesList().push(feature); const collection = features[feat]; feature.setName(feat); feature.setType(collection.type); if (collection.type === FeatureNameStatistics.Type.FLOAT || collection.type === FeatureNameStatistics.Type.INT) { feature.setNumStats(createNumStats(collection.vals, collection.counts, numExamples, collection.missing)); } else if (collection.type === FeatureNameStatistics.Type.STRING) { feature.setStringStats( createStringStats(collection.vals, collection.counts, numExamples, collection.missing)); } } return stats; } function createNumStats( vals: DataValue[], counts: number[], numExamples: number, numMissing: number): NumericStatistics { const stats = new NumericStatistics(); stats.setCommonStats(createCommonStats(counts, numExamples, numMissing)); let sum = 0, sumSquares = 0, numZeros = 0; const numVals: number[] = vals.filter(rawVal => typeof rawVal === 'number' && !isNaN(rawVal)) .map(rawVal => +rawVal) .sort((a, b) => a - b); if (numVals.length > 0) { stats.setMin(numVals[0]); stats.setMax(numVals[numVals.length - 1]); const midPoint = Math.floor(numVals.length / 2); stats.setMedian( numVals.length % 2 !== 0 ? numVals[midPoint] : (numVals[midPoint] + numVals[midPoint - 1]) / 2); } numVals.forEach(val => { if (val === 0) { numZeros += 1; } sum += val; sumSquares += val * val; }); if (numVals.length > 1) { const diff = sumSquares - (sum * sum / numVals.length); const variance = diff / (numVals.length - 1); stats.setStdDev(Math.sqrt(variance)); } stats.setMean(sum / vals.length); stats.setNumZeros(numZeros); const numValsNoInf: number[] = numVals.filter(val => val !== Infinity && val !== -Infinity); const numInf = numVals.filter(val => val === Infinity).length; const numNegInf = numVals.filter(val => val === -Infinity).length; const min = numValsNoInf[0]; const max = numValsNoInf[numValsNoInf.length - 1]; const binCount = 10; const thresholds = d3.range(min, max, (max - min) / binCount); const histGenerator = d3.histogram().thresholds(thresholds); const bins = histGenerator(numValsNoInf); let h = stats.addHistograms(); h.setType(Histogram.HistogramType.STANDARD); bins.forEach((bin: {length: number, x0: number, x1: number}) => { const b = h.addBuckets(); b.setSampleCount(bin.length); b.setLowValue(bin.x0); b.setHighValue(bin.x1); }); const buckets = h.getBucketsList(); if (numVals.length && numVals[0] === -Infinity) { buckets[0].setLowValue(-Infinity); buckets[0].setSampleCount(buckets[0].getSampleCount() + numNegInf); } if (numVals.length && numVals[numVals.length - 1] === Infinity) { buckets[buckets.length - 1].setHighValue(Infinity); buckets[buckets.length - 1].setSampleCount( buckets[buckets.length - 1].getSampleCount() + numInf); } h = stats.addHistograms(); getQuantileHistogram(h, numValsNoInf); return stats; } function getQuantileHistogram(hist: Histogram, numVals: number[]) { const quantilesToGet: number[] = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]; const numQuantileBuckets = quantilesToGet.length - 1; const quantiles: number[] = quantilesToGet.map((percentile: number) => quantile(numVals, percentile)); hist.setType(Histogram.HistogramType.QUANTILES); const bucketsSampleCount = numVals.length / numQuantileBuckets; for (let qBucketIndex = 0; qBucketIndex < numQuantileBuckets; qBucketIndex++) { const b = hist.addBuckets(); b.setSampleCount(bucketsSampleCount); b.setLowValue(quantiles[qBucketIndex]); b.setHighValue(quantiles[qBucketIndex + 1]); } } function quantile(nums: number[], percentile: number): number { if (nums.length === 0) { return NaN; } const index = percentile / 100. * (nums.length - 1); const i = Math.floor(index); if (i === index) { return nums[index]; } else { const fraction = index - i; return nums[i] + (nums[i+1] - nums[i]) * fraction; } } function createStringStats( vals: DataValue[], counts: number[], numExamples: number, numMissing: number): StringStatistics { const stats = new StringStatistics(); stats.setCommonStats(createCommonStats(counts, numExamples, numMissing)); let sumLength = 0; const strCounts: {[val: string]: number} = {}; vals.forEach(rawVal => { const val: string = String(rawVal); strCounts[val] = (strCounts[val] || 0) + 1; sumLength += val.length; }); if (vals.length > 0) { stats.setAvgLength(sumLength / vals.length); } let strArray: Array<{str: string, count: number}> = []; for (const str in strCounts) { if (strCounts.hasOwnProperty(str)) { strArray.push({str, count: strCounts[str]}); } } stats.setUnique(strArray.length); strArray = strArray.sort((a, b) => b.count - a.count); const hist = new RankHistogram(); stats.setRankHistogram(hist); if (strArray.length) { const f = stats.addTopValues(); f.setValue(strArray[0].str); f.setFrequency(strArray[0].count); } strArray.forEach((entry, i) => { const bucket = hist.addBuckets(); bucket.setSampleCount(entry.count); bucket.setLowRank(i); bucket.setHighRank(i); bucket.setLabel(entry.str); }); return stats; } function createCommonStats(counts: number[], numExamples: number, numMissing: number): CommonStatistics { const common = new CommonStatistics(); let min = Infinity, max = 0, total = 0; counts.forEach(count => { if (count < min) { min = count; } if (count > max) { max = count; } total += count; }); common.setNumNonMissing(numExamples - numMissing); common.setNumMissing(numMissing); common.setMinNumValues(min); common.setMaxNumValues(max); if (counts.length > 0) { common.setAvgNumValues(total / counts.length); } const hist = new Histogram(); common.setNumValuesHistogram(hist); getQuantileHistogram(hist, counts); return common; }
the_stack
import { HomeAssistant } from 'custom-card-helpers'; import { ChartCardSeriesConfig, EntityCachePoints, EntityEntryCache, HassHistory, HassHistoryEntry, HistoryBuckets, HistoryPoint, } from './types'; import { compress, decompress, log } from './utils'; import localForage from 'localforage'; import { HassEntity } from 'home-assistant-js-websocket'; import { DateRange } from 'moment-range'; import { moment } from './const'; import parse from 'parse-duration'; import SparkMD5 from 'spark-md5'; import { ChartCardSpanExtConfig } from './types-config'; import * as pjson from '../package.json'; export default class GraphEntry { private _computedHistory?: EntityCachePoints; private _hass?: HomeAssistant; private _entityID: string; private _entityState?: HassEntity; private _updating = false; private _cache = true; // private _hoursToShow: number; private _graphSpan: number; private _useCompress = false; private _index: number; private _config: ChartCardSeriesConfig; private _func: (item: EntityCachePoints) => number; private _realStart: Date; private _realEnd: Date; private _groupByDurationMs: number; private _md5Config: string; constructor( index: number, graphSpan: number, cache: boolean, config: ChartCardSeriesConfig, span: ChartCardSpanExtConfig | undefined, ) { const aggregateFuncMap = { avg: this._average, max: this._maximum, min: this._minimum, first: this._first, last: this._last, sum: this._sum, median: this._median, delta: this._delta, diff: this._diff, }; this._index = index; this._cache = cache; this._entityID = config.entity; this._graphSpan = graphSpan; this._config = config; this._func = aggregateFuncMap[config.group_by.func]; this._realEnd = new Date(); this._realStart = new Date(); // Valid because tested during init; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this._groupByDurationMs = parse(this._config.group_by.duration)!; this._md5Config = SparkMD5.hash(`${this._graphSpan}${JSON.stringify(this._config)}${JSON.stringify(span)}`); } set hass(hass: HomeAssistant) { this._hass = hass; this._entityState = this._hass.states[this._entityID]; } get history(): EntityCachePoints { return this._computedHistory || []; } get index(): number { return this._index; } get start(): Date { return this._realStart; } get end(): Date { return this._realEnd; } set cache(cache: boolean) { this._cache = cache; } get lastState(): number | null { return this.history.length > 0 ? this.history[this.history.length - 1][1] : null; } public nowValue(now: number, before: boolean): number | null { if (this.history.length === 0) return null; const index = this.history.findIndex((point, index, arr) => { if (!before && point[0] > now) return true; if (before && point[0] < now && arr[index + 1] && arr[index + 1][0] > now) return true; return false; }); if (index === -1) return null; return this.history[index][1]; } get min(): number | undefined { if (!this._computedHistory || this._computedHistory.length === 0) return undefined; return Math.min(...this._computedHistory.flatMap((item) => (item[1] === null ? [] : [item[1]]))); } get max(): number | undefined { if (!this._computedHistory || this._computedHistory.length === 0) return undefined; return Math.max(...this._computedHistory.flatMap((item) => (item[1] === null ? [] : [item[1]]))); } public minMaxWithTimestamp(start: number, end: number): { min: HistoryPoint; max: HistoryPoint } | undefined { if (!this._computedHistory || this._computedHistory.length === 0) return undefined; if (this._computedHistory.length === 1) return { min: [start, this._computedHistory[0][1]], max: [end, this._computedHistory[0][1]] }; return this._computedHistory.reduce( (acc: { min: HistoryPoint; max: HistoryPoint }, point) => { if (point[1] === null) return acc; if (point[0] > end || point[0] < start) return acc; if (acc.max[1] === null || acc.max[1] < point[1]) acc.max = [...point]; if (acc.min[1] === null || (point[1] !== null && acc.min[1] > point[1])) acc.min = [...point]; return acc; }, { min: [0, null], max: [0, null] }, ); } public minMaxWithTimestampForYAxis(start: number, end: number): { min: HistoryPoint; max: HistoryPoint } | undefined { if (!this._computedHistory || this._computedHistory.length === 0) return undefined; let lastTimestampBeforeStart = start; const lastHistoryIndexBeforeStart = this._computedHistory.findIndex((hist) => { return hist[0] >= start; }) - 1; if (lastHistoryIndexBeforeStart >= 0) lastTimestampBeforeStart = this._computedHistory[lastHistoryIndexBeforeStart][0]; return this.minMaxWithTimestamp(lastTimestampBeforeStart, end); } private async _getCache(key: string, compressed: boolean): Promise<EntityEntryCache | undefined> { const data: EntityEntryCache | undefined | null = await localForage.getItem( `${key}_${this._md5Config}${compressed ? '' : '-raw'}`, ); return data ? (compressed ? decompress(data) : data) : undefined; } private async _setCache( key: string, data: EntityEntryCache, compressed: boolean, ): Promise<string | EntityEntryCache> { return compressed ? localForage.setItem(`${key}_${this._md5Config}`, compress(data)) : localForage.setItem(`${key}_${this._md5Config}-raw`, data); } public async _updateHistory(start: Date, end: Date): Promise<boolean> { let startHistory = new Date(start); if (this._config.group_by.func !== 'raw') { const range = end.getTime() - start.getTime(); const nbBuckets = Math.floor(range / this._groupByDurationMs) + (range % this._groupByDurationMs > 0 ? 1 : 0); startHistory = new Date(end.getTime() - (nbBuckets + 1) * this._groupByDurationMs); } if (!this._entityState || this._updating) return false; this._updating = true; if (this._config.ignore_history) { let currentState: null | number | string = null; if (this._config.attribute) { currentState = this._entityState.attributes?.[this._config.attribute]; } else { currentState = this._entityState.state; } if (this._config.transform) { currentState = this._applyTransform(currentState, this._entityState); } let stateParsed: number | null = parseFloat(currentState as string); stateParsed = !Number.isNaN(stateParsed) ? stateParsed : null; this._computedHistory = [[new Date(this._entityState.last_updated).getTime(), stateParsed]]; this._updating = false; return true; } let history: EntityEntryCache | undefined = undefined; if (this._config.data_generator) { history = await this._generateData(start, end); } else { this._realStart = new Date(start); this._realEnd = new Date(end); let skipInitialState = false; history = this._cache ? await this._getCache(this._entityID, this._useCompress) : undefined; if (history && history.span === this._graphSpan) { const currDataIndex = history.data.findIndex( (item) => item && new Date(item[0]).getTime() > startHistory.getTime(), ); if (currDataIndex !== -1) { // skip initial state when fetching recent/not-cached data skipInitialState = true; } if (currDataIndex > 4) { // >4 so that the graph has some more history history.data = history.data.slice(currDataIndex === 0 ? 0 : currDataIndex - 4); } else if (currDataIndex === -1) { // there was no state which could be used in current graph so clearing history.data = []; } } else { history = undefined; } const usableCache = !!( history && history.data && history.data.length !== 0 && history.data[history.data.length - 1] ); const newHistory = await this._fetchRecent( // if data in cache, get data from last data's time + 1ms usableCache ? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion new Date(history!.data[history!.data.length - 1][0] + 1) : new Date(startHistory.getTime() + (this._config.group_by.func !== 'raw' ? 0 : -1)), end, this._config.attribute || this._config.transform ? false : skipInitialState, ); if (newHistory && newHistory[0] && newHistory[0].length > 0) { /* hack because HA doesn't return anything if skipInitialState is false when retrieving for attributes so we retrieve it and we remove it. */ if ((this._config.attribute || this._config.transform) && skipInitialState) { newHistory[0].shift(); } let lastNonNull: number | null = null; if (history && history.data && history.data.length > 0) { lastNonNull = history.data[history.data.length - 1][1]; } const newStateHistory: EntityCachePoints = newHistory[0].map((item) => { let currentState: unknown = null; if (this._config.attribute) { if (item.attributes && item.attributes[this._config.attribute] !== undefined) { currentState = item.attributes[this._config.attribute]; } } else { currentState = item.state; } if (this._config.transform) { currentState = this._applyTransform(currentState, item); } let stateParsed: number | null = parseFloat(currentState as string); stateParsed = !Number.isNaN(stateParsed) ? stateParsed : null; if (stateParsed === null) { if (this._config.fill_raw === 'zero') { stateParsed = 0; } else if (this._config.fill_raw === 'last') { stateParsed = lastNonNull; } } else { lastNonNull = stateParsed; } if (this._config.attribute) { return [new Date(item.last_updated).getTime(), !Number.isNaN(stateParsed) ? stateParsed : null]; } else { return [new Date(item.last_changed).getTime(), !Number.isNaN(stateParsed) ? stateParsed : null]; } }); if (history?.data.length) { history.span = this._graphSpan; history.last_fetched = new Date(); history.card_version = pjson.version; if (history.data.length !== 0) { history.data.push(...newStateHistory); } } else { history = { span: this._graphSpan, card_version: pjson.version, last_fetched: new Date(), data: newStateHistory, }; } if (this._cache) { await this._setCache(this._entityID, history, this._useCompress).catch((err) => { log(err); localForage.clear(); }); } } } if (!history || history.data.length === 0) { this._updating = false; this._computedHistory = undefined; return false; } if (this._config.group_by.func !== 'raw') { const res: EntityCachePoints = this._dataBucketer(history, moment.range(startHistory, end)).map((bucket) => { return [bucket.timestamp, this._func(bucket.data)]; }); if ([undefined, 'line', 'area'].includes(this._config.type)) { while (res.length > 0 && res[0][1] === null) res.shift(); } this._computedHistory = res; } else { this._computedHistory = history.data; } this._updating = false; return true; } private _applyTransform(value: unknown, historyItem: HassHistoryEntry): number | null { return new Function('x', 'hass', 'entity', `'use strict'; ${this._config.transform}`).call( this, value, this._hass, historyItem, ); } private async _fetchRecent( start: Date | undefined, end: Date | undefined, skipInitialState: boolean, ): Promise<HassHistory | undefined> { let url = 'history/period'; if (start) url += `/${start.toISOString()}`; url += `?filter_entity_id=${this._entityID}`; if (end) url += `&end_time=${end.toISOString()}`; if (skipInitialState) url += '&skip_initial_state'; url += '&significant_changes_only=0'; return this._hass?.callApi('GET', url); } private async _generateData(start: Date, end: Date): Promise<EntityEntryCache> { // eslint-disable-next-line @typescript-eslint/no-empty-function const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor; let data; try { const datafn = new AsyncFunction( 'entity', 'start', 'end', 'hass', 'moment', `'use strict'; ${this._config.data_generator}`, ); data = await datafn(this._entityState, start, end, this._hass, moment); } catch (e) { const funcTrimmed = // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this._config.data_generator!.length <= 100 ? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this._config.data_generator!.trim() : // eslint-disable-next-line @typescript-eslint/no-non-null-assertion `${this._config.data_generator!.trim().substring(0, 98)}...`; e.message = `${e.name}: ${e.message} in '${funcTrimmed}'`; e.name = 'Error'; throw e; } return { span: 0, card_version: pjson.version, last_fetched: new Date(), data, }; } private _dataBucketer(history: EntityEntryCache, timeRange: DateRange): HistoryBuckets { const ranges = Array.from(timeRange.reverseBy('milliseconds', { step: this._groupByDurationMs })).reverse(); // const res: EntityCachePoints[] = [[]]; const buckets: HistoryBuckets = []; ranges.forEach((range, index) => { buckets[index] = { timestamp: range.valueOf(), data: [] }; }); history?.data.forEach((entry) => { buckets.some((bucket, index) => { if (bucket.timestamp > entry[0] && index > 0) { if (entry[0] >= buckets[index - 1].timestamp) { buckets[index - 1].data.push(entry); return true; } } return false; }); }); let lastNonNullBucketValue: number | null = null; const now = new Date().getTime(); buckets.forEach((bucket, index) => { if (bucket.data.length === 0) { if (this._config.group_by.fill === 'last' && (bucket.timestamp <= now || this._config.data_generator)) { bucket.data[0] = [bucket.timestamp, lastNonNullBucketValue]; } else if (this._config.group_by.fill === 'zero' && (bucket.timestamp <= now || this._config.data_generator)) { bucket.data[0] = [bucket.timestamp, 0]; } else if (this._config.group_by.fill === 'null') { bucket.data[0] = [bucket.timestamp, null]; } } else { lastNonNullBucketValue = bucket.data.slice(-1)[0][1]; } if (this._config.group_by.start_with_last) { if (index > 0) { if (bucket.data.length === 0 || bucket.data[0][0] !== bucket.timestamp) { const prevBucketData = buckets[index - 1].data; bucket.data.unshift([bucket.timestamp, prevBucketData[prevBucketData.length - 1][1]]); } } else { const firstIndexAfter = history.data.findIndex((entry) => { if (entry[0] > bucket.timestamp) return true; return false; }); if (firstIndexAfter > 0) { bucket.data.unshift([bucket.timestamp, history.data[firstIndexAfter - 1][1]]); } } } }); buckets.shift(); buckets.pop(); // Remove nulls at the end while ( buckets.length > 0 && (buckets[buckets.length - 1].data.length === 0 || (buckets[buckets.length - 1].data.length === 1 && buckets[buckets.length - 1].data[0][1] === null)) ) { buckets.pop(); } return buckets; } private _sum(items: EntityCachePoints): number { if (items.length === 0) return 0; let lastIndex = 0; return items.reduce((sum, entry, index) => { let val = 0; if (entry && entry[1] === null) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion val = items[lastIndex][1]!; } else { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion val = entry[1]!; lastIndex = index; } return sum + val; }, 0); } private _average(items: EntityCachePoints): number | null { const nonNull = this._filterNulls(items); if (nonNull.length === 0) return null; return this._sum(nonNull) / nonNull.length; } private _minimum(items: EntityCachePoints): number | null { let min: number | null = null; items.forEach((item) => { if (item[1] !== null) if (min === null) min = item[1]; else min = Math.min(item[1], min); }); return min; } private _maximum(items: EntityCachePoints): number | null { let max: number | null = null; items.forEach((item) => { if (item[1] !== null) if (max === null) max = item[1]; else max = Math.max(item[1], max); }); return max; } private _last(items: EntityCachePoints): number | null { if (items.length === 0) return null; return items.slice(-1)[0][1]; } private _first(items: EntityCachePoints): number | null { if (items.length === 0) return null; return items[0][1]; } private _median(items: EntityCachePoints) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const itemsDup = this._filterNulls([...items]).sort((a, b) => a[1]! - b[1]!); const mid = Math.floor((itemsDup.length - 1) / 2); if (itemsDup.length % 2 === 1) return itemsDup[mid][1]; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return (itemsDup[mid][1]! + itemsDup[mid + 1][1]!) / 2; } private _delta(items: EntityCachePoints): number | null { const max = this._maximum(items); const min = this._minimum(items); return max === null || min === null ? null : max - min; } private _diff(items: EntityCachePoints): number | null { const noNulls = this._filterNulls(items); const first = this._first(noNulls); const last = this._last(noNulls); if (first === null || last === null) { return null; } return last - first; } private _filterNulls(items: EntityCachePoints): EntityCachePoints { return items.filter((item) => item[1] !== null); } }
the_stack
import { NydusClient, RouteHandler, RouteInfo } from 'nydus-client' import { GameLaunchConfig, PlayerInfo } from '../../common/game-launch-config' import { GameType } from '../../common/games/configuration' import { TypedIpcRenderer } from '../../common/ipc' import { GetPreferencesPayload, MatchmakingEvent, MatchmakingStatusJson, MatchmakingType, MATCHMAKING_ACCEPT_MATCH_TIME_MS, } from '../../common/matchmaking' import { ACTIVE_GAME_LAUNCH } from '../actions' import audioManager, { AudioManager, AvailableSound } from '../audio/audio-manager' import { closeDialog, openDialog } from '../dialogs/action-creators' import { DialogType } from '../dialogs/dialog-type' import { dispatch, Dispatchable } from '../dispatch-registry' import { replace } from '../navigation/routing' import { makeServerUrl } from '../network/server-url' import { openSnackbar } from '../snackbars/action-creators' import { getCurrentMapPool } from './action-creators' const ipcRenderer = new TypedIpcRenderer() type EventToActionMap = { [E in MatchmakingEvent['type']]?: ( matchmakingType: MatchmakingType, event: Extract<MatchmakingEvent, { type: E }>, ) => Dispatchable } interface TimerState { timer: ReturnType<typeof setInterval> | undefined } interface CountdownState extends TimerState { sound: ReturnType<AudioManager['playFadeableSound']> | undefined atmosphere: ReturnType<AudioManager['playFadeableSound']> | undefined } const acceptMatchState: TimerState = { timer: undefined, } function clearAcceptMatchTimer() { const { timer } = acceptMatchState if (timer) { clearInterval(timer) acceptMatchState.timer = undefined } } const requeueState: TimerState = { timer: undefined, } function clearRequeueTimer() { const { timer } = requeueState if (timer) { clearTimeout(timer) requeueState.timer = undefined } } const countdownState: CountdownState = { timer: undefined, sound: undefined, atmosphere: undefined, } function fadeAtmosphere(fast = true) { const { atmosphere } = countdownState if (atmosphere) { const timing = fast ? 1.5 : 3 atmosphere.gainNode.gain.exponentialRampToValueAtTime(0.001, audioManager.currentTime + timing) atmosphere.source.stop(audioManager.currentTime + timing + 0.1) countdownState.atmosphere = undefined } } function clearCountdownTimer(leaveAtmosphere = false) { const { timer, sound, atmosphere } = countdownState if (timer) { clearInterval(timer) countdownState.timer = undefined } if (sound) { sound.gainNode.gain.exponentialRampToValueAtTime(0.001, audioManager.currentTime + 0.5) sound.source.stop(audioManager.currentTime + 0.6) countdownState.sound = undefined } if (!leaveAtmosphere && atmosphere) { fadeAtmosphere() } } const eventToAction: EventToActionMap = { matchFound: (matchmakingType, event) => { ipcRenderer.send('userAttentionRequired') audioManager.playSound(AvailableSound.MatchFound) clearRequeueTimer() clearAcceptMatchTimer() ipcRenderer.send('rallyPointRefreshPings') let tick = MATCHMAKING_ACCEPT_MATCH_TIME_MS / 1000 dispatch({ type: '@matchmaking/acceptMatchTime', payload: tick, }) dispatch(openDialog(DialogType.AcceptMatch)) acceptMatchState.timer = setInterval(() => { tick -= 1 dispatch({ type: '@matchmaking/acceptMatchTime', payload: tick, }) if (tick <= 0) { clearAcceptMatchTimer() } }, 1000) return { type: '@matchmaking/matchFound', payload: event, } }, playerAccepted: (matchmakingType, event) => { return { type: '@matchmaking/playerAccepted', payload: event, } }, acceptTimeout: (matchmakingType, event) => { return { type: '@matchmaking/playerFailedToAccept', payload: event, } }, requeue: (matchmakingType, event) => (dispatch, getState) => { clearRequeueTimer() clearAcceptMatchTimer() dispatch({ type: '@matchmaking/findMatch', payload: { startTime: window.performance.now() }, }) requeueState.timer = setTimeout(() => { // TODO(tec27): we should allow people to close this dialog themselves, and if/when they do, // clear this timer dispatch(closeDialog()) }, 5000) }, matchReady: (matchmakingType, event) => (dispatch, getState) => { dispatch(closeDialog()) clearAcceptMatchTimer() // All players are ready; feel free to move to the loading screen and start the game dispatch({ type: '@matchmaking/matchReady', payload: event, }) replace('/matchmaking/countdown') const { auth: { user }, } = getState() const { hash, mapData: { format }, mapUrl, } = event.chosenMap // Even though we're downloading the whole map pool as soon as the player enters the queue, // we're still leaving this as a check to make sure the map exists before starting a game. ipcRenderer.invoke('mapStoreDownloadMap', hash, format, mapUrl!)?.catch(err => { // TODO(tec27): Report this to the server so the loading is canceled immediately // This is already logged to our file by the map store, so we just log it to the console for // easy visibility during development console.error('Error downloading map: ' + err + '\n' + err.stack) }) // TODO(2Pac): This mapping should not be necessary. The game's `PlayerInfo` type and the // lobby's `Slot` type should probably be one and the same if possible. const slots: PlayerInfo[] = event.slots.map(slot => ({ id: slot.id, name: slot.name, race: slot.race, playerId: slot.playerId, type: slot.type, typeId: slot.typeId, userId: slot.userId, })) const config: GameLaunchConfig = { localUser: { id: user.id, name: user.name, }, setup: { gameId: event.setup.gameId!, name: 'Matchmaking game', // Does this even matter for anything? map: event.chosenMap, gameType: GameType.OneVsOne, slots, host: slots[0], // Arbitrarily set first player as host seed: event.setup.seed!, resultCode: event.resultCode!, serverUrl: makeServerUrl(''), }, } dispatch({ type: ACTIVE_GAME_LAUNCH, payload: ipcRenderer.invoke('activeGameSetConfig', config), } as any) }, setRoutes: (matchmakingType, event) => dispatch => { const { routes, gameId } = event ipcRenderer.invoke('activeGameSetRoutes', gameId, routes) }, // TODO(2Pac): Try to pull this out into a common place and reuse with lobbies startCountdown: (matchmakingType, event) => dispatch => { clearCountdownTimer() let tick = 5 dispatch({ type: '@matchmaking/countdownStarted', payload: tick, }) countdownState.sound = audioManager.playFadeableSound(AvailableSound.Countdown) countdownState.atmosphere = audioManager.playFadeableSound(AvailableSound.Atmosphere) countdownState.timer = setInterval(() => { tick -= 1 dispatch({ type: '@matchmaking/countdownTick', payload: tick, }) if (!tick) { clearCountdownTimer(true /* leaveAtmosphere */) } }, 1000) }, startWhenReady: (matchmakingType, event) => (dispatch, getState) => { const { gameId } = event const currentPath = location.pathname if (currentPath === '/matchmaking/countdown') { replace('/matchmaking/game-starting') } dispatch({ type: '@matchmaking/gameStarting' }) ipcRenderer.invoke('activeGameStartWhenReady', gameId) }, cancelLoading: (matchmakingType, event) => (dispatch, getState) => { clearCountdownTimer() const currentPath = location.pathname if (currentPath === '/matchmaking/countdown' || currentPath === '/matchmaking/game-starting') { replace('/') } dispatch({ type: ACTIVE_GAME_LAUNCH, payload: ipcRenderer.invoke('activeGameSetConfig', {}), } as any) dispatch({ type: '@matchmaking/loadingCanceled' }) dispatch(openSnackbar({ message: 'The game has failed to load.' })) }, gameStarted: (matchmakingType, event) => (dispatch, getState) => { fadeAtmosphere(false /* fast */) const { matchmaking: { match }, } = getState() const currentPath = location.pathname if (currentPath === '/matchmaking/game-starting') { replace('/matchmaking/active-game') } dispatch({ type: '@matchmaking/gameStarted', payload: { match, }, }) }, queueStatus: (matchmakingType, event) => { return { type: '@matchmaking/queueStatus', payload: event, } }, } export default function registerModule({ siteSocket }: { siteSocket: NydusClient }) { const matchmakingHandler: RouteHandler = (route: RouteInfo, event: MatchmakingEvent) => { if (!eventToAction[event.type]) return const action = eventToAction[event.type]!( route.params.matchmakingType as MatchmakingType, event as any, ) if (action) dispatch(action) } siteSocket.registerRoute('/matchmaking/:userName', matchmakingHandler) siteSocket.registerRoute('/matchmaking/:userId/:clientId', matchmakingHandler) siteSocket.registerRoute( '/matchmakingStatus', (route: RouteInfo, event: MatchmakingStatusJson[]) => { dispatch({ type: '@matchmaking/statusUpdate', payload: event, }) }, ) siteSocket.registerRoute( '/matchmakingPreferences/:userId/:matchmakingType', (route: RouteInfo, event: GetPreferencesPayload | Record<string, undefined>) => { const type = route.params.matchmakingType as MatchmakingType dispatch((_, getState) => { const { mapPools: { byType }, } = getState() if (!byType.has(type) || byType.get(type)!.id !== event.currentMapPoolId) { dispatch(getCurrentMapPool(type)) } dispatch({ type: '@matchmaking/initPreferences', payload: event, meta: { type }, }) }) }, ) }
the_stack
module ManipulationHelpers { import Color3 = BABYLON.Color3; import StandardMaterial = BABYLON.StandardMaterial; import Scene = BABYLON.Scene; import Matrix = BABYLON.Matrix; import Mesh = BABYLON.Mesh; import Vector3 = BABYLON.Vector3; import Quaternion = BABYLON.Quaternion; import VertexData = BABYLON.VertexData; import LinesMesh = BABYLON.LinesMesh; import PointLight = BABYLON.PointLight; import AbstractMesh = BABYLON.AbstractMesh; import Ray = BABYLON.Ray; import Vector2 = BABYLON.Vector2; export const enum RadixFeatures { None = 0, /** * Display the Arrow that follows the X Axis */ ArrowX = 0x0001, /** * Display the Arrow that follows the Y Axis */ ArrowY = 0x0002, /** * Display the Arrow that follows the Z Axis */ ArrowZ = 0x0004, /** * Display the Arrow that follows the XYZ Axis */ ArrowsXYZ = 0x0007, /** * Display the anchor that allow XY plane manipulation */ PlaneSelectionXY = 0x0010, /** * Display the anchor that allow XZ plane manipulation */ PlaneSelectionXZ = 0x0020, /** * Display the anchor that allow YZ plane manipulation */ PlaneSelectionYZ = 0x0040, /** * Display all the anchors that allow plane manipulation */ AllPlanesSelection = 0x0070, /** * Display the rotation cylinder that allows rotation manipulation along the X Axis */ RotationX = 0x0100, /** * Display the rotation cylinder that allows rotation manipulation along the Y Axis */ RotationY = 0x0200, /** * Display the rotation cylinder that allows rotation manipulation along the A Axis */ RotationZ = 0x0400, /** * Display all rotation cylinders */ Rotations = 0x0700, //CenterSquare = 0x1000 NOT SUPPORTED RIGHT NOW } /** * This class create the visual geometry to display a manipulation radix in a viewport. * It also implements the logic to handler intersection, hover on feature. */ export class Radix { private static pc = 0.6; private static sc = 0.2; /** * Set/get the Wire Selection Threshold, set a bigger value to improve tolerance while picking a wire mesh */ get wireSelectionThreshold(): number { return this._wireSelectionThreshold; } set wireSelectionThreshold(value: number) { this._wireSelectionThreshold = value; let meshes = this._rootMesh.getChildMeshes(true, m => m instanceof LinesMesh); for (var mesh of meshes) { var lm = <LinesMesh>mesh; if (lm) { lm.intersectionThreshold = value; } } } /** * Get/set the colors of the X Arrow */ get xArrowColor(): Color3 { return this._xArrowColor; } set xArrowColor(value: Color3) { this._xArrowColor = value; this.updateMaterial("arrowX", value); this.updateMaterial("rotationX", value); } /** * Get/set the colors of the Y Arrow */ get yArrowColor(): Color3 { return this._yArrowColor; } set yArrowColor(value: Color3) { this._yArrowColor = value; this.updateMaterial("arrowY", value); this.updateMaterial("rotationY", value); } /** * Get/set the colors of the Z Arrow */ get zArrowColor(): Color3 { return this._zArrowColor; } set zArrowColor(value: Color3) { this._zArrowColor = value; this.updateMaterial("arrowZ", value); this.updateMaterial("rotationZ", value); } /** * Get/set the colors of the XY Plane selection anchor */ get xyPlaneSelectionColor(): Color3 { return this._xyPlaneSelectionColor; } set xyPlaneSelectionColor(value: Color3) { this._xyPlaneSelectionColor = value; } /** * Get/set the colors of the XZ Plane selection anchor */ get xzPlaneSelectionColor(): Color3 { return this._xzPlaneSelectionColor; } set xzPlaneSelectionColor(value: Color3) { this._xzPlaneSelectionColor = value; } /** * Get/set the colors of the YZ Plane selection anchor */ get yzPlaneSelectionColor(): Color3 { return this._yzPlaneSelectionColor; } set yzPlaneSelectionColor(value: Color3) { this._yzPlaneSelectionColor = value; } /** * Get/set the feature of the Radix that are/must be highlighted * @returns {} */ get highlighted(): RadixFeatures { return this._highlighted; } set highlighted(value: RadixFeatures) { this.updateMaterialFromHighlighted(RadixFeatures.ArrowX, value, "arrowX"); this.updateMaterialFromHighlighted(RadixFeatures.ArrowY, value, "arrowY"); this.updateMaterialFromHighlighted(RadixFeatures.ArrowZ, value, "arrowZ"); this.updateMaterialFromHighlighted(RadixFeatures.PlaneSelectionXY, value, "planeXY"); this.updateMaterialFromHighlighted(RadixFeatures.PlaneSelectionXZ, value, "planeXZ"); this.updateMaterialFromHighlighted(RadixFeatures.PlaneSelectionYZ, value, "planeYZ"); this.updateMaterialFromHighlighted(RadixFeatures.RotationX, value, "rotationX"); this.updateMaterialFromHighlighted(RadixFeatures.RotationY, value, "rotationY"); this.updateMaterialFromHighlighted(RadixFeatures.RotationZ, value, "rotationZ"); this._highlighted = value; } /** * Get the Radix Features that were selected upon creation */ get features(): RadixFeatures { return this._features; } /** * Create a new Radix instance. The length/radius members are optionals and the default value should suit most cases * @param scene the owner Scene * @param features the feature the radix must display * @param arrowLength the length of a row of an axis, include the rotation cylinder (if any), but always exclude the arrow cone * @param coneLength the length of the arrow cone. this is also the length taken for the rotation cylinder (if any) * @param coneRadius the radius of the arrow cone * @param planeSelectionLength the length of the selection plane */ constructor(scene: Scene, features: RadixFeatures = RadixFeatures.ArrowsXYZ | RadixFeatures.AllPlanesSelection | RadixFeatures.Rotations, arrowLength?: number, coneLength?: number, coneRadius?: number, planeSelectionLength?: number) { this._scene = scene; this._arrowLength = arrowLength ? arrowLength : 1; this._coneLength = coneLength ? coneLength : 0.2; this._coneRadius = coneRadius ? coneRadius : 0.1; this._planeSelectionLength = planeSelectionLength ? planeSelectionLength : (this._arrowLength / 5.0); this._wireSelectionThreshold = 0.05; this._light1 = new BABYLON.PointLight("ManipulatorLight", new BABYLON.Vector3(50, 50, 70), this._scene); this._light1.id = "***SceneManipulatorLight***"; this._light2 = new BABYLON.PointLight("ManipulatorLight", new BABYLON.Vector3(-50, -50, -70), this._scene); this._light2.id = "***SceneManipulatorLight***"; this._xArrowColor = new Color3(Radix.pc, Radix.sc / 2, Radix.sc); this._yArrowColor = new Color3(Radix.sc, Radix.pc, Radix.sc / 2); this._zArrowColor = new Color3(Radix.sc / 2, Radix.sc, Radix.pc); this._xyPlaneSelectionColor = new Color3(Radix.pc / 1.1, Radix.pc / 1.3, Radix.sc); this._xzPlaneSelectionColor = new Color3(Radix.pc / 1.1, Radix.sc, Radix.pc / 1.3); this._yzPlaneSelectionColor = new Color3(Radix.sc, Radix.pc / 1.3, Radix.pc / 1.1); var materials = []; materials.push({ name: "arrowX", color: this.xArrowColor }); materials.push({ name: "arrowY", color: this.yArrowColor }); materials.push({ name: "arrowZ", color: this.zArrowColor }); materials.push({ name: "planeXY", color: this.xyPlaneSelectionColor }); materials.push({ name: "planeXZ", color: this.xzPlaneSelectionColor }); materials.push({ name: "planeYZ", color: this.yzPlaneSelectionColor }); materials.push({ name: "rotationX", color: this.xArrowColor.clone() }); materials.push({ name: "rotationY", color: this.yArrowColor.clone() }); materials.push({ name: "rotationZ", color: this.zArrowColor.clone() }); this._materials = []; for (var matData of materials) { var mtl = new StandardMaterial(matData.name + "RadixMaterial", this._scene); mtl.diffuseColor = matData.color; this._materials[matData.name] = mtl; } this._features = features; this._rootMesh = new Mesh("radixRoot", this._scene); this._rootMesh.renderingGroupId = 1; this.constructGraphicalObjects(); } /** * make an intersection test between a point position in the viwport and the Radix, return the feature that is intersected, if any. * only the closer Radix Feature is picked. * @param pos the viewport position to create the picking ray from. */ intersect(pos: Vector2): RadixFeatures { let hit = RadixFeatures.None; let closest = Number.MAX_VALUE; // Arrows if (this.hasFeature(RadixFeatures.ArrowX)) { let dist = this.intersectMeshes(pos, "arrowX", closest); if (dist < closest) { closest = dist; hit = RadixFeatures.ArrowX; } } if (this.hasFeature(RadixFeatures.ArrowY)) { let dist = this.intersectMeshes(pos, "arrowY", closest); if (dist < closest) { closest = dist; hit = RadixFeatures.ArrowY; } } if (this.hasFeature(RadixFeatures.ArrowZ)) { let dist = this.intersectMeshes(pos, "arrowZ", closest); if (dist < closest) { closest = dist; hit = RadixFeatures.ArrowZ; } } // Planes if (this.hasFeature(RadixFeatures.PlaneSelectionXY)) { let dist = this.intersectMeshes(pos, "planeXY", closest); if (dist < closest) { closest = dist; hit = RadixFeatures.PlaneSelectionXY; } } if (this.hasFeature(RadixFeatures.PlaneSelectionXZ)) { let dist = this.intersectMeshes(pos, "planeXZ", closest); if (dist < closest) { closest = dist; hit = RadixFeatures.PlaneSelectionXZ; } } if (this.hasFeature(RadixFeatures.PlaneSelectionYZ)) { let dist = this.intersectMeshes(pos, "planeYZ", closest); if (dist < closest) { closest = dist; hit = RadixFeatures.PlaneSelectionYZ; } } // Rotation if (this.hasFeature(RadixFeatures.RotationX)) { let dist = this.intersectMeshes(pos, "rotationX", closest); if (dist < closest) { closest = dist; hit = RadixFeatures.RotationX; } } if (this.hasFeature(RadixFeatures.RotationY)) { let dist = this.intersectMeshes(pos, "rotationY", closest); if (dist < closest) { closest = dist; hit = RadixFeatures.RotationY; } } if (this.hasFeature(RadixFeatures.RotationZ)) { let dist = this.intersectMeshes(pos, "rotationZ", closest); if (dist < closest) { closest = dist; hit = RadixFeatures.RotationZ; } } return hit; } /** * Set the world coordinate of where the Axis should be displayed * @param position the position * @param rotation the rotation quaternion * @param scale the scale (should be uniform) */ setWorld(position: Vector3, rotation: Quaternion, scale: Vector3) { this._rootMesh.position = position; this._rootMesh.rotationQuaternion = rotation; this._rootMesh.scaling = scale; } /** * Display the Radix on screen */ show() { this.setVisibleState(this._rootMesh, true); } /** * Hide the Radix from the screen */ hide() { this.setVisibleState(this._rootMesh, false); } private setVisibleState(mesh: AbstractMesh, state: boolean) { mesh.isVisible = state; mesh.getChildMeshes(true).forEach(m => this.setVisibleState(m, state)); } private intersectMeshes(pos: Vector2, startName: string, currentClosest: number): number { let meshes = this._rootMesh.getChildMeshes(true, m => m.name.indexOf(startName) === 0); for (var mesh of meshes) { var ray = this._scene.createPickingRay(pos.x, pos.y, mesh.getWorldMatrix(), this._scene.activeCamera); var pi = mesh.intersects(ray, false); if (pi.hit && pi.distance < currentClosest) { currentClosest = pi.distance; } } return currentClosest; } private constructGraphicalObjects() { var hp = Math.PI / 2; if (this.hasFeature(RadixFeatures.ArrowX)) { this.constructArrow(RadixFeatures.ArrowX, "arrowX", Matrix.RotationZ(-hp)); } if (this.hasFeature(RadixFeatures.ArrowY)) { this.constructArrow(RadixFeatures.ArrowY, "arrowY", Matrix.Identity()); } if (this.hasFeature(RadixFeatures.ArrowZ)) { this.constructArrow(RadixFeatures.ArrowZ, "arrowZ", Matrix.RotationX(hp)); } if (this.hasFeature(RadixFeatures.PlaneSelectionXY)) { this.constructPlaneSelection(RadixFeatures.PlaneSelectionXY, "planeXY", Matrix.Identity()); } if (this.hasFeature(RadixFeatures.PlaneSelectionXZ)) { this.constructPlaneSelection(RadixFeatures.PlaneSelectionXZ, "planeXZ", Matrix.RotationX(hp)); } if (this.hasFeature(RadixFeatures.PlaneSelectionYZ)) { this.constructPlaneSelection(RadixFeatures.PlaneSelectionYZ, "planeYZ", Matrix.RotationY(-hp)); } if (this.hasFeature(RadixFeatures.RotationX)) { this.constructRotation(RadixFeatures.RotationX, "rotationX", Matrix.RotationZ(-hp)); } if (this.hasFeature(RadixFeatures.RotationY)) { this.constructRotation(RadixFeatures.RotationY, "rotationY", Matrix.Identity()); } if (this.hasFeature(RadixFeatures.RotationZ)) { this.constructRotation(RadixFeatures.RotationZ, "rotationZ", Matrix.RotationX(hp)); } } private constructArrow(feature: RadixFeatures, name: string, transform: Matrix) { let mtl = this.getMaterial(name); let hasRot; switch (feature) { case RadixFeatures.ArrowX: hasRot = this.hasFeature(RadixFeatures.RotationX); break; case RadixFeatures.ArrowY: hasRot = this.hasFeature(RadixFeatures.RotationY); break; case RadixFeatures.ArrowZ: hasRot = this.hasFeature(RadixFeatures.RotationZ); break; } let rotation = Quaternion.FromRotationMatrix(transform); let points = new Array<number>(); points.push(0, hasRot ? this._coneLength : 0, 0); points.push(0, this._arrowLength - this._coneLength, 0); let wireMesh = new LinesMesh(name + "Wire", this._scene); wireMesh.rotationQuaternion = rotation; wireMesh.parent = this._rootMesh; wireMesh.color = mtl.diffuseColor; wireMesh.renderingGroupId = 1; wireMesh.intersectionThreshold = this.wireSelectionThreshold; wireMesh.isPickable = false; var vd = new VertexData(); vd.positions = points; vd.indices = [0, 1]; vd.applyToMesh(wireMesh); let arrow = Mesh.CreateCylinder(name + "Cone", this._coneLength, 0, this._coneRadius, 18, 1, this._scene, false); arrow.position = Vector3.TransformCoordinates(new Vector3(0, this._arrowLength - (this._coneLength / 2), 0), transform); arrow.rotationQuaternion = rotation; arrow.material = mtl; arrow.parent = this._rootMesh; arrow.renderingGroupId = 1; arrow.isPickable = false; this.addSymbolicMeshToLit(arrow); } private constructPlaneSelection(feature: RadixFeatures, name: string, transform: Matrix) { let mtl = this.getMaterial(name); let points = new Array<Vector3>(); points.push(new Vector3(this._arrowLength - this._planeSelectionLength, this._arrowLength, 0)); points.push(new Vector3(this._arrowLength, this._arrowLength, 0)); points.push(new Vector3(this._arrowLength, this._arrowLength - this._planeSelectionLength, 0)); let wireMesh = Mesh.CreateLines(name + "Plane", points, this._scene); wireMesh.parent = this._rootMesh; wireMesh.color = mtl.diffuseColor; wireMesh.rotationQuaternion = Quaternion.FromRotationMatrix(transform); wireMesh.renderingGroupId = 1; wireMesh.intersectionThreshold = this.wireSelectionThreshold; wireMesh.isPickable = false; } private constructRotation(feature: RadixFeatures, name: string, transform: Matrix) { let mtl = this.getMaterial(name); var rotCyl = Mesh.CreateCylinder(name + "Cylinder", this._coneLength, this._coneRadius, this._coneRadius, 18, 1, this._scene, false); rotCyl.material = mtl; rotCyl.position = Vector3.TransformCoordinates(new Vector3(0, this._coneLength / 2, 0), transform); rotCyl.rotationQuaternion = Quaternion.FromRotationMatrix(transform); rotCyl.parent = this._rootMesh; rotCyl.renderingGroupId = 1; rotCyl.isPickable = false; this.addSymbolicMeshToLit(rotCyl); } private addSymbolicMeshToLit(mesh: AbstractMesh) { this._light1.includedOnlyMeshes.push(mesh); this._light2.includedOnlyMeshes.push(mesh); this._scene.lights.map(l => { if ((l !== this._light1) && (l !== this._light2)) l.excludedMeshes.push(mesh) }); } private hasFeature(value: RadixFeatures): boolean { return (this._features & value) !== 0; } private hasHighlightedFeature(value: RadixFeatures): boolean { return (this._highlighted & value) !== 0; } private updateMaterial(name: string, color: Color3) { let mtl = this.getMaterial(name); if (mtl) { mtl.diffuseColor = color; } } private updateMaterialFromHighlighted(feature: RadixFeatures, highlighted: RadixFeatures, name: string) { if (!this.hasFeature(feature)) { return; } if ((this._highlighted & feature) !== (highlighted & feature)) { let mtl = this.getMaterial(name); if ((highlighted&feature) !== 0) { mtl.diffuseColor.r *= 1.8; mtl.diffuseColor.g *= 1.8; mtl.diffuseColor.b *= 1.8; } else { mtl.diffuseColor.r /= 1.8; mtl.diffuseColor.g /= 1.8; mtl.diffuseColor.b /= 1.8; } } } private getMaterial(name: string): StandardMaterial { var mtl = <StandardMaterial>this._materials[name]; return mtl; } private _arrowLength: number; private _coneLength: number; private _coneRadius: number; private _planeSelectionLength: number; private _light1: PointLight; private _light2: PointLight; private _rootMesh: Mesh; private _features: RadixFeatures; private _scene: Scene; private _materials; private _wireSelectionThreshold: number; private _xArrowColor: Color3; private _yArrowColor: Color3; private _zArrowColor: Color3; private _xyPlaneSelectionColor: Color3; private _xzPlaneSelectionColor: Color3; private _yzPlaneSelectionColor: Color3; private _highlighted: RadixFeatures; } }
the_stack
import { KKJSBridgeUtil, KKJSBridgeIframe } from "../util/KKJSBridgeUtil" /** * AJAX 相关方法 */ export class _KKJSBridgeXHR { // 静态属性和方法 public static readonly moduleName: string = 'ajax'; public static globalId: number = Math.floor(Math.random() * 1000); public static cache: any[] = []; /** * 用于处理来自 native 的异步回调 */ public static setProperties: Function = (response: any) => { let jsonObj: any; if (typeof response == "string") { jsonObj = JSON.parse(response); } else { jsonObj = response; } let id: any = jsonObj.id; let xhr: any = _KKJSBridgeXHR.cache[id]; if (xhr) { if (jsonObj.readyState === xhr.DONE) { // 防止重复利用 xhr 对象发送请求而导致 id 不变的问题 xhr.isCached = false; } // 保存回调对象,对象子属性的处理放在了 hook 里。因为 xhr 代理对象的可读属性(readyState,status,statusText,responseText)都是从实际 xhr 拷贝过来的,相应的我们也是不能直接对这些可读属性赋值的 xhr.callbackProperties = jsonObj; if (xhr.onreadystatechange) { xhr.onreadystatechange(); } // 因为不能直接赋值给 xhr 的可读属性,所以这里是使用回调对象的属性来判断 if (xhr.callbackProperties.readyState === xhr.LOADING && xhr.onprogress) { xhr.onprogress(); } if (xhr.callbackProperties.readyState === xhr.DONE) { if (xhr.onload) { xhr.onload(); } var load = document.createEvent("Events"); load.initEvent("load"); xhr.dispatchEvent(load); } } // 处理有 iframe 的情况 KKJSBridgeIframe.dispatchMessage(response); }; /** * 删除已经已经处理过的请求 */ public static deleteObject: Function = (id: any) => { if (_KKJSBridgeXHR.cache[id]) { delete _KKJSBridgeXHR.cache[id]; } } /** * 缓存 ajax 代理对象 */ private static cacheXHRIfNeed: Function = (xhr: any) => { // 添加属性,并缓存 xhr if (!xhr.hasOwnProperty('id')) { Object.defineProperties(xhr, { 'id': { value: 0, writable: true, enumerable: true }, 'callbackProperties': { value: {}, writable: true, enumerable: true }, 'isCached': { value: false, writable: true, enumerable: true } }); // readyState,status,statusText,responseText,headers Object.defineProperties(xhr.callbackProperties, { 'readyState': { value: 0, writable: true, enumerable: true }, 'status': { value: 0, writable: true, enumerable: true }, 'statusText': { value: '', writable: true, enumerable: true }, 'responseText': { value: '', writable: true, enumerable: true }, 'headers': { value: {}, writable: true, enumerable: true }, }); } if (!xhr.isCached) { // 避免重复缓存 xhr.id = _KKJSBridgeXHR.globalId++; // 请求 id 计数加 1 _KKJSBridgeXHR.cache[xhr.id] = xhr; xhr.isCached = true; } } /** * 安装 AJAX Proxy * https://github.com/wendux/Ajax-hook/blob/master/src/ajaxhook.js */ public static setupHook: Function = () => { let ob: any = {}; //Save original XMLHttpRequest as RealXMLHttpRequest var realXhr = "RealXMLHttpRequest" //Call this function will override the `XMLHttpRequest` object ob.hookAjax = function (proxy: any) { // Avoid double hook window[realXhr] = window[realXhr] || XMLHttpRequest window.XMLHttpRequest = function () { var xhr = new window[realXhr]; // We shouldn't hook XMLHttpRequest.prototype because we can't // guarantee that all attributes are on the prototype。 // Instead, hooking XMLHttpRequest instance can avoid this problem. for (var attr in xhr) { var type = ""; try { type = typeof xhr[attr]; // May cause exception on some browser } catch (e) { } if (type === "function") { // hook methods of xhr, such as `open`、`send` ... this[attr] = hookFunction(attr); } else { Object.defineProperty(this, attr, { get: getterFactory(attr), set: setterFactory(attr), enumerable: true }); } } this.xhr = xhr; } // Generate getter for attributes of xhr function getterFactory(attr: string) { return function () { var v = this.hasOwnProperty(attr + "_") ? this[attr + "_"] : this.xhr[attr]; var attrGetterHook = (proxy[attr] || {})["getter"]; return attrGetterHook && attrGetterHook(v, this) || v; } } // Generate setter for attributes of xhr; by this we have an opportunity // to hook event callbacks (eg: `onload`) of xhr; function setterFactory(attr: string) { return function (v: any) { var xhr = this.xhr; var that = this; var hook = proxy[attr]; if (typeof hook === "function") { // hook event callbacks such as `onload`、`onreadystatechange`... xhr[attr] = function () { proxy[attr](that) || v.apply(xhr, arguments); } } else { //If the attribute isn't writable, generate proxy attribute var attrSetterHook = (hook || {})["setter"]; v = attrSetterHook && attrSetterHook(v, that) || v; try { xhr[attr] = v; } catch (e) { this[attr + "_"] = v; } } } } // Hook methods of xhr. function hookFunction(fun: string) { return function () { var args = [].slice.call(arguments) /** if (proxy[fun] && proxy[fun].call(this, args, this.xhr)) { return; } 需求上是需要在方法代理时,也把代理的值返回出去,所以这里修改了源码。 */ if (proxy[fun]) { return proxy[fun].call(this, args, this.xhr); } return this.xhr[fun].apply(this.xhr, args); } } // Return the real XMLHttpRequest return window[realXhr]; } // Cancel hook ob.unHookAjax = function () { if (window[realXhr]) XMLHttpRequest = window[realXhr]; window[realXhr] = undefined; } window._KKJSBridgeAjaxProxy = ob; } /** * 是否开启 ajax hook */ public static enableAjaxHook: Function = (enable: boolean) => { if (!enable) { window._KKJSBridgeAjaxProxy.unHookAjax(); return; } /** * https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest * * 1、hook 之后,每个 XMLHttpRequest 代理对象里面都会对应一个真正的 XMLHttpRequest 对象。 * 2、支持基本属性 hook,事件属性回调 hook 和函数 hook。 * 3、基本属性和事件属性 hook 里的入参 xhr 参数是一个 XMLHttpRequest 代理对象。而函数 hook 里的入参 xhr 是一个实际 XMLHttpRequest。 所以可以给代理对象添加属性,然后在其他 hook 方法里共享属性。 * 4、函数 hook 返回 true 时,将会阻断真正的 XMLHttpRequest 的实际函数请求。 * **/ window._KKJSBridgeAjaxProxy.hookAjax({ // 拦截属性 readyState: { getter: function(v: any, xhr: any) { if (xhr.callbackProperties) { return xhr.callbackProperties.readyState; } return false; } }, status: { getter: function(v: any, xhr: any) { if (xhr.callbackProperties) { return xhr.callbackProperties.status; } return false; } }, statusText: { getter: function(v: any, xhr: any) { if (xhr.callbackProperties) { return xhr.callbackProperties.statusText; } return false; } }, responseText: { getter: function(v: any, xhr: any) { if (xhr.callbackProperties) { return xhr.callbackProperties.responseText; } return false; } }, response: { getter: function(v: any, xhr: any) { if (xhr.callbackProperties) { return xhr.callbackProperties.responseText; } return false; } }, //拦截回调 onreadystatechange: function(xhr: any) { // nothing }, onload: function(xhr: any) { // nothing }, //拦截方法 open: function(arg: any[], xhr: any) { console.log("open called: method:%s,url:%s,async:%s",arg[0],arg[1],arg[2]); const method: string = arg[0]; const url: string = arg[1]; const async: boolean = arg[2]; this.requestAsync = async; _KKJSBridgeXHR.cacheXHRIfNeed(this); window.KKJSBridge.call(_KKJSBridgeXHR.moduleName, 'open', { "id" : this.id, "method" : method, "url" : url, "scheme" : window.location.protocol, "host" : window.location.hostname, "port" : window.location.port, "href" : window.location.href, "referer" : document.referrer != "" ? document.referrer : null, "useragent" : navigator.userAgent, "async" : async, // "timeout" : this.timeout }); return true; }, send: function(arg: any[], xhr: any) { console.log("send called:", arg[0]); let body: any = arg[0]; let requestAsync: boolean = this.requestAsync; let bodyRequest: KK.AJAXBodySendRequest = { id: this.id, bodyType: "String", value: null }; function sendBody(bodyRequest: KK.AJAXBodySendRequest, requestAsync: boolean = true) { /* ajax 同步请求只支持纯文本数据,不支持 Blob 和 FormData 数据。 如果要支持的话,必须使用 FileReaderSync 对象,但是该对象只在 workers 里可用, 因为在主线程里进行同步 I/O 操作可能会阻塞用户界面。 https://developer.mozilla.org/zh-CN/docs/Web/API/FileReaderSync */ if (requestAsync) {// 异步 send 请求 window.KKJSBridge.call(_KKJSBridgeXHR.moduleName, 'send', bodyRequest); return; } // 同步 send 请求 let response: any = window.KKJSBridge.syncCall(_KKJSBridgeXHR.moduleName, 'send', bodyRequest); // 处理请求回来的结果 _KKJSBridgeXHR.setProperties(response); } if (body instanceof ArrayBuffer) {// 说明是 ArrayBuffer,转成 base64 bodyRequest.bodyType = "ArrayBuffer"; bodyRequest.value = KKJSBridgeUtil.convertArrayBufferToBase64(body); } else if (body instanceof Blob) {// 说明是 Blob,转成 base64 bodyRequest.bodyType = "Blob"; let fileReader: FileReader = new FileReader(); fileReader.onload = function(this: FileReader, ev: ProgressEvent) { let base64: string = (ev.target as any).result; bodyRequest.value = base64; sendBody(bodyRequest); }; fileReader.readAsDataURL(body); return true; } else if (body instanceof FormData) {// 说明是表单 bodyRequest.bodyType = "FormData"; bodyRequest.formEnctype = "multipart/form-data"; KKJSBridgeUtil.convertFormDataToJson(body, (json: any) => { bodyRequest.value = json; sendBody(bodyRequest); }); return true; } else {// 说明是字符串或者json bodyRequest.bodyType = "String"; bodyRequest.value = body; } sendBody(bodyRequest, requestAsync); return true; }, overrideMimeType: function(arg: any[], xhr: any) { // console.log("overrideMimeType called:", arg[0]); _KKJSBridgeXHR.cacheXHRIfNeed(this); let mimetype : string = arg[0]; window.KKJSBridge.call(_KKJSBridgeXHR.moduleName, 'overrideMimeType', { "id" : this.id, "mimetype" : mimetype }); return true; }, abort: function(arg: any[], xhr: any) { console.log("abort called"); window.KKJSBridge.call(_KKJSBridgeXHR.moduleName, 'abort', { "id" : this.id }); return true; }, setRequestHeader: function(arg: any[], xhr: any) { // console.log("setRequestHeader called:", arg[0], arg[1]); let headerName : string = arg[0]; let headerValue : string = arg[1]; window.KKJSBridge.call(_KKJSBridgeXHR.moduleName, 'setRequestHeader', { "id" : this.id, "headerName" : headerName, "headerValue" : headerValue }); return true; }, getAllResponseHeaders: function(arg: any[], xhr: any) { // console.log("getAllResponseHeaders called"); let strHeaders: string = ''; for (let name in this.callbackProperties.headers) { strHeaders += (name + ": " + this.callbackProperties.headers[name] + "\r\n"); } return strHeaders; }, getResponseHeader: function(arg: any[], xhr: any) { console.log("getResponseHeader called:", arg[0]); let headerName: string = arg[0]; let strHeaders: string = ''; let upperCaseHeaderName: string = headerName.toUpperCase(); for (let name in this.callbackProperties.headers) { if (upperCaseHeaderName == name.toUpperCase()) strHeaders = this.callbackProperties.headers[name] } return strHeaders; }, }); } }
the_stack
import {Density, FloppyDisk, FloppyDiskGeometry, SectorData, Side, TrackGeometryBuilder} from "./FloppyDisk.js"; import {ProgramAnnotation} from "./ProgramAnnotation.js"; import {CRC_16_CCITT} from "./Crc16.js"; // Print extra debug stuff. const DEBUG = false; // Bit rate on floppy. I think this is a constant on all TRS-80 floppies. const BITRATE = 250000; /** * Data for a sector on a SCP floppy. */ class ScpSector { public readonly binary: Uint8Array; public readonly idamIndex: number; public readonly damIndex: number; public readonly density: Density; constructor(binary: Uint8Array, idamIndex: number, damIndex: number, density: Density) { this.binary = binary; this.idamIndex = idamIndex; this.damIndex = damIndex; this.density = density; } public getTrackNumber(): number { return this.binary[this.idamIndex + 1]; } public getSideNumber(): number { return this.binary[this.idamIndex + 2]; } public getSectorNumber(): number { return this.binary[this.idamIndex + 3]; } public getLength(): number { return 128 << this.binary[this.idamIndex + 4]; } public getDensity(): Density { return this.density; } public isDeleted(): boolean { return this.binary[this.damIndex] === 0xF8; } /** * Get the CRC for the IDAM. */ public getIdamCrc(): number { // Big endian. return (this.binary[this.idamIndex + 5] << 8) | this.binary[this.idamIndex + 6]; } /** * Compute the CRC for the IDAM. */ public computeIdamCrc(): number { let crc = 0xFFFF; // For double density, include the three 0xA1 bytes preceding the IDAM. const begin = this.getDensity() === Density.DOUBLE ? -3 : 0; for (let i = begin; i < 5; i++) { crc = CRC_16_CCITT.update(crc, this.binary[this.idamIndex + i]); } return crc; } /** * Get the CRC for the data bytes, or undefined if the sector has no data. */ public getDataCrc(): number | undefined { // Big endian. const index = this.damIndex + 1 + this.getLength(); return (this.binary[index] << 8) + this.binary[index + 1]; } /** * Compute the CRC for the data bytes, or undefined if the sector has no data. */ public computeDataCrc(): number | undefined { let crc = 0xFFFF; const index = this.damIndex + 1; // For double density, include the preceding three 0xA1 bytes. const begin = this.getDensity() === Density.DOUBLE ? index - 4 : index - 1; const end = index + this.getLength(); for (let i = begin; i < end; i++) { crc = CRC_16_CCITT.update(crc, this.binary[i]); } return crc; } public getData(): Uint8Array { return this.binary.subarray(this.damIndex + 1, this.damIndex + 1 + this.getLength()); } } /** * Data for one revolution sample. */ class ScpRev { public readonly bitcells: Uint16Array; public readonly binary: Uint8Array; public readonly sectors: ScpSector[]; constructor(bitcells: Uint16Array, binary: Uint8Array, sectors: ScpSector[]) { this.bitcells = bitcells; this.binary = binary; this.sectors = sectors; } /** * Get the track number of this revolution from the sectors' data. */ public getTrackNumber(): number | undefined { let trackNumber: number | undefined = undefined; for (const sector of this.sectors) { const sectorTrackNumber = sector.getTrackNumber(); if (trackNumber === undefined) { trackNumber = sectorTrackNumber; } else if (trackNumber !== sectorTrackNumber) { if (DEBUG) console.log(`sector has inconsistent track number ${trackNumber} vs ${sectorTrackNumber}`); break; } } return trackNumber; } } /** * Everything we know about a track on an SCP disk. */ class ScpTrack { // Offset of start of track into binary. public readonly offset: number; public readonly trackNumber: number; public readonly side: Side; public readonly revs: ScpRev[]; constructor(offset: number, trackNumber: number, side: Side, revs: ScpRev[]) { this.offset = offset; this.trackNumber = trackNumber; this.side = side; this.revs = revs; } } /** * Entire SCP floppy. */ export class ScpFloppyDisk extends FloppyDisk { readonly className = "ScpFloppyDisk"; private geometry: FloppyDiskGeometry | undefined = undefined; public readonly tracks: ScpTrack[]; constructor(binary: Uint8Array, error: string | undefined, annotations: ProgramAnnotation[], supportsDoubleDensity: boolean, tracks: ScpTrack[]) { super(binary, error, annotations, supportsDoubleDensity); this.tracks = tracks; } getDescription(): string { return "Floppy disk (SCP)"; } getGeometry(): FloppyDiskGeometry { if (this.geometry === undefined) { const firstTrackBuilder = new TrackGeometryBuilder(); const lastTrackBuilder = new TrackGeometryBuilder(); // First compute track span. let firstTrack = 999; let lastTrack = 0; for (const track of this.tracks) { firstTrack = Math.min(firstTrack, track.trackNumber); lastTrack = Math.max(lastTrack, track.trackNumber); } // Then other geometry. for (const track of this.tracks) { const builder = track.trackNumber === firstTrack ? firstTrackBuilder : lastTrackBuilder; builder.updateSide(track.side); for (const sector of track.revs[0].sectors) { builder.updateSector(sector.getSectorNumber()); builder.updateSectorSize(sector.getLength()); builder.updateDensity(sector.getDensity()); } } this.geometry = new FloppyDiskGeometry( firstTrackBuilder.build(firstTrack), lastTrackBuilder.build(lastTrack)); } return this.geometry; } readSector(trackNumber: number, side: Side, sectorNumber: number | undefined): SectorData | undefined { for (const track of this.tracks) { if (track.trackNumber === trackNumber && track.side === side) { const rev = track.revs[0]; for (const sector of rev.sectors) { if (sectorNumber === undefined || sector.getSectorNumber() === sectorNumber) { const sectorData = new SectorData(sector.getData(), sector.getDensity()); sectorData.crcError = sector.getIdamCrc() !== sector.computeIdamCrc() || sector.getDataCrc() !== sector.computeDataCrc(); sectorData.deleted = sector.isDeleted(); return sectorData; } } break; } } return undefined; } } /** * Whether the bytes at "begin" in the binary match the letters in "text". */ function matchesAscii(binary: Uint8Array, begin: number, text: string): boolean { for (let i = 0; i < text.length; i++) { if (binary[begin + i] !== text.codePointAt(i)) { return false; } } return true; } /** * Compute a simple 32-bit checksum of a range of an array. */ function computeChecksum32(binary: Uint8Array, begin: number, end: number): number { let checksum = 0; for (let i = begin; i < end; i++) { checksum = (checksum + binary[i]) & 0xFFFFFFFF; } return checksum; } /** * Parse a little-endian integer from a binary array. */ function parseInteger(binary: Uint8Array, begin: number, byteCount: number): number { let value = 0; if (byteCount > 4) { // JavaScript only handles bit operations on 32-bit numbers. throw new Error("Cannot parse numbers larger than 32 bits"); } for (let i = 0; i < byteCount; i++) { value = (value << 8) | binary[begin + byteCount - 1 - i]; } return value; } /** * Guess the density based on the histogram of bitcells, or undefined if it can't be determined. */ function guessDensity(bitcells: Uint16Array, resolutionTimeNs: number): Density | undefined { const interval = 1e9/BITRATE/resolutionTimeNs/2; // Single density will have spikes at interval*2 and interval*4. // Double density will have spikes at interval*2, 3, and 4. const counts = new Array<number>(6).fill(0); for (const bitcell of bitcells) { const count = Math.min(Math.round(bitcell/interval), counts.length - 1); counts[count] += 1; } const min = bitcells.length/100; const high = counts.map(count => count > min); if (high[0] || high[1] || !high[2] || !high[4] || high.slice(5).indexOf(true) >= 0) { return undefined; } return high[3] ? Density.DOUBLE : Density.SINGLE; } /** * A byte with its eight clock bits. */ type ClockedData = { clock: number, data: number, } /** * Decode a sequence of flux transitions into byts with their clock bits. */ function decodeFlux(bitcells: Uint16Array, density: Density, resolutionTimeNs: number): ClockedData[] { let interval = 1e9/BITRATE/resolutionTimeNs; if (density === Density.DOUBLE) { // Double density is ... twice as dense. interval /= 2; } let data = 0; let clock = 0; let recent = 0; let nextBitIsClock = true; let bitCount: number | undefined = undefined; const bytes: ClockedData[] = []; /** * Update the clock bit for MFM. Essentially make it look like FM. */ function updateClock() { const dataBit = data & 0x01; const clockBit = clock & 0x01; const previousDataBit = (data >> 1) & 0x01; if (clockBit === 0 && dataBit === 0) { clock = (clock & 0xFE) | previousDataBit; if (previousDataBit === 0) { if (DEBUG) console.log("MISSING CLOCK BIT"); } } else if (clockBit === 0 && dataBit === 1) { // Legit 1. clock |= 1; } else if (clockBit === 1 && dataBit === 0) { if (previousDataBit === 1) { if (DEBUG) console.log("ERROR: 1/0 can't happen"); } } else if (clockBit === 1 && dataBit === 1) { if (DEBUG) console.log("ERROR: 1/1 can't happen"); } } /** * Inject a clock or data bit into the stream. */ function injectBit(value: number) { recent = (recent << 1) | value; if (density === Density.DOUBLE && (recent & 0x7FFF) === 0x4489) { // This is the 0xA1 data with the 0xFB clock. if (DEBUG) console.log("MATCH SYNC", nextBitIsClock); clock = 0xFB; data = 0xA1; nextBitIsClock = true; } else { if (nextBitIsClock) { clock = ((clock << 1) & 0xFF) | value; } else { data = ((data << 1) & 0xFF) | value; if (density === Density.DOUBLE) { updateClock(); } } nextBitIsClock = !nextBitIsClock; } // Re-sync clock and data on FM. if (density === Density.SINGLE && data === 0xFF && clock === 0x00 && value === 1) { nextBitIsClock = false; } // Look for sync bytes. if (density === Density.DOUBLE) { if (clock === 0xFB && data === 0xA1) { // bytes.push({clock, data}); bitCount = 15; if (DEBUG) console.log("Got address mark: " + data.toString(16).padStart(2, "0")); } } else { if (clock === 0xC7 && (data === 0xFE || (data >= 0xF8 && data <= 0xFB))) { // bytes.push({clock, data}); bitCount = 15; if (DEBUG) console.log("Got address mark: " + data.toString(16).padStart(2, "0")); } } // Catch new bytes. if (bitCount !== undefined) { bitCount += 1; if (bitCount === 16) { // console.log("Got byte: " + data.toString(16).padStart(2, "0")); bytes.push({clock, data}); bitCount = 0; } } if (false) { const binClock = clock.toString(2).padStart(8, "0"); const binData = data.toString(2).padStart(8, "0"); console.log( binClock.substring(0, 4) + "." + binClock.substring(4), binData.substring(0, 4) + "." + binData.substring(4), clock.toString(16).padStart(2, "0").toUpperCase(), data.toString(16).padStart(2, "0").toUpperCase(), bitCount, nextBitIsClock ? "is data" : "is clock", value); } } // Handle pulses. for (const bitcell of bitcells) { const len = Math.round(bitcell / interval); // Skip too-short pulses. if (len > 0) { // Missing pulses are zeros. for (let i = 0; i < len - 1; i++) { injectBit(0); } injectBit(1); } } return bytes; } /** * Parse one revolution of a track. */ function parseRev(binary: Uint8Array, revOffset: number, numBitcells: number, resolutionTimeNs: number): ScpRev | undefined { if (revOffset + numBitcells*2 > binary.length) { if (DEBUG) console.log("Rev runs off the end of the binary"); return undefined; } // Decode the pulse lengths. const bitcells = new Uint16Array(numBitcells); for (let i = 0; i < numBitcells; i++) { // Big endian. bitcells[i] = (binary[revOffset + i * 2] << 8) | binary[revOffset + i * 2 + 1]; } // See if we can guess the density from the distribution of pulse widths. const density = guessDensity(bitcells, resolutionTimeNs); if (density === undefined) { if (DEBUG) console.log("Can't guess rev density"); return undefined; } // Decode the whole track into bytes. const bytes = decodeFlux(bitcells, density, resolutionTimeNs); const trackBinary = new Uint8Array(bytes.map(e => e.data)); // Decode the sectors. const sectors: ScpSector[] = []; let idamIndex: number | undefined = undefined; for (let i = 0; i < bytes.length; i++) { const {clock, data} = bytes[i]; switch (density) { case Density.SINGLE: if (clock === 0xC7 && data === 0xFE) { idamIndex = i; } if (clock === 0xC7 && (data >= 0xF8 && data <= 0xFB)) { if (idamIndex !== undefined) { sectors.push(new ScpSector(trackBinary, idamIndex, i, density)); } idamIndex = undefined; } break; case Density.DOUBLE: if (clock === 0xFB && data === 0xA1) { const nextData = bytes[i + 1].data; if (nextData === 0xFE) { idamIndex = i + 1; } if (nextData >= 0xF8 && nextData <= 0xFB) { if (idamIndex !== undefined) { sectors.push(new ScpSector(trackBinary, idamIndex, i + 1, density)); } idamIndex = undefined; } } break; } } return new ScpRev(bitcells, trackBinary, sectors); } /** * Parse an SCP track at the given offset. */ function parseScpTrack(binary: Uint8Array, trackOffset: number, numRevolutions: number, resolutionTimeNs: number): ScpTrack | undefined { if (!matchesAscii(binary, trackOffset, "TRK")) { if (DEBUG) console.log("SCP: missing track magic number"); return undefined; } // Number of the track. const scpTrackNumber = binary[trackOffset + 3]; const trackNumber = Math.floor(scpTrackNumber / 2); const side = scpTrackNumber % 2 === 0 ? Side.FRONT : Side.BACK; let offset = trackOffset + 4; const revs: ScpRev[] = []; for (let rev = 0; rev < numRevolutions; rev++) { const revDurationNs = parseInteger(binary, offset, 4)*25; // Always 25, not resolutionTimeNs. offset += 4; const numBitcells = parseInteger(binary, offset, 4); offset += 4; const revOffset = parseInteger(binary, offset, 4) + trackOffset; offset += 4; // console.log(scpTrackNumber, revDurationNs, 60e9/revDurationNs, numBitcells, revOffset); const scpRev = parseRev(binary, revOffset, numBitcells, resolutionTimeNs); if (scpRev === undefined) { if (DEBUG) console.log("Can't parse rev " + rev + " for track"); return undefined; } revs.push(scpRev); } return new ScpTrack(trackOffset, trackNumber, side, revs); } /** * Decode a SuperCard Pro (.SCP) file. */ export function decodeScpFloppyDisk(binary: Uint8Array): ScpFloppyDisk | undefined { if (binary.length < 16) { // File too short, doesn't even have a header. if (DEBUG) console.log("SCP: file missing header"); return undefined; } // Parse header. if (!matchesAscii(binary, 0, "SCP")) { // Missing magic number. if (DEBUG) console.log("SCP: missing file magic number"); return undefined; } // Nibble major/minor version. We ignore this. const version = binary[3]; // Nibble manufacturer/machine disk type. We ignore this. const diskType = binary[4]; // Number of times each track was recorded. const numRevolutions = binary[5]; // First and last track number. const firstTrack = binary[6]; const lastTrack = binary[7]; // Bitflags. const flags = binary[8]; if (flags !== 0x03) { throw new Error("Don't handle SCP flags other than 0x03 currently"); } // Number of bits used by each pulse. Zero means 16. const bitCellTimeWidth = binary[9]; if (bitCellTimeWidth !== 0) { throw new Error("Don't handle SCP bit cell time width other than zero"); } // Number of heads. 0 = both, 1 = bottom, 2 = top. const headNumbers = binary[10]; // Timing resolution. const resolutionTimeNs = (binary[11] + 1)*25; // Checksum of rest of file. const expectedChecksum = parseInteger(binary, 12, 4); const actualChecksum = computeChecksum32(binary, 16, binary.length); if (expectedChecksum !== actualChecksum) { if (DEBUG) console.log(`SCP: checksum fail (${expectedChecksum} vs ${actualChecksum})`); return undefined; } // Parse tracks. const tracks: ScpTrack[] = []; for (let trackNumber = firstTrack, trackIndex = 0; trackNumber <= lastTrack; trackNumber++, trackIndex++) { const offset = parseInteger(binary, 16 + trackIndex*4, 4); if (offset !== 0) { const track = parseScpTrack(binary, offset, numRevolutions, resolutionTimeNs); if (track === undefined) { if (DEBUG) console.log("SCP: Cannot parse track " + trackNumber); } else { tracks.push(track); } } } return new ScpFloppyDisk(binary, undefined, [], true, tracks); }
the_stack
import { TypePoint, TypeContext } from '@idraw/types'; // import util from '@idraw/util'; import { BoardEvent, TypeBoardEventArgMap } from './event'; import { TempData } from './watcher-temp'; // const { throttle } = util.time; // const isInIframe = window.self === window.top; export class ScreenWatcher { private _canvas: HTMLCanvasElement; private _isMoving = false; // private _onMove?: TypeWatchCallback; // private _onMoveStart?: TypeWatchCallback; // private _onMoveEnd?: TypeWatchCallback; private _event: BoardEvent; private _temp: TempData = new TempData; private _container: HTMLElement | Window = window; // private _ctx: TypeContext; constructor(canvas: HTMLCanvasElement, ctx: TypeContext) { this._canvas = canvas; this._isMoving = false; this._initEvent(); this._event = new BoardEvent; // this._ctx = ctx; } setStatusMap(statusMap: { canScrollYPrev: boolean, canScrollYNext: boolean, canScrollXPrev: boolean, canScrollXNext: boolean, }) { this._temp.set('statusMap', statusMap); } on<T extends keyof TypeBoardEventArgMap >(name: T, callback: (p: TypeBoardEventArgMap[T]) => void): void { this._event.on(name, callback); } off<T extends keyof TypeBoardEventArgMap >(name: T, callback: (p: TypeBoardEventArgMap[T]) => void): void { this._event.off(name, callback); } _initEvent(): void { const canvas = this._canvas; const container = this._container; // container.addEventListener('mousemove', this._listenWindowHover.bind(this), false); // container.addEventListener('mousedown', this._listenWindowMoveStart.bind(this), false); container.addEventListener('mousemove', this._listenWindowMove.bind(this), false); container.addEventListener('mouseup', this._listenWindowMoveEnd.bind(this), false); canvas.addEventListener('mousemove', this._listenHover.bind(this), false); canvas.addEventListener('mousedown', this._listenMoveStart.bind(this), false); canvas.addEventListener('mousemove', this._listenMove.bind(this), false); canvas.addEventListener('mouseup', this._listenMoveEnd.bind(this), false); canvas.addEventListener('click', this._listenCanvasClick.bind(this), false); canvas.addEventListener('wheel', this._listenCanvasWheel.bind(this), false); canvas.addEventListener('mousedown', this._listenCanvasMoveStart.bind(this), true); canvas.addEventListener('mouseup', this._listenCanvasMoveEnd.bind(this), true); canvas.addEventListener('mouseover', this._listenCanvasMoveOver.bind(this), true); canvas.addEventListener('mouseleave', this._listenCanvasMoveLeave.bind(this), true); this._initParentEvent(); // container.addEventListener('touchstart', this._listenMoveStart.bind(this), true); // container.addEventListener('touchmove', this._listenMove.bind(this), true); // container.addEventListener('touchend', this._listenMoveEnd.bind(this), true); } _initParentEvent() { try { let target = window; let targetOrigin = target.origin; while (target.self !== target.top) { // If in iframe if (target.self !== target.parent) { // If in same origin if (target.origin === targetOrigin) { // window.parent.window.addEventListener( // 'mousemove', // throttle(this._listSameOriginParentWindow.bind(this), 16), // false); target.parent.window.addEventListener( 'mousemove', this._listSameOriginParentWindow.bind(this), false); } } // @ts-ignore target = target.parent; if (!target) { break; } } } catch (err) { console.warn(err); } } _listenHover(e: MouseEvent|TouchEvent): void { e.preventDefault(); const p = this._getPosition(e); if (this._isVaildPoint(p)) { if (this._event.has('hover')) { this._event.trigger('hover', p); } } this._isMoving = true; } // _listenLeave(e: MouseEvent|TouchEvent): void { // e.preventDefault(); // if (this._event.has('leave')) { // this._event.trigger('leave', undefined); // } // } _listenMoveStart(e: MouseEvent|TouchEvent): void { e.preventDefault(); const p = this._getPosition(e); if (this._isVaildPoint(p)) { if (this._event.has('point')) { this._event.trigger('point', p); } if (this._event.has('moveStart')) { this._event.trigger('moveStart', p); } } this._isMoving = true; } _listenMove(e: MouseEvent|TouchEvent): void { e.preventDefault(); e.stopPropagation(); if (this._event.has('move') && this._isMoving === true) { const p = this._getPosition(e); if (this._isVaildPoint(p)) { this._event.trigger('move', p); } } } _listenMoveEnd(e: MouseEvent|TouchEvent): void { e.preventDefault(); if (this._event.has('moveEnd')) { const p = this._getPosition(e); if (this._isVaildPoint(p)) { this._event.trigger('moveEnd', p); } } this._isMoving = false; } _listSameOriginParentWindow() { if (this._temp.get('isHoverCanvas')) { if (this._event.has('leave')) { this._event.trigger('leave', undefined); } } if (this._temp.get('isDragCanvas')) { if (this._event.has('moveEnd')) { this._event.trigger('moveEnd', {x: NaN, y: NaN}); } } this._isMoving = false; this._temp.set('isDragCanvas', false); this._temp.set('isHoverCanvas', false) } _listenCanvasMoveStart() { if (this._temp.get('isHoverCanvas')) { this._temp.set('isDragCanvas', true); } } _listenCanvasMoveEnd() { this._temp.set('isDragCanvas', false); } _listenCanvasMoveOver() { this._temp.set('isHoverCanvas', true); } _listenCanvasMoveLeave() { this._temp.set('isHoverCanvas', false); if (this._event.has('leave')) { this._event.trigger('leave', undefined); } } // _listenWindowHover(e: MouseEvent|TouchEvent|Event): void { // if (this._temp.get('isDragCanvas')) { // return; // } // e.preventDefault(); // const p = this._getPosition(e as MouseEvent|TouchEvent); // if (this._isVaildPoint(p)) { // if (this._event.has('hover')) { // this._event.trigger('hover', p); // } // } // this._isMoving = true; // } // _listenWindowMoveStart(e: MouseEvent|TouchEvent|Event): void { // if (this._temp.get('isHoverCanvas') !== true) { // return; // } // e.preventDefault(); // const p = this._getPosition(e as MouseEvent|TouchEvent); // if (this._isVaildPoint(p)) { // if (this._event.has('point')) { // this._event.trigger('point', p); // } // if (this._event.has('moveStart')) { // this._event.trigger('moveStart', p); // } // } // this._isMoving = true; // } _listenWindowMove(e: MouseEvent|TouchEvent|Event): void { if (this._temp.get('isDragCanvas') !== true) { return; } e.preventDefault(); e.stopPropagation(); if (this._event.has('move') && this._isMoving === true) { const p = this._getPosition(e as MouseEvent|TouchEvent); if (this._isVaildPoint(p)) { this._event.trigger('move', p); } } } _listenWindowMoveEnd(e: MouseEvent|TouchEvent|Event): void { if (!this._temp.get('isDragCanvas') === true) { return; } e.preventDefault(); if (this._event.has('moveEnd')) { const p = this._getPosition(e as MouseEvent|TouchEvent); if (this._isVaildPoint(p)) { this._event.trigger('moveEnd', p); } } this._temp.set('isDragCanvas', false); this._isMoving = false; } _listenCanvasWheel(e: WheelEvent) { // e.preventDefault(); // const { scrollX, scrollY } = this._ctx.getTransform(); // const { width, height } = this._ctx.getSize(); if (this._event.has('wheelX') && (e.deltaX > 0 || e.deltaX < 0)) { this._event.trigger('wheelX', e.deltaX); } if (this._event.has('wheelY') && (e.deltaY > 0 || e.deltaY < 0)) { this._event.trigger('wheelY', e.deltaY); } const { canScrollYNext, canScrollYPrev } = this._temp.get('statusMap'); if (e.deltaX > 0 && e.deltaX < 0) { e.preventDefault(); } else if (e.deltaY > 0 && canScrollYNext === true) { e.preventDefault(); } else if (e.deltaY < 0 && canScrollYPrev === true) { e.preventDefault(); } } _listenCanvasClick(e: MouseEvent|TouchEvent|Event) { e.preventDefault(); const maxLimitTime = 500; const p = this._getPosition(e as MouseEvent|TouchEvent); const t = Date.now(); if (this._isVaildPoint(p)) { const preClickPoint = this._temp.get('prevClickPoint'); if ( preClickPoint && (t - preClickPoint.t <= maxLimitTime) && Math.abs(preClickPoint.x - p.x) <= 5 && Math.abs(preClickPoint.y - p.y) <= 5 ) { if (this._event.has('doubleClick')) { this._event.trigger('doubleClick', { x: p.x, y: p.y }); } } else { this._temp.set('prevClickPoint', {x: p.x, y: p.y, t, }) } } } _getPosition(e: MouseEvent|TouchEvent): TypePoint { const canvas = this._canvas; let x = 0; let y = 0; // @ts-ignore if (e && e.touches && e.touches.length > 0) { // @ts-ignore const touch: Touch = e.touches[0]; if (touch) { x = touch.clientX; y = touch.clientY; } } else { // @ts-ignore x = e.clientX; // @ts-ignore y = e.clientY; } const p = { x: x - canvas.getBoundingClientRect().left, y: y - canvas.getBoundingClientRect().top, t: Date.now(), }; return p; } private _isVaildPoint(p: TypePoint): boolean { return isAvailableNum(p.x) && isAvailableNum(p.y); } } function isAvailableNum(num: any): boolean { return (num > 0 || num < 0 || num === 0); }
the_stack
import ez = require("TypeScript/ez") import EZ_TEST = require("./TestFramework") export class TestColor extends ez.TypescriptComponent { /* BEGIN AUTO-GENERATED: VARIABLES */ /* END AUTO-GENERATED: VARIABLES */ constructor() { super() } static RegisterMessageHandlers() { ez.TypescriptComponent.RegisterMessageHandler(ez.MsgGenericEvent, "OnMsgGenericEvent"); } ExecuteTests(): void { const op1 = new ez.Color(-4.0, 0.2, -7.0, -0.0); const op2 = new ez.Color(2.0, 0.3, 0.0, 1.0); const compArray = [new ez.Color(1.0, 0.0, 0.0, 0.0), new ez.Color(0.0, 1.0, 0.0, 0.0), new ez.Color(0.0, 0.0, 1.0, 0.0), new ez.Color(0.0, 0.0, 0.0, 1.0)]; // default constructor { let c = new ez.Color(); EZ_TEST.FLOAT(c.r, 0); EZ_TEST.FLOAT(c.g, 0); EZ_TEST.FLOAT(c.b, 0); EZ_TEST.FLOAT(c.a, 1); } // constructor { let c = new ez.Color(1, 2, 3, 4); EZ_TEST.FLOAT(c.r, 1); EZ_TEST.FLOAT(c.g, 2); EZ_TEST.FLOAT(c.b, 3); EZ_TEST.FLOAT(c.a, 4); } // Clone { let c0 = new ez.Color(1, 2, 3, 4); let c = c0.Clone(); c0.SetLinearRGBA(2, 3, 4, 5); EZ_TEST.FLOAT(c.r, 1); EZ_TEST.FLOAT(c.g, 2); EZ_TEST.FLOAT(c.b, 3); EZ_TEST.FLOAT(c.a, 4); } // SetColor { let c0 = new ez.Color(1, 2, 3, 4); let c = new ez.Color(); c.SetColor(c0); EZ_TEST.FLOAT(c.r, 1); EZ_TEST.FLOAT(c.g, 2); EZ_TEST.FLOAT(c.b, 3); EZ_TEST.FLOAT(c.a, 4); } // ZeroColor { let c = ez.Color.ZeroColor(); EZ_TEST.FLOAT(c.r, 0); EZ_TEST.FLOAT(c.g, 0); EZ_TEST.FLOAT(c.b, 0); EZ_TEST.FLOAT(c.a, 0); } // SetZero { let c = new ez.Color(1, 2, 3, 4); c.SetZero(); EZ_TEST.FLOAT(c.r, 0); EZ_TEST.FLOAT(c.g, 0); EZ_TEST.FLOAT(c.b, 0); EZ_TEST.FLOAT(c.a, 0); } // ColorByteToFloat { EZ_TEST.FLOAT(ez.Color.ColorByteToFloat(0), 0.0, 0.000001); EZ_TEST.FLOAT(ez.Color.ColorByteToFloat(128), 0.501960784, 0.000001); EZ_TEST.FLOAT(ez.Color.ColorByteToFloat(255), 1.0, 0.000001); } // ColorFloatToByte { EZ_TEST.INT(ez.Color.ColorFloatToByte(-1.0), 0); EZ_TEST.INT(ez.Color.ColorFloatToByte(0.0), 0); EZ_TEST.INT(ez.Color.ColorFloatToByte(0.4), 102); EZ_TEST.INT(ez.Color.ColorFloatToByte(1.0), 255); EZ_TEST.INT(ez.Color.ColorFloatToByte(1.5), 255); } // SetLinearRGB / SetLinearRGBA { let c1 = new ez.Color(0, 0, 0, 0); c1.SetLinearRGBA(1, 2, 3, 4); EZ_TEST.COLOR(c1, new ez.Color(1, 2, 3, 4)); c1.SetLinearRGB(5, 6, 7); EZ_TEST.COLOR(c1, new ez.Color(5, 6, 7, 4)); } // IsIdenticalRGB { let c1 = new ez.Color(0, 0, 0, 0); let c2 = new ez.Color(0, 0, 0, 1); EZ_TEST.BOOL(c1.IsIdenticalRGB(c2)); EZ_TEST.BOOL(!c1.IsIdenticalRGBA(c2)); } // IsIdenticalRGBA { let tmp1 = new ez.Color(); let tmp2 = new ez.Color(); EZ_TEST.BOOL(op1.IsIdenticalRGBA(op1)); for (let i = 0; i < 4; ++i) { tmp1.SetColor(compArray[i]); tmp1.MulNumber(0.001); tmp1.AddColor(op1); tmp2.SetColor(compArray[i]); tmp2.MulNumber(-0.001); tmp2.AddColor(op1); EZ_TEST.BOOL(!op1.IsIdenticalRGBA(tmp1)); EZ_TEST.BOOL(!op1.IsIdenticalRGBA(tmp2)); } } // IsEqualRGB { let c1 = new ez.Color(0, 0, 0, 0); let c2 = new ez.Color(0, 0, 0.2, 1); EZ_TEST.BOOL(!c1.IsEqualRGB(c2, 0.1)); EZ_TEST.BOOL(c1.IsEqualRGB(c2, 0.3)); EZ_TEST.BOOL(!c1.IsEqualRGBA(c2, 0.3)); } // IsEqualRGBA { let tmp1 = new ez.Color(); let tmp2 = new ez.Color(); EZ_TEST.BOOL(op1.IsEqualRGBA(op1, 0.0)); for (let i = 0; i < 4; ++i) { tmp1.SetColor(compArray[i]); tmp1.MulNumber(0.001); tmp1.AddColor(op1); tmp2.SetColor(compArray[i]); tmp2.MulNumber(-0.001); tmp2.AddColor(op1); EZ_TEST.BOOL(op1.IsEqualRGBA(tmp1, 2 * 0.001)); EZ_TEST.BOOL(op1.IsEqualRGBA(tmp2, 2 * 0.001)); EZ_TEST.BOOL(op1.IsEqualRGBA(tmp2, 2 * 0.001)); EZ_TEST.BOOL(op1.IsEqualRGBA(tmp2, 2 * 0.001)); } } // AddColor { let plusAssign = op1.Clone(); plusAssign.AddColor(op2); EZ_TEST.BOOL(plusAssign.IsEqualRGBA(new ez.Color(-2.0, 0.5, -7.0, 1.0), 0.0001)); } // SubColor { let minusAssign = op1.Clone(); minusAssign.SubColor(op2); EZ_TEST.BOOL(minusAssign.IsEqualRGBA(new ez.Color(-6.0, -0.1, -7.0, -1.0), 0.0001)); } // MulNumber { let mulFloat = op1.Clone(); mulFloat.MulNumber(2.0); EZ_TEST.BOOL(mulFloat.IsEqualRGBA(new ez.Color(-8.0, 0.4, -14.0, -0.0), 0.0001)); mulFloat.MulNumber(0.0); EZ_TEST.BOOL(mulFloat.IsEqualRGBA(new ez.Color(0.0, 0.0, 0.0, 0.0), 0.0001)); } // DivNumber { let vDivFloat = op1.Clone(); vDivFloat.DivNumber(2.0); EZ_TEST.BOOL(vDivFloat.IsEqualRGBA(new ez.Color(-2.0, 0.1, -3.5, -0.0), 0.0001)); } // SetAdd { let plus = new ez.Color(); plus.SetAdd(op1, op2); EZ_TEST.BOOL(plus.IsEqualRGBA(new ez.Color(-2.0, 0.5, -7.0, 1.0), 0.0001)); } // SetSub { let minus = new ez.Color(); minus.SetSub(op1, op2); EZ_TEST.BOOL(minus.IsEqualRGBA(new ez.Color(-6.0, -0.1, -7.0, -1.0), 0.0001)); } // SetMulNumber { let mulVec4Float = new ez.Color(); mulVec4Float.SetMulNumber(op1, 2); EZ_TEST.BOOL(mulVec4Float.IsEqualRGBA(new ez.Color(-8.0, 0.4, -14.0, -0.0), 0.0001)); mulVec4Float.SetMulNumber(op1, 0); EZ_TEST.BOOL(mulVec4Float.IsEqualRGBA(new ez.Color(0.0, 0.0, 0.0, 0.0), 0.0001)); } // SetDivNumber { let vDivVec4Float = new ez.Color(); vDivVec4Float.SetDivNumber(op1, 2); EZ_TEST.BOOL(vDivVec4Float.IsEqualRGBA(new ez.Color(-2.0, 0.1, -3.5, -0.0), 0.0001)); } // SetGammaByteRGB { let c = new ez.Color(); c.SetGammaByteRGB(50, 100, 150); EZ_TEST.FLOAT(c.r, 0.031); EZ_TEST.FLOAT(c.g, 0.127); EZ_TEST.FLOAT(c.b, 0.304); EZ_TEST.FLOAT(c.a, 1.0); } // SetGammaByteRGBA { let c = new ez.Color(); c.SetGammaByteRGBA(50, 100, 150, 127.5); EZ_TEST.FLOAT(c.r, 0.031); EZ_TEST.FLOAT(c.g, 0.127); EZ_TEST.FLOAT(c.b, 0.304); EZ_TEST.FLOAT(c.a, 0.5); } // ScaleRGB { let c = new ez.Color(1, 2, 3, 0.5); c.ScaleRGB(2); EZ_TEST.FLOAT(c.r, 2); EZ_TEST.FLOAT(c.g, 4); EZ_TEST.FLOAT(c.b, 6); EZ_TEST.FLOAT(c.a, 0.5); } // MulColor { let c = new ez.Color(2, 3, 4, 6); let m = new ez.Color(5, 3, 2, 0.5); c.MulColor(m); EZ_TEST.FLOAT(c.r, 10); EZ_TEST.FLOAT(c.g, 9); EZ_TEST.FLOAT(c.b, 8); EZ_TEST.FLOAT(c.a, 3); } // SetMul { let n = new ez.Color(2, 3, 4, 6); let m = new ez.Color(5, 3, 2, 0.5); let c = new ez.Color(); c.SetMul(n, m); EZ_TEST.FLOAT(c.r, 10); EZ_TEST.FLOAT(c.g, 9); EZ_TEST.FLOAT(c.b, 8); EZ_TEST.FLOAT(c.a, 3); } // WithAlpha { let o = new ez.Color(2, 3, 4, 6); let c = o.WithAlpha(0.5); EZ_TEST.FLOAT(c.r, 2); EZ_TEST.FLOAT(c.g, 3); EZ_TEST.FLOAT(c.b, 4); EZ_TEST.FLOAT(c.a, 0.5); } // CalcAverageRGB { let c = new ez.Color(1, 1, 1, 2); EZ_TEST.FLOAT(c.CalcAverageRGB(), 1.0); } // IsNormalized { let c = new ez.Color(1, 1, 1, 1); EZ_TEST.BOOL(c.IsNormalized()); c.a = 2.0; EZ_TEST.BOOL(!c.IsNormalized()); } // GetLuminance { EZ_TEST.FLOAT(ez.Color.Black().GetLuminance(), 0.0); EZ_TEST.FLOAT(ez.Color.White().GetLuminance(), 1.0); EZ_TEST.FLOAT(new ez.Color(0.5, 0.5, 0.5).GetLuminance(), 0.2126 * 0.5 + 0.7152 * 0.5 + 0.0722 * 0.5); } // GetInvertedColor { let c1 = new ez.Color(0.1, 0.3, 0.7, 0.9); let c2 = c1.GetInvertedColor(); EZ_TEST.BOOL(c2.IsEqualRGBA(new ez.Color(0.9, 0.7, 0.3, 0.1), 0.01)); } // ComputeHdrExposureValue { let c = new ez.Color(); EZ_TEST.FLOAT(c.ComputeHdrExposureValue(), 0); c.SetLinearRGB(2, 3, 4); EZ_TEST.FLOAT(c.ComputeHdrExposureValue(), 2); } // ApplyHdrExposureValue { let c = new ez.Color(1, 1, 1, 1); c.ApplyHdrExposureValue(2); EZ_TEST.FLOAT(c.ComputeHdrExposureValue(), 2); } // GetAsGammaByteRGBA { let c = new ez.Color(); c.SetGammaByteRGBA(50, 100, 150, 200); let g = c.GetAsGammaByteRGBA(); EZ_TEST.FLOAT(g.byteR, 50); EZ_TEST.FLOAT(g.byteG, 100); EZ_TEST.FLOAT(g.byteB, 150); EZ_TEST.FLOAT(g.byteA, 200); } } OnMsgGenericEvent(msg: ez.MsgGenericEvent): void { if (msg.Message == "TestColor") { this.ExecuteTests(); msg.Message = "done"; } } }
the_stack
export namespace FontBook { // Default Application export interface Application {} // Class /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Abstract object provides a base class for scripting classes. It is never used directly. */ export interface Item { /** * The class of the object. */ class(): any; /** * All of the object's properties. */ properties(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * An application's top level scripting object. */ export interface Application { /** * The name of the application. */ name(): string; /** * Is this the frontmost (active) application? */ frontmost(): boolean; /** * The version of the application. */ version(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A color. */ export interface Color {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A document. */ export interface Document { /** * The document's path. */ path(): string; /** * Has the document been modified since the last save? */ modified(): boolean; /** * The document's name. */ name(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A window. */ export interface Window { /** * The full title of the window. */ name(): string; /** * The unique identifier of the window. */ id(): number; /** * The bounding rectangle of the window. */ bounds(): any; /** * Whether the window has a close box. */ closeable(): boolean; /** * Whether the window has a title bar. */ titled(): boolean; /** * The index of the window in the back-to-front window ordering. */ index(): number; /** * Whether the window floats. */ floating(): boolean; /** * Whether the window can be miniaturized. */ miniaturizable(): boolean; /** * Whether the window is currently miniaturized. */ miniaturized(): boolean; /** * Whether the window is the application's current modal window. */ modal(): boolean; /** * Whether the window can be resized. */ resizable(): boolean; /** * Whether the window is currently visible. */ visible(): boolean; /** * Whether the window can be zoomed. */ zoomable(): boolean; /** * Whether the window is currently zoomed. */ zoomed(): boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A font family */ export interface FontFamily { /** * The name of the family */ name(): string; /** * Synonym for displayed name */ displayName(): string; /** * Font family display name */ displayedName(): string; /** * A font family */ enabled(): boolean; /** * Whether the family contains duplicated faces */ duplicated(): boolean; /** * Font files for the family */ files(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A typeface */ export interface Typeface { /** * The name of the family */ name(): string; /** * Synonym for displayed name */ displayName(): string; /** * Typeface display name */ displayedName(): string; /** * Font family */ fontFamily(): any; /** * Font family name */ familyName(): string; /** * Style name */ styleName(): string; /** * PostScript font name */ postScriptName(): string; /** * The unique identifier of the typeface */ ID(): string; /** * A font family */ enabled(): boolean; /** * Whether the typeface is duplicated or not duplicated faces */ duplicated(): boolean; /** * Font format */ fontType(): string; /** * Copyright */ copyright(): string; /** * Font container */ fontContainer(): any; /** * Font files for the face */ files(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * An abstact object representing font files */ export interface FontContainer { /** * The name of the container */ name(): string; /** * The path to the main container */ path(): string; /** * Files for the container */ files(): any; /** * Font Domain for the container */ domain(): any; /** * The unique identifier of the container */ ID(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A font collection. */ export interface FontCollection { /** * The name of the collection */ name(): string; /** * Synonym for displayed name */ displayName(): string; /** * Display name of the domain */ displayedName(): string; /** * Whether the collection is enabled or disabled. */ enabled(): boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A font library */ export interface FontLibrary {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * MyFonts font library */ export interface MyFontsLibrary {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A font domain */ export interface FontDomain { /** * The unique identifier of the domain */ ID(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * All Fonts library object */ export interface AllFontsLibraryObject {} // CLass Extension /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Font Book's top level scripting object. */ export interface Application { /** * Whether validating fonts before installing or not. */ validateFontsBeforeInstalling(): boolean; /** * Where to install fonts. */ installationTarget(): any; /** * The All Fonts library. */ fontsLibrary(): any; /** * current selection. */ selection(): any; /** * selected font families. */ selectedFontFamilies(): any; /** * selected collections. */ selectedCollections(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A typeface */ export interface Typeface { /** * additional info about the typeface */ typefaceAdditionalInfo(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * All Fonts library object */ export interface AllFontsLibraryObject { /** * Whether the collection is enabled or disabled. */ enabled(): boolean; } // Records // Function options /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface QuitOptionalParameter { /** * Specifies whether changes should be saved before quitting. */ saving?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface CloseOptionalParameter { /** * Specifies whether changes should be saved before closing. */ saving?: any; /** * The file in which to save the object. */ savingIn?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface CountOptionalParameter { /** * The class of objects to be counted. */ each?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface DuplicateOptionalParameter { /** * The location for the new object(s). */ to: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface MakeOptionalParameter { /** * The class of the new object. */ new: any; /** * The location at which to insert the object. */ at?: any; /** * The initial data for the object. */ withData?: any; /** * The initial values for properties of the object. */ withProperties?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface MoveOptionalParameter { /** * The new location for the object(s). */ to: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface SaveOptionalParameter { /** * The file in which to save the object. */ in?: string; /** * The file type in which to save the data. */ as?: string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface SetOptionalParameter { /** * The new value. */ to: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface AddOptionalParameter { /** * The container to which to add the object */ to?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface RemoveOptionalParameter { /** * The container from which to remove the object */ from?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface ExportOptionalParameter { /** * The path to which to export the objeccts */ to: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface ValidateFontFileOptionalParameter { /** * Whether to generate summay. */ generatingSummaryOnly?: boolean; /** * Whether to ignore erros. */ ignorringErrors?: boolean; /** * Whether to do dynamic checking. */ dynamicChecking?: boolean; /** * Additional parameters. */ withProperties?: any; } } export interface FontBook extends FontBook.Application { // Functions /** * Open an object. * @param directParameter list of objects to open * */ open(directParameter: any, ): void; /** * Print an object. * @param directParameter list of objects to print * */ print(directParameter: any, ): void; /** * Quit an application. * @param option * */ quit(option?: FontBook.QuitOptionalParameter): void; /** * Close an object. * @param directParameter the object to close * @param option * */ close(directParameter: any, option?: FontBook.CloseOptionalParameter): void; /** * Return the number of elements of a particular class within an object. * @param directParameter the object whose elements are to be counted * @param option * @return the number of elements */ count(directParameter: any, option?: FontBook.CountOptionalParameter): number; /** * Delete an object. * @param directParameter the object to delete * */ delete(directParameter: any, ): void; /** * Copy object(s) and put the copies at a new location. * @param directParameter the object(s) to duplicate * @param option * */ duplicate(directParameter: any, option?: FontBook.DuplicateOptionalParameter): void; /** * Verify if an object exists. * @param directParameter the object in question * @return true if it exists, false if not */ exists(directParameter: any, ): boolean; /** * Get the data for an object. * @param directParameter undefined * @return undefined */ get(directParameter: any, ): any; /** * Make a new object. * @param option * @return to the new object */ make(option?: FontBook.MakeOptionalParameter): any; /** * Move object(s) to a new location. * @param directParameter the object(s) to move * @param option * */ move(directParameter: any, option?: FontBook.MoveOptionalParameter): void; /** * Save an object. * @param directParameter the object to save, usually a document or window * @param option * */ save(directParameter: any, option?: FontBook.SaveOptionalParameter): void; /** * Set an object's data. * @param directParameter undefined * @param option * */ set(directParameter: any, option?: FontBook.SetOptionalParameter): void; /** * Add the given object to the container. * @param directParameter The object for the command * @param option * */ add(directParameter: any, option?: FontBook.AddOptionalParameter): void; /** * Remove the given object from the container. * @param directParameter The object for the command * @param option * */ remove(directParameter: any, option?: FontBook.RemoveOptionalParameter): void; /** * Export the given objects to the specified location. * @param directParameter The object for the command * @param option * */ export(directParameter: any, option?: FontBook.ExportOptionalParameter): void; /** * Validate the given font file. * @param directParameter The file for the command * @param option * @return undefined */ validateFontFile(directParameter: any, option?: FontBook.ValidateFontFileOptionalParameter): any; }
the_stack
import { AttestationSigner } from "."; import { GeneratedAttestationResult } from "../generated"; import { _attestationSignerFromGenerated } from "./attestationSigner"; /** * Defines the contents of the {@link AttestationResult.sgxCollateral} claim in * an {@link AttestationResult}. */ export interface AttestationSgxCollateralInfo { /** * Hex encoded Sha256 hash of the Quoting Enclave Certificates. * * See the {@link https://software.intel.com/content/www/us/en/develop/articles/quote-verification-attestation-with-intel-sgx-dcap.html | Intel SGX documentation } * for more information on quote validation. */ qeidcertshash?: string; /** * Hex encoded Sha256 hash of the Quoting Enclave Certificate CRL. * * See the {@link https://software.intel.com/content/www/us/en/develop/articles/quote-verification-attestation-with-intel-sgx-dcap.html | Intel SGX documentation } * for more information on quote validation. */ qeidcrlhash?: string; /** * Hex encoded Sha256 hash of the Quoting Enclave Identity. * * See the {@link https://software.intel.com/content/www/us/en/develop/articles/quote-verification-attestation-with-intel-sgx-dcap.html | Intel SGX documentation } * for more information on quote validation. */ qeidhash?: string; /** * Hex encoded Sha256 hash of the SGX Quote or OpenEnclave Report validated * by this token. * * See the {@link https://software.intel.com/content/www/us/en/develop/articles/quote-verification-attestation-with-intel-sgx-dcap.html | Intel SGX documentation } * for more information on quote validation. */ quotehash?: string; /** * Hex encoded Sha256 hash of the TCB Info Certificates. * * See the {@link https://software.intel.com/content/www/us/en/develop/articles/quote-verification-attestation-with-intel-sgx-dcap.html | Intel SGX documentation } * for more information on quote validation. */ tcbinfocertshash?: string; /** * Hex encoded Sha256 hash of the TCB Info Certificate CRL. * * See the {@link https://software.intel.com/content/www/us/en/develop/articles/quote-verification-attestation-with-intel-sgx-dcap.html | Intel SGX documentation } * for more information on quote validation. */ tcbinfocrlhash?: string; /** * Hex encoded Sha256 hash of the TCB Info for the device being attested. * * See the {@link https://software.intel.com/content/www/us/en/develop/articles/quote-verification-attestation-with-intel-sgx-dcap.html | Intel SGX documentation } * for more information on quote validation. */ tcbinfohash?: string; } /** * A Microsoft Azure Attestation response token body - the body of a response token issued by MAA */ export interface AttestationResult { /** * Unique Identifier for the token. * * Corresponds to the 'jti' claim defined in * {@link https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.7 | RFC 7519 section 4.1.7} */ uniqueId: string; /** * Returns the issuer of the attestation token. MUST be the same as the * endpoint used when constructing the attestation client instance. */ issuer: string; /** * Returns the "nonce" value if one was specified in the Attest request. */ nonce?: string; /** * The Schema version of this structure. Current Value: 1.0 */ version: string; /** * Returns the runtime claims in the token. * * This value will match the input `runTimeJson` property to the * {@link AttestationClient.attestSgxEnclave} or * {@link AttestationClient.attestOpenEnclave} API. * * @remarks * * The `runtimeClaims` property will only be populated if the * `runtimeJson` parameter to the `Attest` API is specified. It will * not be populated if the `runtimeData` parameter is specified. */ runTimeClaims: unknown; /** * Returns the initialization time claims in the token. * This value will match the input `initTimeJson` property to the * {@link AttestationClient.attestSgxEnclave} or * {@link AttestationClient.attestOpenEnclave} API. * * @remarks * * The `initTimeClaims` property will only be populated if the `initTimeJson` * parameter to the `Attest` API is specified. It will not be populated if * the `initTimeData` parameter is specified. */ initTimeClaims: unknown; /** * Returns the set of claims generated by the attestation policy on the instance. */ policyClaims: unknown; /** * Returns the verifier which generated this attestation token. Normally one of: * "SGX" or "TPM", but others can be specified. */ verifierType: string; /** * The certificate used to sign the policy object, if specified. */ policySigner?: AttestationSigner; /** * The base64url encoded SHA256 hash of the BASE64URL encoded policy text * used for attestation. */ policyHash: Uint8Array; /** * True if the enclave is debuggable, false otherwise. Only valid if `verifierType` is SGX. */ isDebuggable?: boolean; /** * The SGX Product ID for the enclave. Only valid if the `verifierType` field is "SGX" */ productId?: number; /** * The HEX encoded SGX MRENCLAVE value for the enclave. Only valid if the * `verifierType` field is "SGX" */ mrEnclave?: string; /** * The HEX encoded SGX MRSIGNER value for the enclave. Only valid if the * `verifierType` field is "SGX" */ mrSigner?: string; /** * The SGX SVN value for the enclave. Only valid if the `verifierType` field is "SGX" */ svn?: number; /** * Returns the value of the runtime_data field specified as an input to the * {@link AttestationClient.attestSgxEnclave} or {@link AttestationClient.attestOpenEnclave} API. * * @remarks * * The `enclaveHeldData` property will only be populated if the * `runtimeData` parameter to the `Attest` API is specified. */ enclaveHeldData?: Uint8Array; /** * Returns a set of information describing the complete set of inputs to the * Attestation validation logic. * * See the {@link https://software.intel.com/content/www/us/en/develop/articles/quote-verification-attestation-with-intel-sgx-dcap.html | Intel SGX documentation } * for more information on quote validation. */ sgxCollateral?: AttestationSgxCollateralInfo; } /** * A Microsoft Azure Attestation response token body - the body of a response token issued by MAA */ export class AttestationResultImpl implements AttestationResult { /** * * @param params - The parameters for the constructor. * * @hidden */ constructor(params: { issuer: string; version: string; nonce?: string; uniqueId: string; runTimeClaims?: unknown; initTimeClaims?: unknown; policyClaims?: unknown; verifierType: string; policySigner?: AttestationSigner; policyHash: Uint8Array; isDebuggable?: boolean; productId?: number; mrEnclave?: string; mrSigner?: string; svn?: number; enclaveHeldData?: Uint8Array; sgxCollateral?: AttestationSgxCollateralInfo; }) { this._issuer = params.issuer; this._nonce = params.nonce; this._version = params.version; this._uniqueId = params.uniqueId; this._runTimeClaims = params.runTimeClaims; this._initTimeClaims = params.initTimeClaims; this._policyClaims = params.policyClaims; this._verifierType = params.verifierType; this._policySigner = params.policySigner; this._policyHash = params.policyHash; this._isDebuggable = params.isDebuggable; this._productId = params.productId; this._mrEnclave = params.mrEnclave; this._mrSigner = params.mrSigner; this._svn = params.svn; this._enclaveHeldData = params.enclaveHeldData; this._sgxCollateral = params.sgxCollateral; } private _issuer: string; private _version: string; private _nonce?: string; private _uniqueId: string; private _runTimeClaims?: unknown; private _initTimeClaims?: unknown; private _policyClaims?: unknown; private _verifierType: string; private _policySigner?: AttestationSigner; private _policyHash: Uint8Array; private _isDebuggable?: boolean; private _productId?: number; private _mrEnclave?: string; private _mrSigner?: string; private _svn?: number; private _enclaveHeldData?: Uint8Array; private _sgxCollateral?: AttestationSgxCollateralInfo; /** * Unique Identifier for the token * */ get uniqueId(): string { return this._uniqueId; } /** * Returns the issuer of the attestation token. MUST be the same as the * endpoint used when constructing the attestation client instance. */ get issuer(): string { return this._issuer; } /** * Returns the "nonce" value specified in the Attest request. */ get nonce(): string | undefined { return this._nonce; } /** * The Schema version of this structure. Current Value: 1.0 */ get version(): string { return this._version; } /** * Runtime Claims */ get runTimeClaims(): unknown { return this._runTimeClaims; } /** * Inittime Claims */ get initTimeClaims(): unknown { return this._initTimeClaims; } /** * Policy Generated Claims */ get policyClaims(): unknown { return this._policyClaims; } /** * The Attestation type being attested. */ get verifierType(): string { return this._verifierType; } /** * The certificate used to sign the policy object, if specified. */ get policySigner(): AttestationSigner | undefined { return this._policySigner; } /** * The SHA256 hash of the BASE64URL encoded policy text used for attestation */ get policyHash(): Uint8Array { return this._policyHash; } /** * True if the enclave is debuggable, false otherwise */ get isDebuggable(): boolean | undefined { return this._isDebuggable; } /** * The SGX Product ID for the enclave. */ get productId(): number | undefined { return this._productId; } /** * The HEX encoded SGX MRENCLAVE value for the enclave. */ get mrEnclave(): string | undefined { return this._mrEnclave; } /** * The HEX encoded SGX MRSIGNER value for the enclave. */ get mrSigner(): string | undefined { return this._mrSigner; } /** * The SGX SVN value for the enclave. */ get svn(): number | undefined { return this._svn; } /** * A copy of the RuntimeData specified as an input to the attest call. */ get enclaveHeldData(): Uint8Array | undefined { return this._enclaveHeldData; } /** * The SGX SVN value for the enclave. */ get sgxCollateral(): AttestationSgxCollateralInfo | undefined { return this._sgxCollateral; } } /** * * @param generated - Generated attestation result object. * @returns newly created AttestationResult from the generated result. * * @internal */ export function _attestationResultFromGenerated( generated: GeneratedAttestationResult ): AttestationResultImpl { return new AttestationResultImpl({ issuer: generated.iss, version: generated.version, nonce: generated.nonce, uniqueId: generated.jti, policySigner: generated.policySigner ? _attestationSignerFromGenerated(generated.policySigner) : undefined, runTimeClaims: generated.runtimeClaims, initTimeClaims: generated.inittimeClaims, policyClaims: generated.policyClaims, verifierType: generated.verifierType, policyHash: generated.policyHash, isDebuggable: generated.isDebuggable, productId: generated.productId, mrEnclave: generated.mrEnclave, mrSigner: generated.mrSigner, svn: generated.svn, enclaveHeldData: generated.enclaveHeldData, sgxCollateral: generated.sgxCollateral, }); }
the_stack
import { ConcreteRequest } from "relay-runtime"; import { FragmentRefs } from "relay-runtime"; export type FairTestsQueryVariables = {}; export type FairTestsQueryResponse = { readonly fair: { readonly " $fragmentRefs": FragmentRefs<"Fair_fair">; } | null; }; export type FairTestsQueryRawResponse = { readonly fair: ({ readonly id: string; readonly slug: string; readonly name: string | null; readonly formattedOpeningHours: string | null; readonly startAt: string | null; readonly endAt: string | null; readonly exhibitionPeriod: string | null; readonly counts: ({ readonly artists: number | null; }) | null; readonly image: ({ readonly url: string | null; }) | null; readonly followedContent: ({ readonly artists: ReadonlyArray<({ readonly name: string | null; readonly href: string | null; readonly slug: string; readonly internalID: string; readonly id: string | null; }) | null> | null; }) | null; readonly artistsConnection: ({ readonly edges: ReadonlyArray<({ readonly node: ({ readonly name: string | null; readonly href: string | null; readonly slug: string; readonly internalID: string; readonly id: string | null; }) | null; }) | null> | null; }) | null; readonly profile: ({ readonly id: string; readonly icon: ({ readonly url: string | null; }) | null; readonly name: string | null; }) | null; readonly internalID: string; readonly hours: string | null; readonly isActive: boolean | null; readonly location: ({ readonly id: string; readonly internalID: string; readonly city: string | null; readonly address: string | null; readonly address_2: string | null; readonly postal_code: string | null; readonly summary: string | null; readonly coordinates: ({ readonly lat: number | null; readonly lng: number | null; }) | null; readonly day_schedules: ReadonlyArray<({ readonly start_time: number | null; readonly end_time: number | null; readonly day_of_week: string | null; }) | null> | null; readonly openingHours: ({ readonly __typename: "OpeningHoursArray"; readonly schedules: ReadonlyArray<({ readonly days: string | null; readonly hours: string | null; }) | null> | null; } | { readonly __typename: "OpeningHoursText"; readonly text: string | null; } | { readonly __typename: string | null; }) | null; }) | null; readonly organizer: ({ readonly website: string | null; readonly id: string | null; }) | null; readonly sponsoredContent: ({ readonly pressReleaseUrl: string | null; readonly activationText: string | null; }) | null; readonly shows: ({ readonly pageInfo: { readonly hasNextPage: boolean; readonly startCursor: string | null; readonly endCursor: string | null; }; readonly edges: ReadonlyArray<({ readonly cursor: string; readonly node: ({ readonly artworks: ({ readonly edges: ReadonlyArray<({ readonly node: ({ readonly slug: string; readonly id: string | null; readonly image: ({ readonly aspect_ratio: number; readonly url: string | null; }) | null; readonly title: string | null; readonly date: string | null; readonly sale_message: string | null; readonly is_biddable: boolean | null; readonly is_acquireable: boolean | null; readonly is_offerable: boolean | null; readonly sale: ({ readonly is_auction: boolean | null; readonly is_closed: boolean | null; readonly display_timely_at: string | null; readonly id: string | null; }) | null; readonly sale_artwork: ({ readonly current_bid: ({ readonly display: string | null; }) | null; readonly id: string | null; }) | null; readonly artists: ReadonlyArray<({ readonly name: string | null; readonly id: string | null; }) | null> | null; readonly partner: ({ readonly name: string | null; readonly id: string | null; }) | null; readonly href: string | null; }) | null; }) | null> | null; }) | null; readonly slug: string; readonly internalID: string; readonly counts: ({ readonly artworks: number | null; }) | null; readonly partner: ({ readonly __typename: "Partner"; readonly id: string | null; readonly name: string | null; readonly href: string | null; readonly slug: string; readonly internalID: string; readonly profile: ({ readonly id: string; readonly slug: string; readonly internalID: string; readonly isFollowed: boolean | null; }) | null; } | { readonly __typename: string | null; readonly id: string | null; }) | null; readonly coverImage: ({ readonly url: string | null; }) | null; readonly location: ({ readonly display: string | null; readonly id: string | null; }) | null; readonly id: string | null; readonly __typename: "Show"; }) | null; }) | null> | null; }) | null; }) | null; }; export type FairTestsQuery = { readonly response: FairTestsQueryResponse; readonly variables: FairTestsQueryVariables; readonly rawResponse: FairTestsQueryRawResponse; }; /* query FairTestsQuery { fair(id: "sofa-chicago-2018") { ...Fair_fair id } } fragment Fair_fair on Fair { id ...FairDetail_fair } fragment FairDetail_fair on Fair { ...FairHeader_fair slug internalID name hours isActive location { ...LocationMap_location coordinates { lat lng } id } organizer { website id } profile { name id } sponsoredContent { pressReleaseUrl activationText } shows: showsConnection(first: 5) { pageInfo { hasNextPage startCursor endCursor } edges { cursor node { artworks: artworksConnection(first: 4) { edges { node { slug id } } } ...FairBoothPreview_show id __typename } } } } fragment FairHeader_fair on Fair { slug name formattedOpeningHours startAt endAt exhibitionPeriod counts { artists } image { url } followedContent { artists { name href slug internalID id } } artistsConnection(first: 3) { edges { node { name href slug internalID id } } } profile { id icon { url(version: "square140") } } } fragment LocationMap_location on Location { id internalID city address address_2: address2 postal_code: postalCode summary coordinates { lat lng } day_schedules: daySchedules { start_time: startTime end_time: endTime day_of_week: dayOfWeek } openingHours { __typename ... on OpeningHoursArray { schedules { days hours } } ... on OpeningHoursText { text } } } fragment FairBoothPreview_show on Show { slug internalID counts { artworks } partner { __typename ... on Partner { name href slug internalID id profile { id slug internalID isFollowed } } ... on Node { id } ... on ExternalPartner { id } } coverImage { url } location { display id } artworks: artworksConnection(first: 4) { edges { node { ...GenericGrid_artworks id } } } } fragment GenericGrid_artworks on Artwork { id image { aspect_ratio: aspectRatio } ...ArtworkGridItem_artwork } fragment ArtworkGridItem_artwork on Artwork { title date sale_message: saleMessage is_biddable: isBiddable is_acquireable: isAcquireable is_offerable: isOfferable slug sale { is_auction: isAuction is_closed: isClosed display_timely_at: displayTimelyAt id } sale_artwork: saleArtwork { current_bid: currentBid { display } id } image { url(version: "large") aspect_ratio: aspectRatio } artists(shallow: true) { name id } partner { name id } href } */ const node: ConcreteRequest = (function(){ var v0 = [ { "kind": "Literal", "name": "id", "value": "sofa-chicago-2018" } ], v1 = { "kind": "ScalarField", "alias": null, "name": "id", "args": null, "storageKey": null }, v2 = { "kind": "ScalarField", "alias": null, "name": "slug", "args": null, "storageKey": null }, v3 = { "kind": "ScalarField", "alias": null, "name": "name", "args": null, "storageKey": null }, v4 = [ { "kind": "ScalarField", "alias": null, "name": "url", "args": null, "storageKey": null } ], v5 = { "kind": "ScalarField", "alias": null, "name": "href", "args": null, "storageKey": null }, v6 = { "kind": "ScalarField", "alias": null, "name": "internalID", "args": null, "storageKey": null }, v7 = [ (v3/*: any*/), (v5/*: any*/), (v2/*: any*/), (v6/*: any*/), (v1/*: any*/) ], v8 = { "kind": "ScalarField", "alias": null, "name": "hours", "args": null, "storageKey": null }, v9 = { "kind": "ScalarField", "alias": null, "name": "__typename", "args": null, "storageKey": null }, v10 = [ { "kind": "Literal", "name": "first", "value": 5 } ], v11 = { "kind": "ScalarField", "alias": null, "name": "display", "args": null, "storageKey": null }, v12 = [ (v3/*: any*/), (v1/*: any*/) ]; return { "kind": "Request", "fragment": { "kind": "Fragment", "name": "FairTestsQuery", "type": "Query", "metadata": null, "argumentDefinitions": [], "selections": [ { "kind": "LinkedField", "alias": null, "name": "fair", "storageKey": "fair(id:\"sofa-chicago-2018\")", "args": (v0/*: any*/), "concreteType": "Fair", "plural": false, "selections": [ { "kind": "FragmentSpread", "name": "Fair_fair", "args": null } ] } ] }, "operation": { "kind": "Operation", "name": "FairTestsQuery", "argumentDefinitions": [], "selections": [ { "kind": "LinkedField", "alias": null, "name": "fair", "storageKey": "fair(id:\"sofa-chicago-2018\")", "args": (v0/*: any*/), "concreteType": "Fair", "plural": false, "selections": [ (v1/*: any*/), (v2/*: any*/), (v3/*: any*/), { "kind": "ScalarField", "alias": null, "name": "formattedOpeningHours", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "startAt", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "endAt", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "exhibitionPeriod", "args": null, "storageKey": null }, { "kind": "LinkedField", "alias": null, "name": "counts", "storageKey": null, "args": null, "concreteType": "FairCounts", "plural": false, "selections": [ { "kind": "ScalarField", "alias": null, "name": "artists", "args": null, "storageKey": null } ] }, { "kind": "LinkedField", "alias": null, "name": "image", "storageKey": null, "args": null, "concreteType": "Image", "plural": false, "selections": (v4/*: any*/) }, { "kind": "LinkedField", "alias": null, "name": "followedContent", "storageKey": null, "args": null, "concreteType": "FollowedContent", "plural": false, "selections": [ { "kind": "LinkedField", "alias": null, "name": "artists", "storageKey": null, "args": null, "concreteType": "Artist", "plural": true, "selections": (v7/*: any*/) } ] }, { "kind": "LinkedField", "alias": null, "name": "artistsConnection", "storageKey": "artistsConnection(first:3)", "args": [ { "kind": "Literal", "name": "first", "value": 3 } ], "concreteType": "ArtistConnection", "plural": false, "selections": [ { "kind": "LinkedField", "alias": null, "name": "edges", "storageKey": null, "args": null, "concreteType": "ArtistEdge", "plural": true, "selections": [ { "kind": "LinkedField", "alias": null, "name": "node", "storageKey": null, "args": null, "concreteType": "Artist", "plural": false, "selections": (v7/*: any*/) } ] } ] }, { "kind": "LinkedField", "alias": null, "name": "profile", "storageKey": null, "args": null, "concreteType": "Profile", "plural": false, "selections": [ (v1/*: any*/), { "kind": "LinkedField", "alias": null, "name": "icon", "storageKey": null, "args": null, "concreteType": "Image", "plural": false, "selections": [ { "kind": "ScalarField", "alias": null, "name": "url", "args": [ { "kind": "Literal", "name": "version", "value": "square140" } ], "storageKey": "url(version:\"square140\")" } ] }, (v3/*: any*/) ] }, (v6/*: any*/), (v8/*: any*/), { "kind": "ScalarField", "alias": null, "name": "isActive", "args": null, "storageKey": null }, { "kind": "LinkedField", "alias": null, "name": "location", "storageKey": null, "args": null, "concreteType": "Location", "plural": false, "selections": [ (v1/*: any*/), (v6/*: any*/), { "kind": "ScalarField", "alias": null, "name": "city", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "address", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": "address_2", "name": "address2", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": "postal_code", "name": "postalCode", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "summary", "args": null, "storageKey": null }, { "kind": "LinkedField", "alias": null, "name": "coordinates", "storageKey": null, "args": null, "concreteType": "LatLng", "plural": false, "selections": [ { "kind": "ScalarField", "alias": null, "name": "lat", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "lng", "args": null, "storageKey": null } ] }, { "kind": "LinkedField", "alias": "day_schedules", "name": "daySchedules", "storageKey": null, "args": null, "concreteType": "DaySchedule", "plural": true, "selections": [ { "kind": "ScalarField", "alias": "start_time", "name": "startTime", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": "end_time", "name": "endTime", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": "day_of_week", "name": "dayOfWeek", "args": null, "storageKey": null } ] }, { "kind": "LinkedField", "alias": null, "name": "openingHours", "storageKey": null, "args": null, "concreteType": null, "plural": false, "selections": [ (v9/*: any*/), { "kind": "InlineFragment", "type": "OpeningHoursArray", "selections": [ { "kind": "LinkedField", "alias": null, "name": "schedules", "storageKey": null, "args": null, "concreteType": "FormattedDaySchedules", "plural": true, "selections": [ { "kind": "ScalarField", "alias": null, "name": "days", "args": null, "storageKey": null }, (v8/*: any*/) ] } ] }, { "kind": "InlineFragment", "type": "OpeningHoursText", "selections": [ { "kind": "ScalarField", "alias": null, "name": "text", "args": null, "storageKey": null } ] } ] } ] }, { "kind": "LinkedField", "alias": null, "name": "organizer", "storageKey": null, "args": null, "concreteType": "organizer", "plural": false, "selections": [ { "kind": "ScalarField", "alias": null, "name": "website", "args": null, "storageKey": null }, (v1/*: any*/) ] }, { "kind": "LinkedField", "alias": null, "name": "sponsoredContent", "storageKey": null, "args": null, "concreteType": "FairSponsoredContent", "plural": false, "selections": [ { "kind": "ScalarField", "alias": null, "name": "pressReleaseUrl", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "activationText", "args": null, "storageKey": null } ] }, { "kind": "LinkedField", "alias": "shows", "name": "showsConnection", "storageKey": "showsConnection(first:5)", "args": (v10/*: any*/), "concreteType": "ShowConnection", "plural": false, "selections": [ { "kind": "LinkedField", "alias": null, "name": "pageInfo", "storageKey": null, "args": null, "concreteType": "PageInfo", "plural": false, "selections": [ { "kind": "ScalarField", "alias": null, "name": "hasNextPage", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "startCursor", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "endCursor", "args": null, "storageKey": null } ] }, { "kind": "LinkedField", "alias": null, "name": "edges", "storageKey": null, "args": null, "concreteType": "ShowEdge", "plural": true, "selections": [ { "kind": "ScalarField", "alias": null, "name": "cursor", "args": null, "storageKey": null }, { "kind": "LinkedField", "alias": null, "name": "node", "storageKey": null, "args": null, "concreteType": "Show", "plural": false, "selections": [ { "kind": "LinkedField", "alias": "artworks", "name": "artworksConnection", "storageKey": "artworksConnection(first:4)", "args": [ { "kind": "Literal", "name": "first", "value": 4 } ], "concreteType": "ArtworkConnection", "plural": false, "selections": [ { "kind": "LinkedField", "alias": null, "name": "edges", "storageKey": null, "args": null, "concreteType": "ArtworkEdge", "plural": true, "selections": [ { "kind": "LinkedField", "alias": null, "name": "node", "storageKey": null, "args": null, "concreteType": "Artwork", "plural": false, "selections": [ (v2/*: any*/), (v1/*: any*/), { "kind": "LinkedField", "alias": null, "name": "image", "storageKey": null, "args": null, "concreteType": "Image", "plural": false, "selections": [ { "kind": "ScalarField", "alias": "aspect_ratio", "name": "aspectRatio", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "url", "args": [ { "kind": "Literal", "name": "version", "value": "large" } ], "storageKey": "url(version:\"large\")" } ] }, { "kind": "ScalarField", "alias": null, "name": "title", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "date", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": "sale_message", "name": "saleMessage", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": "is_biddable", "name": "isBiddable", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": "is_acquireable", "name": "isAcquireable", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": "is_offerable", "name": "isOfferable", "args": null, "storageKey": null }, { "kind": "LinkedField", "alias": null, "name": "sale", "storageKey": null, "args": null, "concreteType": "Sale", "plural": false, "selections": [ { "kind": "ScalarField", "alias": "is_auction", "name": "isAuction", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": "is_closed", "name": "isClosed", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": "display_timely_at", "name": "displayTimelyAt", "args": null, "storageKey": null }, (v1/*: any*/) ] }, { "kind": "LinkedField", "alias": "sale_artwork", "name": "saleArtwork", "storageKey": null, "args": null, "concreteType": "SaleArtwork", "plural": false, "selections": [ { "kind": "LinkedField", "alias": "current_bid", "name": "currentBid", "storageKey": null, "args": null, "concreteType": "SaleArtworkCurrentBid", "plural": false, "selections": [ (v11/*: any*/) ] }, (v1/*: any*/) ] }, { "kind": "LinkedField", "alias": null, "name": "artists", "storageKey": "artists(shallow:true)", "args": [ { "kind": "Literal", "name": "shallow", "value": true } ], "concreteType": "Artist", "plural": true, "selections": (v12/*: any*/) }, { "kind": "LinkedField", "alias": null, "name": "partner", "storageKey": null, "args": null, "concreteType": "Partner", "plural": false, "selections": (v12/*: any*/) }, (v5/*: any*/) ] } ] } ] }, (v2/*: any*/), (v6/*: any*/), { "kind": "LinkedField", "alias": null, "name": "counts", "storageKey": null, "args": null, "concreteType": "ShowCounts", "plural": false, "selections": [ { "kind": "ScalarField", "alias": null, "name": "artworks", "args": null, "storageKey": null } ] }, { "kind": "LinkedField", "alias": null, "name": "partner", "storageKey": null, "args": null, "concreteType": null, "plural": false, "selections": [ (v9/*: any*/), (v1/*: any*/), { "kind": "InlineFragment", "type": "Partner", "selections": [ (v3/*: any*/), (v5/*: any*/), (v2/*: any*/), (v6/*: any*/), { "kind": "LinkedField", "alias": null, "name": "profile", "storageKey": null, "args": null, "concreteType": "Profile", "plural": false, "selections": [ (v1/*: any*/), (v2/*: any*/), (v6/*: any*/), { "kind": "ScalarField", "alias": null, "name": "isFollowed", "args": null, "storageKey": null } ] } ] } ] }, { "kind": "LinkedField", "alias": null, "name": "coverImage", "storageKey": null, "args": null, "concreteType": "Image", "plural": false, "selections": (v4/*: any*/) }, { "kind": "LinkedField", "alias": null, "name": "location", "storageKey": null, "args": null, "concreteType": "Location", "plural": false, "selections": [ (v11/*: any*/), (v1/*: any*/) ] }, (v1/*: any*/), (v9/*: any*/) ] } ] } ] }, { "kind": "LinkedHandle", "alias": "shows", "name": "showsConnection", "args": (v10/*: any*/), "handle": "connection", "key": "Fair_shows", "filters": null } ] } ] }, "params": { "operationKind": "query", "name": "FairTestsQuery", "id": "ccccb6105858e650bbb2199609fad828", "text": null, "metadata": {} } }; })(); (node as any).hash = '830dfb36fc561a9890e4fb7733c19f2c'; export default node;
the_stack
import React, { useState } from 'react'; import classNames from 'classnames'; import { InputRowContext } from '../InputRow/index'; import styles from './index.module.scss'; type UiState = 'disabled' | 'readonly' | 'error' | 'default'; type ContextValue = { hasValue: boolean; size?: 'large' | 'small'; position: 'left' | 'right'; }; const Context = React.createContext<ContextValue>({ hasValue: false, size: undefined, position: 'left', }); /** * Prioritize the mutually exclusive UI states the user may end up in. */ const getUIState = ({ isDisabled, isReadOnly, hasError, }: Pick<TextInputPropTypes, 'isDisabled' | 'isReadOnly' | 'hasError'>): UiState => { if (isDisabled) { return 'disabled'; } if (isReadOnly) { return 'readonly'; } if (hasError) { return 'error'; } return 'default'; }; interface InputIconContainerPropTypes { children: React.ReactNode; style?: { color: string }; } /** * This component is not exported. It wraps the `InputClearButton` and `InputIcon`, applying * classes to position the icon. It does this by using `create-react-context`, a ponyfill for * React’s context functionality. This makes it easier for consumers to use `InputClearButton` and * `InputIcon` because they won’t have to specify as many props. */ const TextInputIconContainer = ({ children, style }: InputIconContainerPropTypes): JSX.Element => ( <Context.Consumer> {(theme): JSX.Element => { const position = theme && theme.position; const size = theme && theme.size; return ( <div className={classNames({ [styles.inputIconContainer]: true, // Applies when used on left [styles.inputIconContainerPositionLeft]: position === 'left', [styles.inputIconContainerPositionLeftSizeSmall]: position === 'left' && size === 'small', [styles.inputIconContainerPositionLeftSizeLarge]: position === 'left' && size === 'large', // Applies when used on right [styles.inputIconContainerPositionRight]: position === 'right', [styles.inputIconContainerPositionRightSizeSmall]: position === 'right' && size === 'small', [styles.inputIconContainerPositionRightSizeLarge]: position === 'right' && size === 'large', })} style={style} > {children} </div> ); }} </Context.Consumer> ); interface TextInputClearButtonPropTypes { onClick: () => void; } /** * Accessible button that makes it easy to add a "Clear" button to a text input. It should be used * with the `innerRight` prop in `Input`. */ const TextInputClearButton = ({ onClick }: TextInputClearButtonPropTypes): JSX.Element => ( <TextInputIconContainer> <Context.Consumer> {(theme): JSX.Element => ( <div className={classNames({ displayNone: theme && !theme.hasValue, })} > <button className={styles.unstyledButton} aria-label="Clear input" onClick={onClick} type="button" > <svg viewBox="0 0 24 24" width="18" height="18" stroke="currentColor" strokeWidth="3" fill="none" strokeLinecap="round" strokeLinejoin="round" className={styles.closeButtonIcon} > <line x1="18" y1="6" x2="6" y2="18" /> <line x1="6" y1="6" x2="18" y2="18" /> </svg> </button> </div> )} </Context.Consumer> </TextInputIconContainer> ); interface TextInputIconPropTypes { /** * Set the icon color with a color from [Thumbprint Tokens](/tokens/). */ color?: string; /** * An icon component from [Thumbprint Icons](/icons/). * You should pair "Medium" icons with `large` inputs and "Small" icons with `small` inputs. */ children: React.ReactNode; } /** * Component that helps position icons within inputs. */ const TextInputIcon = ({ color = 'inherit', children }: TextInputIconPropTypes): JSX.Element => ( <TextInputIconContainer style={{ color }}>{children}</TextInputIconContainer> ); interface TextInputPropTypes { /** * Adds a HTML `id` attribute to the input. This is used for linking the HTML with a * [Label](/components/label/react/). */ id?: string; /** * Visually and functionally disable the input. */ isDisabled?: boolean; /** * Adds `readonly` HTML attribute, allowing users to select (but not modify) the input. */ isReadOnly?: boolean; /** * Adds the `required` HTML attribute. */ isRequired?: boolean; /** * A regular expression that the `<input>` element's value is checked against when submitting a * form. */ pattern?: string; /** * The maximum number of characters that a user can enter. `onChange` will not fire if a user * enters a character that exceeds `maxLength`. */ maxLength?: number; /** * Makes the text and border color red. */ hasError?: boolean; /** * Text that appears within the input when there is no `value`. */ placeholder?: string; /** * Controls the height and padding of the input. */ size?: 'small' | 'large'; /** * Sets the `type` attribute on the input element. */ type?: 'email' | 'password' | 'text' | 'search' | 'tel' | 'number'; /** * A [proposed specification](https://html.spec.whatwg.org/multipage/interaction.html#input-modalities:-the-inputmode-attribute) * that enables specification of virtual keyboard type in Chrome. Currently only supported in * Chrome and Android. */ inputMode?: 'numeric'; /** * The HTML `name` attribute that will be pased to the input. It is required if working with a * form that uses `<form action="" method="">` to submit data to a server. */ name?: string; /** * The current value of the input. */ value?: string | number; /** * Content that appears within the input on the left. */ innerLeft?: React.ReactNode; /** * Content that appears within the input on the right. */ innerRight?: React.ReactNode; /** * The function that is called when the input value changes. * * It receives two arguments: `onChange(newValue, event)`. * * The consumer of this component should use that data to update the `value` prop passed in to * this component. */ onChange: (value: string, event: React.ChangeEvent<HTMLInputElement>) => void; /** * Function that fires when you click into the input. */ onClick?: (event: React.MouseEvent<HTMLInputElement, MouseEvent>) => void; /** * Fires when the input gains focus. */ onFocus?: (event: React.FocusEvent<HTMLInputElement>) => void; /** * Fires when the input loses focus, regardless of whether the value has changed. */ onBlur?: (event: React.FocusEvent<HTMLInputElement>) => void; /** * Fires when a key is pressed down with the input focused. */ onKeyDown?: (event: React.KeyboardEvent<HTMLInputElement>) => void; /** * Fires when a key press is released with the input focused. */ onKeyUp?: (event: React.KeyboardEvent<HTMLInputElement>) => void; /** * Fires when a valid key input is made. */ onKeyPress?: (event: React.KeyboardEvent<HTMLInputElement>) => void; /** * This tells the browser to give the input focus when the page is loaded. This can [only be * used once on a page](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-autofocus). */ shouldFocusOnPageLoad?: boolean; /** * A selector hook into the React component for use in automated testing environments. It is * applied internally to the `<input />` element. */ dataTest?: string; /** * This tells the browser whether to attempt autocompletion of the input. * [Supports all values](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete). */ autoComplete?: React.InputHTMLAttributes<HTMLInputElement>['autoComplete']; } const TextInput = React.forwardRef<HTMLInputElement, TextInputPropTypes>( ( { id, type = 'text', isDisabled = false, isReadOnly = false, isRequired = false, hasError = false, placeholder, size = 'large', name, value = '', innerLeft, innerRight, onClick = (): void => {}, onChange = (): void => {}, onFocus = (): void => {}, onBlur = (): void => {}, onKeyDown = (): void => {}, onKeyUp = (): void => {}, onKeyPress = (): void => {}, shouldFocusOnPageLoad = false, dataTest, inputMode, pattern, maxLength, autoComplete, }: TextInputPropTypes, outerRef, ): JSX.Element => { const uiState = getUIState({ isDisabled, isReadOnly, hasError }); // The input element rendered by this component. We use `useState` instead of // `useRef` because callback refs allow us to add more than one `ref` to a DOM node. const [inputEl, setInputEl] = useState<HTMLInputElement | null>(null); const focusInput = (): void => { if (inputEl) { inputEl.focus(); } }; /* eslint-disable jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions */ return ( <div className={classNames({ [styles.root]: true, [styles.rootUiStateDefault]: uiState === 'default', [styles.rootUiStateReadonly]: uiState === 'readonly', [styles.rootUiStateDisabled]: uiState === 'disabled', [styles.rootUiStateError]: uiState === 'error', })} > {innerLeft && ( <Context.Provider value={{ hasValue: !!value, size, position: 'left', }} > <div className={styles.inputInnerElement} onClick={focusInput}> {innerLeft} </div> </Context.Provider> )} <input className={classNames({ [styles.input]: true, [styles.inputError]: uiState === 'error', [styles.inputSizeSmall]: size === 'small', [styles.inputSizeLarge]: size === 'large', [styles.inputInnerLeft]: innerLeft, [styles.inputInnerRight]: innerRight, })} disabled={isDisabled} readOnly={isReadOnly} required={isRequired} placeholder={placeholder} // eslint-disable-next-line jsx-a11y/no-autofocus autoFocus={shouldFocusOnPageLoad} name={name} type={type} value={value} onChange={(e): void => onChange(e.target.value, e)} onClick={(e): void => onClick(e)} onFocus={(e): void => onFocus(e)} onBlur={(e): void => onBlur(e)} onKeyDown={(e): void => onKeyDown(e)} onKeyUp={(e): void => onKeyUp(e)} onKeyPress={(e): void => onKeyPress(e)} id={id} ref={(el): void => { setInputEl(el); // `outerRef` is the potential forwarded `ref` passed in from a consumer. // Not all refs are callable functions, so only try and call it if it is. if (typeof outerRef === 'function') { outerRef(el); } }} data-test={dataTest} inputMode={inputMode} pattern={pattern} maxLength={maxLength} autoComplete={autoComplete} /> {innerRight && ( <Context.Provider value={{ hasValue: !!value, size, position: 'right', }} > <div className={styles.inputInnerElement} onClick={focusInput}> {innerRight} </div> </Context.Provider> )} <InputRowContext.Consumer> {({ isWithinInputRow, isFirstInputRowChild, isLastInputRowChild, }): JSX.Element => ( <div className={classNames({ [styles.inputStyles]: true, [styles.inputStylesRoundedBordersLeft]: isFirstInputRowChild || !isWithinInputRow, [styles.inputStylesRoundedBordersRight]: isLastInputRowChild || !isWithinInputRow, [styles.inputStylesHasNoRightBorder]: isWithinInputRow && !isLastInputRowChild, [styles.inputStylesUiStateDefault]: uiState === 'default', [styles.inputStylesUiStateReadonly]: uiState === 'readonly', [styles.inputStylesUiStateDisabled]: uiState === 'disabled', [styles.inputStylesUiStateError]: uiState === 'error', })} /> )} </InputRowContext.Consumer> </div> ); }, ); TextInput.displayName = 'TextInput'; export default TextInput; export { TextInputIcon, TextInputClearButton };
the_stack
import React, { useEffect, useLayoutEffect, useState } from 'react'; import { fetchGetInitialProps, InitialProps, makeLayout } from './layout'; import { act, create, ReactTestRenderer } from 'react-test-renderer'; import { LayoutRenderer } from './LayoutRenderer'; import { ChildLayout, ChildLayoutProps, clientRenderer, EmptyLayout, ErrorComponent, LoadingComponent, mockPageContext, ParentLayout, ParentLayoutProps, sleep, } from './test-utils'; import useSWR from 'swr'; import { commonLayoutTests } from './layout.test.common'; import { wrapSwrInitialProps } from './utils'; describe('layout', () => { commonLayoutTests(clientRenderer); test('stays mounted', async () => { let parentMountedTimes = 0; let parentRenderedTimes = 0; const Parent = makeLayout(undefined, { component: function Component(props) { parentRenderedTimes++; useLayoutEffect(() => { parentMountedTimes++; }, []); return <>{props.children}</>; }, useParentProps: (props) => ({}), }); const Child1 = makeLayout(undefined, { component: EmptyLayout, parent: Parent, useParentProps: (props) => ({}), }); const Child2 = makeLayout(undefined, { component: EmptyLayout, parent: Parent, useParentProps: (props) => ({}), }); const parent = create( <LayoutRenderer layout={Child1} layoutProps={{}} initialProps={await fetchGetInitialProps(Child1, mockPageContext)} errorComponent={ErrorComponent} > content </LayoutRenderer> ); expect(parentMountedTimes).toBe(1); expect(parentRenderedTimes).toBe(1); parent.update( <LayoutRenderer layout={Child2} layoutProps={{}} initialProps={await fetchGetInitialProps(Child1, mockPageContext)} errorComponent={ErrorComponent} > content </LayoutRenderer> ); expect(parentMountedTimes).toBe(1); expect(parentRenderedTimes).toBe(2); }); test('with different useParentProps hooks', async () => { const Parent = makeLayout(undefined, { component: EmptyLayout, useParentProps: (props) => ({}), }); // Using hook in useParentProps. const Child1 = makeLayout(undefined, { component: EmptyLayout, parent: Parent, useParentProps: (props) => { useState(false); return {}; }, }); // No hooks. const Child2 = makeLayout(undefined, { component: EmptyLayout, parent: Parent, useParentProps: (props) => ({}), }); const parent = create( <LayoutRenderer layout={Child1} layoutProps={{}} initialProps={await fetchGetInitialProps(Child1, mockPageContext)} errorComponent={ErrorComponent} > content </LayoutRenderer> ); parent.update( <LayoutRenderer layout={Child2} layoutProps={{}} initialProps={await fetchGetInitialProps(Child1, mockPageContext)} errorComponent={ErrorComponent} > content </LayoutRenderer> ); parent.update( <LayoutRenderer layout={Child1} layoutProps={{}} initialProps={await fetchGetInitialProps(Child1, mockPageContext)} errorComponent={ErrorComponent} > content </LayoutRenderer> ); }); test('with useInitialProps', async () => { const Parent = makeLayout( { useInitialProps: () => { return wrapSwrInitialProps( useSWR('layoutWithUseInitialProps:parent', async () => { await sleep(100); return { one: 'initialOne' }; }) ); }, }, { component: ParentLayout, useParentProps: (props) => ({}), } ); let renderer: ReactTestRenderer = null as any; void act(() => { renderer = create( <LayoutRenderer layout={Parent} layoutProps={{ two: 2 }} initialProps={undefined} errorComponent={ErrorComponent} loadingComponent={LoadingComponent} > content </LayoutRenderer> ); }); expect(renderer.toJSON()).toEqual('loading'); await act(async () => { jest.runAllTimers(); }); expect(renderer.toJSON()).toEqual(['initialOne', '2', 'content']); // Navigate to Child1. const Child1 = makeLayout( { useInitialProps: () => { return wrapSwrInitialProps( useSWR('layoutWithUseInitialProps:child1', async () => { await sleep(100); return { three: 'child1', four: 4 }; }) ); }, }, { component: ChildLayout, parent: Parent, useParentProps: (props) => ({ two: 22, }), } ); void act(() => { renderer.update( <LayoutRenderer layout={Child1} layoutProps={{}} initialProps={undefined} errorComponent={ErrorComponent} loadingComponent={LoadingComponent} > content </LayoutRenderer> ); }); expect(renderer.toJSON()).toEqual(['initialOne', '22', 'loading']); await act(async () => { jest.runAllTimers(); }); expect(renderer.toJSON()).toEqual([ 'initialOne', '22', 'child1', '4', 'content', ]); // Navigate to Child2. const Child2 = makeLayout( { useInitialProps: () => { return wrapSwrInitialProps( useSWR('layoutWithUseInitialProps:child2', async () => { await sleep(100); return { three: 'child2', four: 44 }; }) ); }, }, { component: ChildLayout, parent: Parent, useParentProps: (props) => ({ two: 2222, }), } ); void act(() => { renderer.update( <LayoutRenderer layout={Child2} layoutProps={{}} initialProps={undefined} errorComponent={ErrorComponent} loadingComponent={LoadingComponent} > content </LayoutRenderer> ); }); expect(renderer.toJSON()).toEqual(['initialOne', '2222', 'loading']); await act(async () => { jest.runAllTimers(); }); expect(renderer.toJSON()).toEqual([ 'initialOne', '2222', 'child2', '44', 'content', ]); // Navigate back to Child1, no loading state expected. void act(() => { renderer.update( <LayoutRenderer layout={Child1} layoutProps={{}} initialProps={undefined} errorComponent={ErrorComponent} loadingComponent={LoadingComponent} > content </LayoutRenderer> ); }); expect(renderer.toJSON()).toEqual([ 'initialOne', '22', 'child1', '4', 'content', ]); // And finally, navigate back to Parent. void act(() => { renderer = create( <LayoutRenderer layout={Parent} layoutProps={{ two: 2 }} initialProps={undefined} errorComponent={ErrorComponent} loadingComponent={LoadingComponent} > content </LayoutRenderer> ); }); expect(renderer.toJSON()).toEqual(['initialOne', '2', 'content']); }); test('with getInitialProps and useInitialProps', async () => { const Parent = makeLayout( { getInitialProps: async () => ({ one: 'initialOne', two: 2, }), }, { component: ParentLayout, useParentProps: (props) => ({}), } ); const Child1 = makeLayout( { useInitialProps: () => { return wrapSwrInitialProps( useSWR( 'layoutWithGetInitialPropsAndUseInitialProps:child1', async () => { await sleep(100); return { three: 'child', four: 4 }; } ) ); }, }, { component: ChildLayout, parent: Parent, useParentProps: (props) => ({ two: 22, }), } ); let renderer: ReactTestRenderer = null as any; await act(async () => { renderer = create( <LayoutRenderer layout={Child1} layoutProps={{}} initialProps={await fetchGetInitialProps(Child1, mockPageContext)} errorComponent={ErrorComponent} loadingComponent={LoadingComponent} > content </LayoutRenderer> ); }); expect(renderer.toJSON()).toEqual(['initialOne', '22', 'loading']); await act(async () => { jest.runAllTimers(); }); expect(renderer.toJSON()).toEqual([ 'initialOne', '22', 'child', '4', 'content', ]); }); // useSWR data prop is undefined while loading, while useQuery in Apollo Client returns an empty object {}. Imitate both. const testUseInitialPropsAsParentProps = async (imitateApollo: boolean) => { const Parent = makeLayout(undefined, { component: ParentLayout, useParentProps: (props) => ({}), }); const Child = makeLayout(undefined, { component: (props: ChildLayoutProps) => { expect(props.three).toBeDefined(); expect(props.four).toBeDefined(); return <ChildLayout {...props} />; }, parent: Parent, useParentProps: (props) => ({ one: 'one', two: 2 }), }); const GrandChild = makeLayout( { useInitialProps: () => { const result = useSWR( `layoutWithUseInitialPropsAsUseParentProps:${ imitateApollo ? 'apollo' : 'swr' }`, async () => { await sleep(1000); return { three: 'initialThree', four: 4, }; } ); return { data: imitateApollo ? result.data ?? ({} as any) : result.data, loading: !result.data, }; }, }, { component: (props: ChildLayoutProps) => { return <>{props.children}</>; }, parent: Child, useParentProps: (props) => { return props.requireInitialProps((initialProps) => { return { three: initialProps.three, four: initialProps.four, }; }); }, } ); let renderer: ReactTestRenderer = null as any; void act(() => { renderer = create( <LayoutRenderer layout={GrandChild} layoutProps={{}} initialProps={undefined} errorComponent={ErrorComponent} loadingComponent={LoadingComponent} > content </LayoutRenderer> ); }); expect(renderer.toJSON()).toEqual(['one', '2', 'loading']); await act(async () => { jest.runAllTimers(); }); expect(renderer.toJSON()).toEqual([ 'one', '2', 'initialThree', '4', 'content', ]); }; test('with useInitialProps as useParentProps', async () => testUseInitialPropsAsParentProps(false)); test('with useInitialProps as useParentProps (Apollo Client like)', async () => testUseInitialPropsAsParentProps(true)); test('with useInitialProps and useParentProps error', async () => { const Parent = makeLayout( { getInitialProps: async () => ({ one: 'one', two: 2, }), }, { component: ParentLayout, useParentProps: (props) => ({}), } ); const Child = makeLayout(undefined, { component: ChildLayout, parent: Parent, useParentProps: (props) => ({}), }); const GrandChild = makeLayout( { useInitialProps: () => { return { data: undefined, error: new Error('error'), } as InitialProps<Omit<ChildLayoutProps, 'children'>>; }, }, { component: (props: ChildLayoutProps) => { return <>{props.children}</>; }, parent: Child, useParentProps: (props) => { return props.requireInitialProps((initialProps) => { return { three: initialProps.three, four: initialProps.four, }; }); }, } ); let renderer: ReactTestRenderer = null as any; await act(async () => { renderer = create( <LayoutRenderer layout={GrandChild} layoutProps={{}} initialProps={await fetchGetInitialProps(GrandChild, mockPageContext)} errorComponent={ErrorComponent} loadingComponent={LoadingComponent} > content </LayoutRenderer> ); }); expect(renderer.toJSON()).toEqual(['one', '2', 'error']); }); test("doesn't re-render loading state", async () => { let count = 0; const Parent = makeLayout( { useInitialProps: () => { const [data, setData] = useState<Omit<ParentLayoutProps, 'children'>>(); useEffect(() => { const fetchData = async () => { count++; await sleep(100); setData({ one: 'one', two: count }); await sleep(100); setData(undefined); void fetchData(); }; void fetchData(); }, []); return { data, loading: !data, }; }, }, { component: ParentLayout, useParentProps: (props) => ({}), } ); let renderer: ReactTestRenderer = null as any; void act(() => { renderer = create( <LayoutRenderer layout={Parent} layoutProps={{}} initialProps={undefined} errorComponent={ErrorComponent} loadingComponent={LoadingComponent} > content </LayoutRenderer> ); }); // Initially we are loading. expect(renderer.toJSON()).toEqual('loading'); // Run timers to get data. await act(async () => { jest.runAllTimers(); }); expect(renderer.toJSON()).toEqual(['one', '1', 'content']); // Start reload but still expect old data to be visible. await act(async () => { jest.runAllTimers(); }); expect(renderer.toJSON()).toEqual(['one', '1', 'content']); // Reload finished, expect new data. await act(async () => { jest.runAllTimers(); }); expect(renderer.toJSON()).toEqual(['one', '2', 'content']); }); });
the_stack
declare namespace dojox { namespace gantt { /** * Permalink: http://dojotoolkit.org/api/1.9/dojox/gantt/contextMenuTab.html * * * @param id * @param description * @param type * @param showOInfo * @param tabMenu * @param withDefaultValue */ class contextMenuTab { constructor(id: any, description: any, type: any, showOInfo: any, tabMenu: any, withDefaultValue: any); /** * * @param handler */ addAction(handler: any): void; /** * */ addChildTaskAction(): void; /** * * @param id * @param name * @param key * @param required */ addItem(id: any, name: any, key: any, required: any): void; /** * */ addProjectAction(): void; /** * */ addSuccessorTaskAction(): void; /** * */ addTaskAction(): void; /** * */ cpProjectAction(): void; /** * */ cpUpdateAction(): void; /** * * @param dateStr */ decodeDate(dateStr: any): any; /** * */ deleteAction(): void; /** * */ deleteProjectAction(): void; /** * */ durationUpdateAction(): void; /** * * @param date */ encodeDate(date: any): String; /** * */ hide(): void; /** * * @param content * @param name * @param value */ insertData(content: any, name: any, value: any): void; /** * */ ownerUpdateAction(): void; /** * * @param items */ preValueValidation(items: any): boolean; /** * */ ptUpdateAction(): void; /** * */ renameProjectAction(): void; /** * */ renameTaskAction(): void; /** * */ show(): void; } /** * Permalink: http://dojotoolkit.org/api/1.9/dojox/gantt/GanttProjectItem.html * * * @param configuration */ class GanttProjectItem extends dojox.gantt.GanttTaskItem { constructor(configuration: any); /** * * @param task */ addChildTask(task: any): void; /** * * @param task */ addTask(task: any): void; /** * * @param id */ deleteTask(id: any): void; /** * * @param id */ getTaskById(id: any): any; /** * * @param parentTask * @param id */ getTaskByIdInTree(parentTask: any, id: any): any; /** * * @param project */ setProject(project: any): void; } /** * Permalink: http://dojotoolkit.org/api/1.9/dojox/gantt/GanttResourceItem.html * * * @param ganttchart */ class GanttResourceItem { constructor(ganttchart: any); /** * */ buildOwnerTimeConsume(): Object; /** * */ buildResource(): Object; /** * * @param taskNameItem */ checkWidthTaskNameItem(taskNameItem: any): void; /** * */ clearAll(): void; /** * */ clearData(): void; /** * */ clearItems(): void; /** * */ create(): void; /** * * @param parentNode * @param currentNode */ createConnectingLinesPN(parentNode: any, currentNode: any): any[]; /** * * @param owner * @param parentNode * @param task */ createDetailedTaskEntry(owner: any, parentNode: any, task: any): any[]; /** * * @param owner */ createOwnerEntry(owner: any): Function; /** * * @param owner * @param posY */ createOwnerItem(owner: any, posY: any): any; /** * * @param owner * @param posY */ createOwnerNameItem(owner: any, posY: any): any; /** * */ createPanelNamesOwners(): any; /** * */ createPanelOwners(): any; /** * * @param task * @param posY */ createTaskItem(task: any, posY: any): any; /** * * @param owner * @param posY */ createTaskNameItem(owner: any, posY: any): any; /** * * @param ownerNameItem */ createTreeImg(ownerNameItem: any): any; /** * */ postAdjustment(): void; /** * */ reConstruct(): void; /** * */ refresh(): void; /** * * @param owner * @param item * @param task */ refreshDetailedTaskEntry(owner: any, item: any, task: any): void; /** * * @param owner */ refreshOwnerEntry(owner: any): void; /** * * @param owner */ refreshOwnerItem(owner: any): void; /** * * @param item * @param task */ refreshTaskItem(item: any, task: any): void; /** * * @param tItem * @param owner * @param displayType * @param topOffset */ styleOwnerItem(tItem: any, owner: any, displayType: any, topOffset: any): void; } /** * Permalink: http://dojotoolkit.org/api/1.9/dojox/gantt/GanttProjectControl.html * * * @param ganttChart * @param projectItem */ class GanttProjectControl { constructor(ganttChart: any, projectItem: any); /** * */ adjustPanelTime(): void; /** * */ checkWidthProjectNameItem(): void; /** * */ create(): void; /** * */ createDescrProject(): any; /** * */ createProjectItem(): any; /** * */ createProjectNameItem(): any; /** * * @param task */ deleteChildTask(task: any): void; /** * * @param id */ deleteTask(id: any): void; /** * */ getDescStr(): String; /** * */ getDuration(): number; /** * */ getPercentCompleted(): any; /** * * @param id */ getTaskById(id: any): any; /** * */ hideDescrProject(): void; /** * * @param id * @param name * @param startTime * @param duration * @param percentage * @param previousTaskId * @param taskOwner * @param parentTaskId */ insertTask(id: any, name: any, startTime: any, duration: any, percentage: any, previousTaskId: any, taskOwner: any, parentTaskId: any): any; /** * */ postLoadData(): void; /** * */ refresh(): Function; /** * * @param divDesc */ refreshDescrProject(divDesc: any): any; /** * * @param projectItem */ refreshProjectItem(projectItem: any): any; /** * * @param width */ resizeProjectItem(width: any): void; /** * * @param task * @param id */ searchTaskInTree(task: any, id: any): any; /** * * @param name */ setName(name: any): void; /** * * @param percentage */ setPercentCompleted(percentage: any): boolean; /** * * @param task * @param height */ shiftChildTasks(task: any, height: any): void; /** * */ shiftDescrProject(): void; /** * * @param task * @param height */ shiftNextParentTask(task: any, height: any): void; /** * * @param project * @param height */ shiftNextProject(project: any, height: any): void; /** * * @param height */ shiftProject(height: any): void; /** * */ shiftProjectItem(): void; /** * * @param task * @param height */ shiftTask(task: any, height: any): void; /** * */ showDescrProject(): void; } /** * Permalink: http://dojotoolkit.org/api/1.9/dojox/gantt/TabMenu.html * * * @param chart */ class TabMenu { constructor(chart: any); /** * * @param tab */ addItemMenuPanel(tab: any): void; /** * */ buildContent(): void; /** * */ clear(): void; /** * */ createMenuPanel(): void; /** * * @param id * @param desc * @param type * @param showOInfo * @param menu * @param withDefaultValue */ createTab(id: any, desc: any, type: any, showOInfo: any, menu: any, withDefaultValue: any): any; /** * */ createTabPanel(): void; /** * */ hide(): void; /** * * @param elem * @param object */ show(elem: any, object: any): void; } /** * Permalink: http://dojotoolkit.org/api/1.9/dojox/gantt/GanttTaskItem.html * * * @param configuration */ class GanttTaskItem { constructor(configuration: any); /** * * @param task */ addChildTask(task: any): void; /** * * @param project */ setProject(project: any): void; } /** * Permalink: http://dojotoolkit.org/api/1.9/dojox/gantt/GanttTaskControl.html * * * @param taskInfo * @param project * @param chart */ class GanttTaskControl { constructor(taskInfo: any, project: any, chart: any); /** * */ adjustPanelTime(): void; /** * * @param resourceInfo */ buildResourceInfo(resourceInfo: any): void; /** * * @param startTime */ checkPos(startTime: any): any; /** * */ checkPosition(): void; /** * */ checkWidthTaskNameItem(): void; /** * */ clearPredTask(): void; /** * */ create(): Function; /** * */ createConnectingLinesDS(): any[]; /** * */ createConnectingLinesPN(): any[]; /** * */ createTaskDescItem(): any; /** * */ createTaskItem(): any; /** * */ createTaskNameItem(): any; /** * */ createTreeImg(): any; /** * */ endMove(): void; /** * */ endResizeItem(): void; /** * * @param position OptionalThe tooltip position. */ getDateOnPosition(position: String[]): any; /** * */ getMaxPosPredChildTaskItem(): any; /** * * @param task */ getMaxPosPredChildTaskItemInTree(task: any): number; /** * */ getMoveInfo(): void; /** * */ getResizeInfo(): void; /** * */ getTaskOwner(): Object; /** * * @param task */ hideChildTasks(task: any): void; /** * */ hideDescTask(): void; /** * * @param task * @param width * @param moveChild */ moveChildTaskItems(task: any, width: any, moveChild: any): void; /** * * @param width * @param moveChild */ moveCurrentTaskItem(width: any, moveChild: any): void; /** * */ moveDescTask(): void; /** * * @param event */ moveItem(event: any): void; /** * * @param posX */ moveTaskItem(posX: any): void; /** * * @param obj * @param delm */ objKeyToStr(obj: any, delm: any): String; /** * */ postLoadData(): void; /** * */ refresh(): Function; /** * * @param arrLines */ refreshConnectingLinesDS(arrLines: any): any; /** * * @param divDesc */ refreshTaskDesc(divDesc: any): any; /** * * @param itemControl */ refreshTaskItem(itemControl: any): any; /** * * @param event */ resizeItem(event: any): void; /** * * @param width */ resizeTaskItem(width: any): void; /** * * @param duration */ setDuration(duration: any): boolean; /** * * @param name */ setName(name: any): void; /** * * @param percentage */ setPercentCompleted(percentage: any): boolean; /** * * @param previousTaskId */ setPreviousTask(previousTaskId: any): boolean; /** * * @param startTime * @param shiftChild */ setStartTime(startTime: any, shiftChild: any): boolean; /** * * @param owner */ setTaskOwner(owner: any): boolean; /** * * @param task * @param height */ shiftChildTask(task: any, height: any): void; /** * * @param task * @param height */ shiftCurrentTasks(task: any, height: any): void; /** * * @param task * @param height */ shiftNextTask(task: any, height: any): void; /** * * @param task * @param height */ shiftTask(task: any, height: any): void; /** * * @param task * @param isOpen */ showChildTasks(task: any, isOpen: any): void; /** * */ showDescTask(): void; /** * * @param event */ startMove(event: any): void; /** * * @param event */ startResize(event: any): void; } /** * Permalink: http://dojotoolkit.org/api/1.9/dojox/gantt/GanttChart.html * * * @param configuration * @param node */ class GanttChart { constructor(configuration: any, node: any); /** * * @param row */ addDayInPanelTime(row: any): void; /** * * @param row */ addHourInPanelTime(row: any): void; /** * * @param row * @param count * @param month * @param year */ addMonthInPanelTime(row: any, count: any, month: any, year: any): void; /** * * @param projectItem */ addProject(projectItem: any): void; /** * * @param row * @param count * @param week */ addWeekInPanelTime(row: any, count: any, week: any): void; /** * * @param row * @param count * @param year */ addYearInPanelTime(row: any, count: any, year: any): void; /** * */ adjustPanelTime(): void; /** * * @param parentTask * @param childTaskItems */ buildChildTasksData(parentTask: any, childTaskItems: any): void; /** * */ buildUIContent(): void; /** * */ checkHeighPanelTasks(): void; /** * */ checkPosition(): void; /** * * @param parentTask * @param task */ checkPosParentTask(parentTask: any, task: any): boolean; /** * * @param parentTask */ checkPosParentTaskInTree(parentTask: any): any; /** * * @param predTask * @param task */ checkPosPreviousTask(predTask: any, task: any): boolean; /** * */ clearAll(): void; /** * */ clearData(): void; /** * */ clearEvents(): void; /** * */ clearItems(): void; /** * * @param parentTask * @param ctask */ correctPosParentTask(parentTask: any, ctask: any): void; /** * * @param predTask * @param ctask * @param ctaskObj */ correctPosPreviousTask(predTask: any, ctask: any, ctaskObj: any): void; /** * * @param arrChildTasks * @param project */ createChildItemControls(arrChildTasks: any, project: any): void; /** * */ createPanelNamesTasks(): any; /** * */ createPanelNamesTasksHeader(): any; /** * */ createPanelTasks(): any; /** * */ createPanelTime(): any; /** * * @param project */ createTasks(project: any): void; /** * * @param id */ deleteProject(id: any): void; /** * * @param childTasks */ getChildTasksData(childTasks: any): any[]; /** * */ getCountDays(): any; /** * */ getJSONData(): Object; /** * * @param task */ getLastChildTask(task: any): any; /** * * @param task */ getLastCloseParent(task: any): any; /** * * @param startTime */ getPosOnDate(startTime: any): number; /** * * @param id */ getProject(id: any): any; /** * * @param id */ getProjectItemById(id: any): any; /** * */ getStartDate(): any; /** * * @param duration */ getWidthOnDuration(duration: any): any; /** * * @param height */ incHeightPanelNames(height: any): void; /** * * @param height */ incHeightPanelTasks(height: any): void; /** * */ init(): Function; /** * * @param id * @param name * @param startDate */ insertProject(id: any, name: any, startDate: any): any; /** * * @param filename */ loadJSONData(filename: any): void; /** * * @param content */ loadJSONString(content: any): void; /** * * @param parentTask */ openNode(parentTask: any): void; /** * * @param parentTask */ openTree(parentTask: any): void; /** * */ postBindEvents(): void; /** * */ postLoadData(): void; /** * * @param count * @param current * @param multi */ refresh(count: any, current: any, multi: any): void; /** * */ refreshController(): void; /** * * @param pixelsPerDay */ refreshParams(pixelsPerDay: any): void; /** * * @param row */ removeCell(row: any): void; /** * * @param fileName */ saveJSONData(fileName: any): void; /** * * @param project */ setPreviousTask(project: any): any; /** * * @param parentTask */ setPreviousTaskInTree(parentTask: any): any; /** * * @param parentTask */ setStartTimeChild(parentTask: any): void; /** * * @param parenttask */ sortChildTasks(parenttask: any): any; /** * * @param a * @param b */ sortProjStartDate(a: any, b: any): number; /** * * @param project */ sortTasksByStartTime(project: any): void; /** * * @param a * @param b */ sortTaskStartTime(a: any, b: any): number; /** * * @param dip */ switchTeleMicroView(dip: any): void; } } } declare module "dojox/gantt/contextMenuTab" { var exp: dojox.gantt.contextMenuTab export=exp; } declare module "dojox/gantt/GanttProjectControl" { var exp: dojox.gantt.GanttProjectControl export=exp; } declare module "dojox/gantt/GanttProjectItem" { var exp: dojox.gantt.GanttProjectItem export=exp; } declare module "dojox/gantt/GanttResourceItem" { var exp: dojox.gantt.GanttResourceItem export=exp; } declare module "dojox/gantt/GanttChart" { var exp: dojox.gantt.GanttChart export=exp; } declare module "dojox/gantt/GanttTaskControl" { var exp: dojox.gantt.GanttTaskControl export=exp; } declare module "dojox/gantt/TabMenu" { var exp: dojox.gantt.TabMenu export=exp; } declare module "dojox/gantt/GanttTaskItem" { var exp: dojox.gantt.GanttTaskItem export=exp; }
the_stack
import { Component, State, Event, EventEmitter, Element, h } from '@stencil/core'; import '@visa/visa-charts-data-table'; import '@visa/keyboard-instructions'; @Component({ tag: 'app-heat-map', styleUrl: 'app-heat-map.scss' }) export class AppHeatMap { @State() data: any; @State() stateTrigger: any = 0; @State() hoverElement: any = ''; @State() clickElement: any = []; @State() codeString: any = ''; @State() value: any = 0; // this is for handling value changes for button to control which dataset to send @State() valueAccessor: any = 'value'; @State() xAccessor: any = 'date'; @State() yAccessor: any = 'category'; @State() xKeyOrder: any = ['01/01', '01/02', '01/03', '01/04', '01/05', '01/06']; @State() yKeyOrder: any = ['Travel', 'Long Name Restaurant', 'Shopping', 'Other']; @State() wrapLabel: any = true; @State() interactionKeys: any = ['date']; @State() xAxisPlacement: any = 'bottom'; @State() xAxisFormat: any = '%m/%d'; @State() suppressEvents: boolean = false; @State() label: any = { labelAccessor: ['category', 'value'], labelTitle: ['Category ', 'Value'], format: ['', '0o'] }; @State() legend: any = { visible: true, type: 'key', format: '0,0', labels: ['Lowest', 'V V Low', 'V Low', 'Low', 'Med-Low', 'Med', 'Med-High', 'High', 'V High', 'V V High', 'Highest'] }; @State() animations: any = { disabled: false }; startData: any = [ [ { date: new Date('2016-01-01T00:00:00.000Z'), otherX: 'a', otherCategory: 'abc', category: 'Long Name Restaurant', value: 120, count: 420 }, { date: new Date('2016-01-02T00:00:00.000Z'), otherX: 'b', otherCategory: 'abc', category: 'Long Name Restaurant', value: 121, count: 439 }, { date: new Date('2016-01-03T00:00:00.000Z'), otherX: 'c', otherCategory: 'abc', category: 'Long Name Restaurant', value: 119, count: 402 }, { date: new Date('2016-01-04T00:00:00.000Z'), otherX: 'd', otherCategory: 'abc', category: 'Long Name Restaurant', value: 114, count: 434 }, { date: new Date('2016-01-05T00:00:00.000Z'), otherX: 'e', otherCategory: 'abc', category: 'Long Name Restaurant', value: 102, count: 395 }, { date: new Date('2016-01-06T00:00:00.000Z'), otherX: 'f', otherCategory: 'abc', category: 'Long Name Restaurant', value: 112, count: 393 }, { date: new Date('2016-01-01T00:00:00.000Z'), otherX: 'a', otherCategory: '123', category: 'Travel', value: 89, count: 342 }, { date: new Date('2016-01-02T00:00:00.000Z'), otherX: 'b', otherCategory: '123', category: 'Travel', value: 93, count: 434 }, { date: new Date('2016-01-03T00:00:00.000Z'), otherX: 'c', otherCategory: '123', category: 'Travel', value: 82, count: 378 }, { date: new Date('2016-01-04T00:00:00.000Z'), otherX: 'd', otherCategory: '123', category: 'Travel', value: 92, count: 323 }, { date: new Date('2016-01-05T00:00:00.000Z'), otherX: 'e', otherCategory: '123', category: 'Travel', value: 90, count: 434 }, { date: new Date('2016-01-06T00:00:00.000Z'), otherX: 'f', otherCategory: '123', category: 'Travel', value: 85, count: 376 }, { date: new Date('2016-01-01T00:00:00.000Z'), otherX: 'a', otherCategory: 'def', category: 'Shopping', value: 73, count: 456 }, { date: new Date('2016-01-02T00:00:00.000Z'), otherX: 'b', otherCategory: 'def', category: 'Shopping', value: 74, count: 372 }, { date: new Date('2016-01-03T00:00:00.000Z'), otherX: 'c', otherCategory: 'def', category: 'Shopping', value: 68, count: 323 }, { date: new Date('2016-01-04T00:00:00.000Z'), otherX: 'd', otherCategory: 'def', category: 'Shopping', value: 66, count: 383 }, { date: new Date('2016-01-05T00:00:00.000Z'), otherX: 'e', otherCategory: 'def', category: 'Shopping', value: 72, count: 382 }, { date: new Date('2016-01-06T00:00:00.000Z'), otherX: 'f', otherCategory: 'def', category: 'Shopping', value: 70, count: 365 }, { date: new Date('2016-01-01T00:00:00.000Z'), otherX: 'a', otherCategory: 'ghi', category: 'Other', value: 83, count: 432 }, { date: new Date('2016-01-02T00:00:00.000Z'), otherX: 'b', otherCategory: 'ghi', category: 'Other', value: 87, count: 364 }, { date: new Date('2016-01-03T00:00:00.000Z'), otherX: 'c', otherCategory: 'ghi', category: 'Other', value: 76, count: 334 }, { date: new Date('2016-01-04T00:00:00.000Z'), otherX: 'd', otherCategory: 'ghi', category: 'Other', value: 86, count: 395 }, { date: new Date('2016-01-05T00:00:00.000Z'), otherX: 'e', otherCategory: 'ghi', category: 'Other', value: 87, count: 354 }, { date: new Date('2016-01-06T00:00:00.000Z'), otherX: 'f', otherCategory: 'ghi', category: 'Other', value: 77, count: 386 } ] ]; dataStorage: any = [ // this.startData, [ { date: new Date('2016-01-01T00:00:00.000Z'), otherX: 'a', otherCategory: 'abc', category: 'Long Name Restaurant', value: 120, count: 420 }, { date: new Date('2016-01-02T00:00:00.000Z'), otherX: 'b', otherCategory: 'abc', category: 'Long Name Restaurant', value: 121, count: 439 }, { date: new Date('2016-01-03T00:00:00.000Z'), otherX: 'c', otherCategory: 'abc', category: 'Long Name Restaurant', value: 119, count: 402 }, { date: new Date('2016-01-04T00:00:00.000Z'), otherX: 'd', otherCategory: 'abc', category: 'Long Name Restaurant', value: 114, count: 434 }, { date: new Date('2016-01-05T00:00:00.000Z'), otherX: 'e', otherCategory: 'abc', category: 'Long Name Restaurant', value: 102, count: 395 }, { date: new Date('2016-01-06T00:00:00.000Z'), otherX: 'f', otherCategory: 'abc', category: 'Long Name Restaurant', value: 112, count: 393 }, { date: new Date('2016-01-01T00:00:00.000Z'), otherX: 'a', otherCategory: '123', category: 'Travel', value: 89, count: 342 }, { date: new Date('2016-01-02T00:00:00.000Z'), otherX: 'b', otherCategory: '123', category: 'Travel', value: 93, count: 434 }, { date: new Date('2016-01-03T00:00:00.000Z'), otherX: 'c', otherCategory: '123', category: 'Travel', value: 82, count: 378 }, { date: new Date('2016-01-04T00:00:00.000Z'), otherX: 'd', otherCategory: '123', category: 'Travel', value: 92, count: 323 }, { date: new Date('2016-01-05T00:00:00.000Z'), otherX: 'e', otherCategory: '123', category: 'Travel', value: 90, count: 434 }, { date: new Date('2016-01-06T00:00:00.000Z'), otherX: 'f', otherCategory: '123', category: 'Travel', value: 85, count: 376 }, { date: new Date('2016-01-01T00:00:00.000Z'), otherX: 'a', otherCategory: 'def', category: 'Shopping', value: 73, count: 456 }, { date: new Date('2016-01-02T00:00:00.000Z'), otherX: 'b', otherCategory: 'def', category: 'Shopping', value: 74, count: 372 }, { date: new Date('2016-01-03T00:00:00.000Z'), otherX: 'c', otherCategory: 'def', category: 'Shopping', value: 68, count: 323 }, { date: new Date('2016-01-04T00:00:00.000Z'), otherX: 'd', otherCategory: 'def', category: 'Shopping', value: 66, count: 383 }, { date: new Date('2016-01-05T00:00:00.000Z'), otherX: 'e', otherCategory: 'def', category: 'Shopping', value: 72, count: 382 }, { date: new Date('2016-01-06T00:00:00.000Z'), otherX: 'f', otherCategory: 'def', category: 'Shopping', value: 70, count: 365 }, { date: new Date('2016-01-01T00:00:00.000Z'), otherX: 'a', otherCategory: 'ghi', category: 'Other', value: 83, count: 432 }, { date: new Date('2016-01-02T00:00:00.000Z'), otherX: 'b', otherCategory: 'ghi', category: 'Other', value: 87, count: 364 }, { date: new Date('2016-01-03T00:00:00.000Z'), otherX: 'c', otherCategory: 'ghi', category: 'Other', value: 76, count: 334 }, { date: new Date('2016-01-04T00:00:00.000Z'), otherX: 'd', otherCategory: 'ghi', category: 'Other', value: 86, count: 395 }, { date: new Date('2016-01-05T00:00:00.000Z'), otherX: 'e', otherCategory: 'ghi', category: 'Other', value: 87, count: 354 }, { date: new Date('2016-01-06T00:00:00.000Z'), otherX: 'f', otherCategory: 'ghi', category: 'Other', value: 77, count: 386 } ], [ { date: new Date('2016-01-01T00:00:00.000Z'), otherX: 'a', otherCategory: 'abc', category: 'Long Name Restaurant', value: 120, count: 420 }, { date: new Date('2016-01-03T00:00:00.000Z'), otherX: 'b', otherCategory: 'abc', category: 'Long Name Restaurant', value: 119, count: 402 }, { date: new Date('2016-01-04T00:00:00.000Z'), otherX: 'c', otherCategory: 'abc', category: 'Long Name Restaurant', value: 114, count: 434 }, { date: new Date('2016-01-05T00:00:00.000Z'), otherX: 'd', otherCategory: 'abc', category: 'Long Name Restaurant', value: 102, count: 395 }, { date: new Date('2016-01-06T00:00:00.000Z'), otherX: 'e', otherCategory: 'abc', category: 'Long Name Restaurant', value: 112, count: 393 }, { date: new Date('2016-01-01T00:00:00.000Z'), otherX: 'a', otherCategory: '123', category: 'Travel', value: 89, count: 342 }, { date: new Date('2016-01-03T00:00:00.000Z'), otherX: 'b', otherCategory: '123', category: 'Travel', value: 82, count: 378 }, { date: new Date('2016-01-04T00:00:00.000Z'), otherX: 'c', otherCategory: '123', category: 'Travel', value: 92, count: 323 }, { date: new Date('2016-01-05T00:00:00.000Z'), otherX: 'd', otherCategory: '123', category: 'Travel', value: 90, count: 434 }, { date: new Date('2016-01-06T00:00:00.000Z'), otherX: 'e', otherCategory: '123', category: 'Travel', value: 85, count: 376 }, { date: new Date('2016-01-01T00:00:00.000Z'), otherX: 'a', otherCategory: 'def', category: 'Shopping', value: 73, count: 456 }, { date: new Date('2016-01-03T00:00:00.000Z'), otherX: 'b', otherCategory: 'def', category: 'Shopping', value: 68, count: 323 }, { date: new Date('2016-01-04T00:00:00.000Z'), otherX: 'c', otherCategory: 'def', category: 'Shopping', value: 66, count: 383 }, { date: new Date('2016-01-05T00:00:00.000Z'), otherX: 'd', otherCategory: 'def', category: 'Shopping', value: 72, count: 382 }, { date: new Date('2016-01-06T00:00:00.000Z'), otherX: 'e', otherCategory: 'def', category: 'Shopping', value: 70, count: 365 }, { date: new Date('2016-01-01T00:00:00.000Z'), otherX: 'a', otherCategory: 'ghi', category: 'Other', value: 83, count: 432 }, { date: new Date('2016-01-03T00:00:00.000Z'), otherX: 'b', otherCategory: 'ghi', category: 'Other', value: 76, count: 334 }, { date: new Date('2016-01-04T00:00:00.000Z'), otherX: 'c', otherCategory: 'ghi', category: 'Other', value: 86, count: 395 }, { date: new Date('2016-01-05T00:00:00.000Z'), otherX: 'd', otherCategory: 'ghi', category: 'Other', value: 87, count: 354 }, { date: new Date('2016-01-06T00:00:00.000Z'), otherX: 'e', otherCategory: 'ghi', category: 'Other', value: 77, count: 386 } ], [ { date: new Date('2016-01-01T00:00:00.000Z'), otherX: 'a', otherCategory: 'abc', category: 'Long Name Restaurant', value: 120, count: 420 }, { date: new Date('2016-01-02T00:00:00.000Z'), otherX: 'b', otherCategory: 'abc', category: 'Long Name Restaurant', value: 121, count: 439 }, { date: new Date('2016-01-03T00:00:00.000Z'), otherX: 'c', otherCategory: 'abc', category: 'Long Name Restaurant', value: 119, count: 402 }, { date: new Date('2016-01-04T00:00:00.000Z'), otherX: 'd', otherCategory: 'abc', category: 'Long Name Restaurant', value: 114, count: 434 }, { date: new Date('2016-01-05T00:00:00.000Z'), otherX: 'e', otherCategory: 'abc', category: 'Long Name Restaurant', value: 102, count: 395 }, { date: new Date('2016-01-06T00:00:00.000Z'), otherX: 'f', otherCategory: 'abc', category: 'Long Name Restaurant', value: 112, count: 393 }, { date: new Date('2016-01-01T00:00:00.000Z'), otherX: 'a', otherCategory: '123', category: 'Travel', value: 89, count: 342 }, { date: new Date('2016-01-02T00:00:00.000Z'), otherX: 'b', otherCategory: '123', category: 'Travel', value: 93, count: 434 }, { date: new Date('2016-01-03T00:00:00.000Z'), otherX: 'c', otherCategory: '123', category: 'Travel', value: 82, count: 378 }, { date: new Date('2016-01-04T00:00:00.000Z'), otherX: 'd', otherCategory: '123', category: 'Travel', value: 92, count: 323 }, { date: new Date('2016-01-05T00:00:00.000Z'), otherX: 'e', otherCategory: '123', category: 'Travel', value: 90, count: 434 }, { date: new Date('2016-01-06T00:00:00.000Z'), otherX: 'f', otherCategory: '123', category: 'Travel', value: 85, count: 376 }, { date: new Date('2016-01-01T00:00:00.000Z'), otherX: 'a', otherCategory: 'def', category: 'Shopping', value: 73, count: 456 }, { date: new Date('2016-01-02T00:00:00.000Z'), otherX: 'b', otherCategory: 'def', category: 'Shopping', value: 74, count: 372 }, { date: new Date('2016-01-03T00:00:00.000Z'), otherX: 'c', otherCategory: 'def', category: 'Shopping', value: 68, count: 323 }, { date: new Date('2016-01-04T00:00:00.000Z'), otherX: 'd', otherCategory: 'def', category: 'Shopping', value: 66, count: 383 }, { date: new Date('2016-01-05T00:00:00.000Z'), otherX: 'e', otherCategory: 'def', category: 'Shopping', value: 72, count: 382 }, { date: new Date('2016-01-06T00:00:00.000Z'), otherX: 'f', otherCategory: 'def', category: 'Shopping', value: 70, count: 365 }, { date: new Date('2016-01-01T00:00:00.000Z'), otherX: 'a', otherCategory: 'ghi', category: 'Other', value: 83, count: 432 }, { date: new Date('2016-01-02T00:00:00.000Z'), otherX: 'b', otherCategory: 'ghi', category: 'Other', value: 87, count: 364 }, { date: new Date('2016-01-03T00:00:00.000Z'), otherX: 'c', otherCategory: 'ghi', category: 'Other', value: 76, count: 334 }, { date: new Date('2016-01-04T00:00:00.000Z'), otherX: 'd', otherCategory: 'ghi', category: 'Other', value: 86, count: 395 }, { date: new Date('2016-01-05T00:00:00.000Z'), otherX: 'e', otherCategory: 'ghi', category: 'Other', value: 87, count: 354 }, { date: new Date('2016-01-06T00:00:00.000Z'), otherX: 'f', otherCategory: 'ghi', category: 'Other', value: 77, count: 386 } ], [ { date: new Date('2016-01-01T00:00:00.000Z'), otherX: 'a', otherCategory: 'abc', category: 'Long Name Restaurant', value: 121, count: 439 }, { date: new Date('2016-01-02T00:00:00.000Z'), otherX: 'b', otherCategory: 'abc', category: 'Long Name Restaurant', value: 120, count: 420 }, { date: new Date('2016-01-03T00:00:00.000Z'), otherX: 'c', otherCategory: 'abc', category: 'Long Name Restaurant', value: 119, count: 402 }, { date: new Date('2016-01-04T00:00:00.000Z'), otherX: 'd', otherCategory: 'abc', category: 'Long Name Restaurant', value: 114, count: 434 }, { date: new Date('2016-01-05T00:00:00.000Z'), otherX: 'e', otherCategory: 'abc', category: 'Long Name Restaurant', value: 102, count: 395 }, { date: new Date('2016-01-06T00:00:00.000Z'), otherX: 'f', otherCategory: 'abc', category: 'Long Name Restaurant', value: 112, count: 393 }, { date: new Date('2016-01-01T00:00:00.000Z'), otherX: 'a', otherCategory: '123', category: 'Travel', value: 89, count: 342 }, { date: new Date('2016-01-02T00:00:00.000Z'), otherX: 'b', otherCategory: '123', category: 'Travel', value: 93, count: 434 }, { date: new Date('2016-01-03T00:00:00.000Z'), otherX: 'c', otherCategory: '123', category: 'Travel', value: 82, count: 378 }, { date: new Date('2016-01-04T00:00:00.000Z'), otherX: 'd', otherCategory: '123', category: 'Travel', value: 92, count: 323 }, { date: new Date('2016-01-05T00:00:00.000Z'), otherX: 'e', otherCategory: '123', category: 'Travel', value: 90, count: 434 }, { date: new Date('2016-01-06T00:00:00.000Z'), otherX: 'f', otherCategory: '123', category: 'Travel', value: 85, count: 376 }, { date: new Date('2016-01-01T00:00:00.000Z'), otherX: 'a', otherCategory: 'def', category: 'Shopping', value: 73, count: 456 }, { date: new Date('2016-01-02T00:00:00.000Z'), otherX: 'b', otherCategory: 'def', category: 'Shopping', value: 74, count: 372 }, { date: new Date('2016-01-03T00:00:00.000Z'), otherX: 'c', otherCategory: 'def', category: 'Shopping', value: 68, count: 323 }, { date: new Date('2016-01-04T00:00:00.000Z'), otherX: 'd', otherCategory: 'def', category: 'Shopping', value: 66, count: 383 }, { date: new Date('2016-01-05T00:00:00.000Z'), otherX: 'e', otherCategory: 'def', category: 'Shopping', value: 72, count: 382 }, { date: new Date('2016-01-06T00:00:00.000Z'), otherX: 'f', otherCategory: 'def', category: 'Shopping', value: 70, count: 365 }, { date: new Date('2016-01-01T00:00:00.000Z'), otherX: 'a', otherCategory: 'ghi', category: 'Other', value: 83, count: 432 }, { date: new Date('2016-01-02T00:00:00.000Z'), otherX: 'b', otherCategory: 'ghi', category: 'Other', value: 87, count: 364 }, { date: new Date('2016-01-03T00:00:00.000Z'), otherX: 'c', otherCategory: 'ghi', category: 'Other', value: 76, count: 334 }, { date: new Date('2016-01-04T00:00:00.000Z'), otherX: 'd', otherCategory: 'ghi', category: 'Other', value: 86, count: 395 }, { date: new Date('2016-01-05T00:00:00.000Z'), otherX: 'e', otherCategory: 'ghi', category: 'Other', value: 87, count: 354 }, { date: new Date('2016-01-06T00:00:00.000Z'), otherX: 'f', otherCategory: 'ghi', category: 'Other', value: 77, count: 386 } ], [ { date: new Date('2016-01-01T00:00:00.000Z'), otherX: 'a', otherCategory: 'abc', category: 'Long Name Restaurant', value: 120, count: 420 }, { date: new Date('2016-01-02T00:00:00.000Z'), otherX: 'b', otherCategory: 'abc', category: 'Long Name Restaurant', value: 121, count: 439 }, { date: new Date('2016-01-03T00:00:00.000Z'), otherX: 'c', otherCategory: 'abc', category: 'Long Name Restaurant', value: 119, count: 402 }, { date: new Date('2016-01-04T00:00:00.000Z'), otherX: 'd', otherCategory: 'abc', category: 'Long Name Restaurant', value: 114, count: 434 }, { date: new Date('2016-01-05T00:00:00.000Z'), otherX: 'e', otherCategory: 'abc', category: 'Long Name Restaurant', value: 102, count: 395 }, { date: new Date('2016-01-06T00:00:00.000Z'), otherX: 'f', otherCategory: 'abc', category: 'Long Name Restaurant', value: 112, count: 393 }, { date: new Date('2016-01-07T00:00:00.000Z'), otherX: 'g', otherCategory: 'abc', category: 'Long Name Restaurant', value: 130, count: 445 }, { date: new Date('2016-01-01T00:00:00.000Z'), otherX: 'a', otherCategory: '123', category: 'Travel', value: 89, count: 342 }, { date: new Date('2016-01-02T00:00:00.000Z'), otherX: 'b', otherCategory: '123', category: 'Travel', value: 93, count: 434 }, { date: new Date('2016-01-03T00:00:00.000Z'), otherX: 'c', otherCategory: '123', category: 'Travel', value: 82, count: 378 }, { date: new Date('2016-01-04T00:00:00.000Z'), otherX: 'd', otherCategory: '123', category: 'Travel', value: 92, count: 323 }, { date: new Date('2016-01-05T00:00:00.000Z'), otherX: 'e', otherCategory: '123', category: 'Travel', value: 90, count: 434 }, { date: new Date('2016-01-06T00:00:00.000Z'), otherX: 'f', otherCategory: '123', category: 'Travel', value: 85, count: 376 }, { date: new Date('2016-01-07T00:00:00.000Z'), otherX: 'g', otherCategory: '123', category: 'Travel', value: 88, count: 404 }, { date: new Date('2016-01-01T00:00:00.000Z'), otherX: 'a', otherCategory: 'def', category: 'Shopping', value: 73, count: 456 }, { date: new Date('2016-01-02T00:00:00.000Z'), otherX: 'b', otherCategory: 'def', category: 'Shopping', value: 74, count: 372 }, { date: new Date('2016-01-03T00:00:00.000Z'), otherX: 'c', otherCategory: 'def', category: 'Shopping', value: 68, count: 323 }, { date: new Date('2016-01-04T00:00:00.000Z'), otherX: 'd', otherCategory: 'def', category: 'Shopping', value: 66, count: 383 }, { date: new Date('2016-01-05T00:00:00.000Z'), otherX: 'e', otherCategory: 'def', category: 'Shopping', value: 72, count: 382 }, { date: new Date('2016-01-06T00:00:00.000Z'), otherX: 'f', otherCategory: 'def', category: 'Shopping', value: 70, count: 365 }, { date: new Date('2016-01-07T00:00:00.000Z'), otherX: 'g', otherCategory: 'def', category: 'Shopping', value: 74, count: 296 } ] ]; @State() accessibility: any = { longDescription: 'This is a chart template that was made to showcase the Visa Chart Components heat map', contextExplanation: 'This chart exists in a demo app created to let you quickly change props and see results', executiveSummary: 'Restaurants have the highest values shown', purpose: 'The purpose of this chart template is to provide an example of a heat map', structureNotes: 'A square is shown for each of the four categories and seven dates displayed, and the color of these squares represents a high, mid or low value', statisticalNotes: 'This chart is using dummy data', elementsAreInterface: false, keyboardNavConfig: { disabled: false }, onChangeFunc: d => { this.onChangeFunc(d); }, disableValidation: true }; dataLabel: any = { visible: true, labelAccessor: 'value', format: '' }; padding: any = { top: 20, bottom: 30, right: 50, left: 80 }; xAxis: any = { visible: true, label: '', placement: this.xAxisPlacement, format: this.xAxisFormat, tickInterval: 1 }; yAxis: any = { visible: true, label: '', format: '' }; @Event() updateComponent: EventEmitter; @Element() appEl: HTMLElement; onClickFunc(ev) { const d = { ...ev.detail }; if (d) { const newClicks = [...this.clickElement]; const keys = Object.keys(d); const index = this.clickElement.findIndex(o => { let conditionsMet = 0; keys.forEach(key => { conditionsMet += o[key] === d[key] ? 1 : 0; }); return conditionsMet && conditionsMet === keys.length; }); if (index > -1) { newClicks.splice(index, 1); } else { newClicks.push(d); } this.clickElement = newClicks; } } onHoverFunc(ev) { this.hoverElement = { ...ev.detail }; } onMouseOut() { this.hoverElement = ''; } onChangeFunc(d) { console.log(d); } changeData() { this.stateTrigger = this.stateTrigger < this.dataStorage.length - 1 ? this.stateTrigger + 1 : 0; } changeXAccessor() { this.xAccessor = this.xAccessor !== 'date' ? 'date' : 'otherX'; } changeYAccessor() { this.yAccessor = this.yAccessor !== 'category' ? 'category' : 'otherCategory'; } changeValueAccessor() { this.valueAccessor = this.valueAccessor !== 'value' ? 'value' : 'count'; } changexKeyOrder() { this.xKeyOrder = this.xKeyOrder[2] !== '01/03' ? ['01/01', '01/02', '01/03', '01/04', '01/05', '01/06'] : ['01/01', '01/02', '01/04', '01/03', '01/06', '01/05']; } changeyKeyOrder() { console.log('changing key order'); this.yKeyOrder = this.yKeyOrder[0] !== 'Long Name Restaurant' ? ['Long Name Restaurant', 'Travel', 'Shopping', 'Other'] : ['Shopping', 'Long Name Restaurant', 'Other', 'Travel']; } changeIntKey() { this.interactionKeys = this.interactionKeys[0] !== 'date' ? ['date'] : ['category']; } changeWrapLabel() { this.wrapLabel = this.wrapLabel ? false : true; } changeTooltip() { this.label.labelAccessor[0] !== 'category' ? (this.label = { labelAccessor: ['category', 'value'], labelTitle: ['Category ', 'Value'], format: ['', '0o'] }) : (this.label = { labelAccessor: ['value'], labelTitle: ['Value'], format: [''] }); } changeLegend() { this.legend.type !== 'key' ? (this.legend = { visible: true, type: 'key', format: '0,0', labels: [ 'Lowest', 'V V Low', 'V Low', 'Low', 'Med-Low', 'Med', 'Med-High', 'High', 'V High', 'V V High', 'Highest' ] }) : (this.legend = { visible: true, type: 'gradient', format: '0o', labels: [''] }); } changeXAxisFormat() { this.xAxisFormat = this.xAxisFormat !== '%d' ? '%d' : '%m/%d'; } changeXAxisPlacement() { this.xAxisPlacement = this.xAxisPlacement !== 'bottom' ? 'bottom' : 'top'; } toggleTextures() { const a = { ...this.accessibility, showExperimentalTextures: !this.accessibility.showExperimentalTextures }; this.accessibility = a; } toggleStrokes() { const a = { ...this.accessibility, hideStrokes: !this.accessibility.hideStrokes }; this.accessibility = a; } changeAccessElements() { this.accessibility = { ...this.accessibility, elementsAreInterface: !this.accessibility.elementsAreInterface }; } changeKeyNav() { const keyboardNavConfig = { disabled: !this.accessibility.keyboardNavConfig.disabled }; this.accessibility = { ...this.accessibility, keyboardNavConfig }; } toggleSuppress() { this.suppressEvents = !this.suppressEvents; } toggleAnimations() { this.animations = { disabled: !this.animations.disabled }; } render() { this.data = this.dataStorage[this.stateTrigger]; console.log('!!!!app re-render'); return ( <div> <button onClick={() => { this.changeData(); }} > change data </button> <button onClick={() => { this.changeAccessElements(); }} > change elementsAreInterface </button> <button onClick={() => { this.toggleSuppress(); }} > toggle event suppression </button> <button onClick={() => { this.changeKeyNav(); }} > toggle keyboard nav </button> <button onClick={() => { this.changeValueAccessor(); }} > change valueAccessor </button> <button onClick={() => { this.changeXAccessor(); }} > change xAccessor </button> <button onClick={() => { this.changeYAccessor(); }} > change yAccessor </button> <button onClick={() => { this.changexKeyOrder(); }} > change xKeyOrder </button> <button onClick={() => { this.changeyKeyOrder(); }} > change yKeyOrder </button> <button onClick={() => { this.changeWrapLabel(); }} > change wrap label </button> <button onClick={() => { this.changeTooltip(); }} > change tooltip label </button> <button onClick={() => { this.changeLegend(); }} > change legend </button> <button onClick={() => { this.changeIntKey(); }} > change interaction key </button> <button onClick={() => { this.changeXAxisFormat(); }} > change xAxis Format </button> <button onClick={() => { this.changeXAxisPlacement(); }} > change xAxis Placement </button> <button onClick={() => { this.toggleTextures(); }} > toggle textures </button> <button onClick={() => { this.toggleStrokes(); }} > toggle strokes </button> <button onClick={() => { this.toggleAnimations(); }} > toggle animations </button> <heat-map colorPalette={'diverging_GtoP'} // sequential_grey // diverging_GtoP // diverging_GtoP // colors={[#ff4000, #555fff, #ff193f]} colorSteps={11} animationConfig={this.animations} cursor={'pointer'} data={this.data} dataLabel={this.dataLabel} height={400} hideAxisPath={true} legend={this.legend} mainTitle={'Heat Map Default'} interactionKeys={this.interactionKeys} padding={this.padding} subTitle={'Interaction Style'} showTooltip={true} tooltipLabel={this.label} width={800} maxValueOverride={50} valueAccessor={this.valueAccessor} xAccessor={this.xAccessor} yAccessor={this.yAccessor} // xKeyOrder={this.xKeyOrder} yKeyOrder={this.yKeyOrder} wrapLabel={this.wrapLabel} shape={'square'} xAxis={this.xAxis} yAxis={this.yAxis} accessibility={this.accessibility} suppressEvents={this.suppressEvents} hoverHighlight={this.hoverElement} clickHighlight={this.clickElement} onClickFunc={d => this.onClickFunc(d)} onHoverFunc={d => this.onHoverFunc(d)} onMouseOutFunc={() => this.onMouseOut()} /> </div> ); } }
the_stack
import { GetProcessesAttemptAction, CreateProcessSuccessAction, CREATE_PROCESS_SUCCESS, GET_PROCESSES_ATTEMPT, GetProcessesSuccessAction, GET_PROCESSES_SUCCESS, DeleteProcessSuccessAction, DELETE_PROCESS_SUCCESS, ProcessActions, UpdateProcessSuccessAction, UPDATE_PROCESS_SUCCESS, GetProcessSuccessAction, RemoveElementMappingAction, REMOVE_ELEMENT_MAPPING, DeleteProcessExtensionAction } from './process-editor.actions'; import { ProcessEntitiesState, initialProcessEntitiesState } from './process-entities.state'; import { PROCESS, Process, ProcessContent, ServicesParameterMappings, ServiceParameterMappings, UpdateServiceParametersAction, EntityProperty, EntityProperties, MappingType, UPDATE_SERVICE_PARAMETERS, UpdateUserTaskTemplateAction, TaskTemplateType, UPDATE_TASK_TEMPLATE } from '@alfresco-dbp/modeling-shared/sdk'; import { processEntitiesReducer } from './process-entities.reducer'; import { mockProcessModel, mappings } from './process.mock'; import * as processVariablesActions from './process-variables.actions'; describe('ProcessEntitiesReducer', () => { let initialState: ProcessEntitiesState; let action: ProcessActions; const process: any = { type: PROCESS, id: 'mock-id' }; const processId = 'Process_12345678'; beforeEach(() => { initialState = { ...initialProcessEntitiesState }; }); it('should handle CREATE_PROCESS_SUCCESS', () => { action = <CreateProcessSuccessAction>{ type: CREATE_PROCESS_SUCCESS, process: process }; const newState = processEntitiesReducer(initialState, action); expect(newState.ids).toEqual([process.id]); expect(newState.entities).toEqual({ [process.id]: process }); }); it('should handle GET_PROCESSES_ATTEMPT', () => { action = <GetProcessesAttemptAction>{ type: GET_PROCESSES_ATTEMPT, projectId: 'app-id' }; const newState = processEntitiesReducer(initialState, action); expect(newState.loading).toEqual(true); }); it('should handle GET_PROCESSES_SUCCESS', () => { const processes = [process, { ...process, id: 'mock-id2' }]; action = <GetProcessesSuccessAction>{ type: GET_PROCESSES_SUCCESS, processes: processes }; const newState = processEntitiesReducer(initialState, action); expect(newState.ids).toEqual(processes.map(conn => conn.id)); expect(newState.entities).toEqual({ [processes[0].id]: processes[0], [processes[1].id]: processes[1] }); expect(newState.loading).toEqual(false); expect(newState.loaded).toEqual(true); }); it('should handle REMOVE_ELEMENT_MAPPING', () => { const elementId = 'UserTask_0o7efx6'; const processes = [{ ...process, extensions: { [processId]: { mappings: { [elementId]: { inputs: { 'e441111c-5a3d-4f78-a571-f57e67ce85bf': { type: MappingType.value, value: 'test' } } } }, constants: { [elementId]: { '_activiti_dmn_table_"': { 'value': 'dt' } } }, assignments: { [elementId]: { 'type': 'identity', 'assignment': 'assignee', 'id': elementId } }, properties: {} } } }]; action = <GetProcessesSuccessAction>{ type: GET_PROCESSES_SUCCESS, processes }; let newState = processEntitiesReducer(initialState, action); action = <RemoveElementMappingAction>{ type: REMOVE_ELEMENT_MAPPING, processModelId: process.id, elementId, bpmnProcessElementId: processId }; newState = processEntitiesReducer(newState, action); expect(newState.entities[process.id].extensions[processId].mappings).toEqual({}); expect(newState.entities[process.id].extensions[processId].constants).toEqual({}); expect(newState.entities[process.id].extensions[processId].assignments).toEqual({}); }); it('should handle UPDATE_SERVICE_PARAMETERS', () => { const elementId = 'UserTask_0o7efx6'; const mockMapping = { inputs: { 'e441111c-5a3d-4f78-a571-f57e67ce85bf': { type: MappingType.value, value: 'test' } }, outputs: { 'test': { type: MappingType.variable, value: 'e441111c-5a3d-4f78-a571-f57e67ce85bf' } } }; const mockConstants = { '_activiti_dmn_table_"': { 'value': 'dt' } }; const processes = [{ ...process, extensions: { mappings: {}, id: 'mock-id', properties: {}, constants: {} } }]; let newState = processEntitiesReducer(initialState, <GetProcessesSuccessAction>{ type: GET_PROCESSES_SUCCESS, processes }); newState = processEntitiesReducer(newState, <UpdateServiceParametersAction>{ type: UPDATE_SERVICE_PARAMETERS, modelId: process.id, processId: processId, serviceId: elementId, serviceParameterMappings: mockMapping, constants: mockConstants }); expect(newState.entities[process.id].extensions[processId].mappings).toEqual({ [elementId]: mockMapping }); expect(newState.entities[process.id].extensions[processId].constants).toEqual({ [elementId]: mockConstants }); newState = processEntitiesReducer(newState, <UpdateServiceParametersAction>{ type: UPDATE_SERVICE_PARAMETERS, modelId: process.id, processId: processId, serviceId: elementId, serviceParameterMappings: {} }); expect(newState.entities[process.id].extensions[processId].mappings).toEqual({ [elementId]: {} }); newState = processEntitiesReducer(newState, <UpdateServiceParametersAction>{ type: UPDATE_SERVICE_PARAMETERS, modelId: process.id, processId: processId, serviceId: elementId, serviceParameterMappings: { inputs: { ...mockMapping.inputs }, outputs: {} } }); expect(newState.entities[process.id].extensions[processId].mappings).toEqual({ [elementId]: { inputs: { ...mockMapping.inputs } } }); newState = processEntitiesReducer(newState, <UpdateServiceParametersAction>{ type: UPDATE_SERVICE_PARAMETERS, modelId: process.id, processId: processId, serviceId: elementId, serviceParameterMappings: { inputs: {}, outputs: { ...mockMapping.outputs } } }); expect(newState.entities[process.id].extensions[processId].mappings).toEqual({ [elementId]: { outputs: { ...mockMapping.outputs } } }); newState = processEntitiesReducer(newState, <UpdateServiceParametersAction>{ type: UPDATE_SERVICE_PARAMETERS, modelId: process.id, processId: processId, serviceId: elementId, serviceParameterMappings: { inputs: {}, outputs: {} } }); expect(newState.entities[process.id].extensions[processId].mappings).toEqual({}); }); it('should handle DELETE_PROCESS_SUCCESS', () => { const processes = [process, { ...process, id: 'mock-id2' }]; action = <GetProcessesSuccessAction>{ type: GET_PROCESSES_SUCCESS, processes: processes }; let newState = processEntitiesReducer(initialState, action); action = <DeleteProcessSuccessAction>{ type: DELETE_PROCESS_SUCCESS, processId: 'mock-id2' }; newState = processEntitiesReducer(newState, action); expect(newState.ids).toEqual([process.id]); expect(newState.entities).toEqual({ [process.id]: process }); }); it('should handle UPDATE_PROCESS_SUCCESS', () => { const processes = [process, { ...process, id: 'mock-id2' }]; action = <GetProcessesSuccessAction>{ type: GET_PROCESSES_SUCCESS, processes: processes }; const stateWithAddedProcesses = processEntitiesReducer(initialState, action); const changes = { id: process.id, changes: { ...process, name: 'name2', description: 'desc2' } }; action = <UpdateProcessSuccessAction>{ type: UPDATE_PROCESS_SUCCESS, payload: changes, content: '' }; const newState = processEntitiesReducer(stateWithAddedProcesses, action); expect(newState.entities[process.id]).toEqual({ ...process, name: 'name2', description: 'desc2' }); }); it('should update to next version on UPDATE_PROCESS_SUCCESS', () => { const processes = [process, { ...process, id: 'mock-id2' }]; action = <GetProcessesSuccessAction>{ type: GET_PROCESSES_SUCCESS, processes: processes }; const stateWithAddedProcesses = processEntitiesReducer(initialState, action); const changes = { id: process.id, changes: { ...process, name: 'name2', description: 'desc2', version: '0.0.5' } }; action = <UpdateProcessSuccessAction>{ type: UPDATE_PROCESS_SUCCESS, payload: changes, content: '' }; const newState = processEntitiesReducer(stateWithAddedProcesses, action); expect(newState.entities[process.id]).toEqual({ ...process, name: 'name2', description: 'desc2', version: '0.0.5' }); }); describe('GET_PROCESS_SUCCESS', () => { let diagram: ProcessContent; beforeEach(() => { diagram = <ProcessContent>'<bpmn></bpmn>'; }); it('should update the process in the state', () => { action = new GetProcessSuccessAction({ process: <Process>process, diagram }); const newState = processEntitiesReducer(initialState, action); expect(newState.entities[process.id]).toEqual(process); }); it('should update the content of a process in the state', () => { action = new GetProcessSuccessAction({ process: <Process>process, diagram }); const newState = processEntitiesReducer(initialState, action); expect(newState.entityContents[process.id]).toEqual(diagram); }); it('should update the content with default values if no content from backend. The id must be prefixed with process-', () => { action = new GetProcessSuccessAction({ process: <Process>process, diagram: <ProcessContent>'' }); const newState = processEntitiesReducer(initialState, action); expect(newState.entityContents[process.id]).toEqual(''); }); }); it('should handle UPDATE_SERVICE_PARAMETERS', () => { const serviceTaskId = 'serviceTaskId'; const serviceParameterMappings: ServiceParameterMappings = { inputs: { 'param1': { type: MappingType.variable, value: 'variable1' } }, outputs: { 'param2': { type: MappingType.variable, value: 'variable' } } }; initialState = { ...initialProcessEntitiesState, entities: { [mockProcessModel.id]: mockProcessModel }, ids: [mockProcessModel.id] }; const newState = processEntitiesReducer(initialState, new UpdateServiceParametersAction(mockProcessModel.id, processId, serviceTaskId, serviceParameterMappings)); expect(newState.entities[mockProcessModel.id].extensions[processId].mappings).toEqual({ ...mappings, 'serviceTaskId': serviceParameterMappings }); }); it('should handle UPDATE_PROCESS_VARIABLES', () => { initialState = { ...initialProcessEntitiesState, entities: { [mockProcessModel.id]: mockProcessModel }, ids: [mockProcessModel.id] }; /* cspell: disable-next-line */ const mockProperty: EntityProperty = { 'id': 'id', 'name': 'appa', 'type': 'string', 'required': false, 'value': '' }; const mockProperties: EntityProperties = { [mockProperty.id]: mockProperty }; const newState = processEntitiesReducer(initialState, new processVariablesActions.UpdateProcessVariablesAction({ modelId: mockProcessModel.id, processId, properties: mockProperties })); expect(newState.entities[mockProcessModel.id].extensions[processId].properties).toEqual(mockProperties); expect(newState.entities[mockProcessModel.id].extensions.mappings).toEqual(mockProcessModel.extensions.mappings); }); describe('should handle mapping update/remove', () => { it('should remove mappings if process variable is renamed', () => { initialState = { ...initialProcessEntitiesState, entities: { [mockProcessModel.id]: mockProcessModel }, ids: [mockProcessModel.id] }; const mockProperties: EntityProperties = { /* cspell: disable-next-line */ 'mockprop': { 'id': 'mockprop', 'name': 'mock-variable', 'type': 'string', 'required': false, 'value': '' }, /* cspell: disable-next-line */ 'mockprop2': { 'id': 'mockprop2', 'name': 'beautiful-variable-updated', 'type': 'string', 'required': false, 'value': '' }, /* cspell: disable-next-line */ 'mockprop3': { 'id': 'mockprop3', 'name': 'terrifying-variable-type-changed', 'type': 'boolean', 'required': false, 'value': '' } }; const newState = processEntitiesReducer(initialState, new processVariablesActions.UpdateProcessVariablesAction({ modelId: mockProcessModel.id, processId, properties: mockProperties })); const updatedMappings: ServicesParameterMappings = { 'taskId': { inputs: { 'input-param-2': { 'type': MappingType.variable, 'value': 'mock-variable' } } } }; expect(newState.entities[mockProcessModel.id].extensions[processId].mappings).toEqual(updatedMappings); }); it('should remove mappings if process variable is deleted', () => { initialState = { ...initialProcessEntitiesState, entities: { [mockProcessModel.id]: mockProcessModel }, ids: [mockProcessModel.id] }; const mockProperties: EntityProperties = { /* cspell: disable-next-line */ 'mockprop': { 'id': 'mockprop', 'name': 'mock-variable', 'type': 'string', 'required': false, 'value': '' } }; const newState = processEntitiesReducer(initialState, new processVariablesActions.UpdateProcessVariablesAction({ modelId: mockProcessModel.id, processId, properties: mockProperties })); const updatedMappings: ServicesParameterMappings = { 'taskId': { inputs: { 'input-param-2': { 'type': MappingType.variable, 'value': 'mock-variable' } } } }; expect(newState.entities[mockProcessModel.id].extensions[processId].mappings).toEqual(updatedMappings); }); it('should remove empty element mappings if process variable is renamed', () => { initialState = { ...initialProcessEntitiesState, entities: { [mockProcessModel.id]: mockProcessModel }, ids: [mockProcessModel.id] }; const mockProperties: EntityProperties = { /* cspell: disable-next-line */ 'mockprop': { 'id': 'mockprop', 'name': 'mock-variable-updated', 'type': 'string', 'required': false, 'value': '' }, /* cspell: disable-next-line */ 'mockprop2': { 'id': 'mockprop2', 'name': 'beautiful-variable-updated', 'type': 'string', 'required': false, 'value': '' }, /* cspell: disable-next-line */ 'mockprop3': { 'id': 'mockprop3', 'name': 'terrifying-variable-type-changed', 'type': 'boolean', 'required': false, 'value': '' } }; const newState = processEntitiesReducer(initialState, new processVariablesActions.UpdateProcessVariablesAction({ modelId: mockProcessModel.id, processId, properties: mockProperties })); expect(newState.entities[mockProcessModel.id].extensions[processId].mappings).toEqual({}); }); it('should remove empty element mappings if process variable is deleted', () => { initialState = { ...initialProcessEntitiesState, entities: { [mockProcessModel.id]: mockProcessModel }, ids: [mockProcessModel.id] }; /* cspell: disable-next-line */ const mockProperties: EntityProperties = {}; const newState = processEntitiesReducer(initialState, new processVariablesActions.UpdateProcessVariablesAction({ modelId: mockProcessModel.id, processId, properties: mockProperties })); expect(newState.entities[mockProcessModel.id].extensions[processId].mappings).toEqual({}); }); }); it('should delete the extension if pools getting deleted', () => { initialState = { ...initialProcessEntitiesState, entities: { [mockProcessModel.id]: mockProcessModel }, ids: [mockProcessModel.id] }; const expected = { ...initialState, entities: { ...initialState.entities, 'id1': { ...initialState.entities.id1, extensions: {} } } }; const newState = processEntitiesReducer(initialState, new DeleteProcessExtensionAction('id1', 'Process_12345678')); expect(newState).toEqual(expected); }); it('should handle UPDATE_TASK_TEMPLATE', () => { const elementId = 'UserTask_0o7efx6'; const processes = [{ ...process, extensions: { [processId]: { mappings: {}, properties: {}, constants: {}, templates: {} } } }]; let newState = processEntitiesReducer(initialState, <GetProcessesSuccessAction>{ type: GET_PROCESSES_SUCCESS, processes }); newState = processEntitiesReducer(newState, <UpdateUserTaskTemplateAction>{ type: UPDATE_TASK_TEMPLATE, modelId: process.id, processId: processId, userTaskId: elementId, taskTemplate: { assignee: { type: TaskTemplateType.file, value: 'file://myFile.bin' }, candidate: { type: TaskTemplateType.file, value: 'file://myFile.bin' } }, }); expect(newState.entities[process.id].extensions[processId].templates).toEqual({ tasks: { [elementId]: { assignee: { type: TaskTemplateType.file, value: 'file://myFile.bin' }, candidate: { type: TaskTemplateType.file, value: 'file://myFile.bin' } } }, default: {} }); newState = processEntitiesReducer(newState, <UpdateUserTaskTemplateAction>{ type: UPDATE_TASK_TEMPLATE, modelId: process.id, processId: processId, userTaskId: elementId, taskTemplate: { type: TaskTemplateType.file, value: '' } }); expect(newState.entities[process.id].extensions[processId].templates).toEqual({ tasks: {}, default: {} }); }); });
the_stack
export const fetchBBB = name => { const lookupName = name.toUpperCase(); const BBB = igemBackbones[lookupName]; if (BBB) { return BBB; } else { console.warn( `Your backbone input ${name} did not match the name of any iGEM Backbone packaged with this library. Please check if the backbone you are using is listed at https://parts.igem.org/Plasmid_backbones/Assembly. If you are using a custom backbone please be aware that this library does not check for the validity of your prefix and suffix. You can read more about prefixes and suffixes here: http://parts.igem.org/Help:Prefix-Suffix.` ); return name; } }; export const igemBackbones = { //http://parts.igem.org/wiki/index.php?title=Part:pSB1A3 PSB1A3: `tactagtagcggccgctgcagtccggcaaaaaagggcaaggtgtcaccaccctgccctttttctttaaaaccgaaaagattacttcgcgttatgcaggct tcctcgctcactgactcgctgcgctcggtcgttcggctgcggcgagcggtatcagctcactcaaaggcggtaatacggttatccacagaatcaggggata acgcaggaaagaacatgtgagcaaaaggccagcaaaaggccaggaaccgtaaaaaggccgcgttgctggcgtttttccacaggctccgcccccctgacga gcatcacaaaaatcgacgctcaagtcagaggtggcgaaacccgacaggactataaagataccaggcgtttccccctggaagctccctcgtgcgctctcct gttccgaccctgccgcttaccggatacctgtccgcctttctcccttcgggaagcgtggcgctttctcatagctcacgctgtaggtatctcagttcggtgt aggtcgttcgctccaagctgggctgtgtgcacgaaccccccgttcagcccgaccgctgcgccttatccggtaactatcgtcttgagtccaacccggtaag acacgacttatcgccactggcagcagccactggtaacaggattagcagagcgaggtatgtaggcggtgctacagagttcttgaagtggtggcctaactac ggctacactagaagaacagtatttggtatctgcgctctgctgaagccagttaccttcggaaaaagagttggtagctcttgatccggcaaacaaaccaccg ctggtagcggtggtttttttgtttgcaagcagcagattacgcgcagaaaaaaaggatctcaagaagatcctttgatcttttctacggggtctgacgctca gtggaacgaaaactcacgttaagggattttggtcatgagattatcaaaaaggatcttcacctagatccttttaaattaaaaatgaagttttaaatcaatc taaagtatatatgagtaaacttggtctgacagttaccaatgcttaatcagtgaggcacctatctcagcgatctgtctatttcgttcatccatagttgcct gactccccgtcgtgtagataactacgatacgggagggcttaccatctggccccagtgctgcaatgataccgcgagacccacgctcaccggctccagattt atcagcaataaaccagccagccggaagggccgagcgcagaagtggtcctgcaactttatccgcctccatccagtctattaattgttgccgggaagctaga gtaagtagttcgccagttaatagtttgcgcaacgttgttgccattgctacaggcatcgtggtgtcacgctcgtcgtttggtatggcttcattcagctccg gttcccaacgatcaaggcgagttacatgatcccccatgttgtgcaaaaaagcggttagctccttcggtcctccgatcgttgtcagaagtaagttggccgc agtgttatcactcatggttatggcagcactgcataattctcttactgtcatgccatccgtaagatgcttttctgtgactggtgagtactcaaccaagtca ttctgagaatagtgtatgcggcgaccgagttgctcttgcccggcgtcaatacgggataataccgcgccacatagcagaactttaaaagtgctcatcattg gaaaacgttcttcggggcgaaaactctcaaggatcttaccgctgttgagatccagttcgatataacccactcgtgcacccaactgatcttcagcatcttt tactttcaccagcgtttctgggtgagcaaaaacaggaaggcaaaatgccgcaaaaaagggaataagggcgacacggaaatgttgaatactcatactcttc ctttttcaatattattgaagcatttatcagggttattgtctcatgagcggatacatatttgaatgtatttagaaaaataaacaaataggggttccgcgca catttccccgaaaagtgccacctgacgtctaagaaaccattattatcatgacattaacctataaaaataggcgtatcacgaggcagaatttcagataaaa aaaatccttagctttcgctaaggatgatttctggaattcgcggccgcttctagag`, //http://parts.igem.org/wiki/index.php?title=Part:pSB1C3 PSB1C3: `tactagtagcggccgctgcagtccggcaaaaaagggcaaggtgtcaccaccctgccctttttctttaaaaccgaaaagattacttcgcgttatgcaggct tcctcgctcactgactcgctgcgctcggtcgttcggctgcggcgagcggtatcagctcactcaaaggcggtaatacggttatccacagaatcaggggata acgcaggaaagaacatgtgagcaaaaggccagcaaaaggccaggaaccgtaaaaaggccgcgttgctggcgtttttccacaggctccgcccccctgacga gcatcacaaaaatcgacgctcaagtcagaggtggcgaaacccgacaggactataaagataccaggcgtttccccctggaagctccctcgtgcgctctcct gttccgaccctgccgcttaccggatacctgtccgcctttctcccttcgggaagcgtggcgctttctcatagctcacgctgtaggtatctcagttcggtgt aggtcgttcgctccaagctgggctgtgtgcacgaaccccccgttcagcccgaccgctgcgccttatccggtaactatcgtcttgagtccaacccggtaag acacgacttatcgccactggcagcagccactggtaacaggattagcagagcgaggtatgtaggcggtgctacagagttcttgaagtggtggcctaactac ggctacactagaagaacagtatttggtatctgcgctctgctgaagccagttaccttcggaaaaagagttggtagctcttgatccggcaaacaaaccaccg ctggtagcggtggtttttttgtttgcaagcagcagattacgcgcagaaaaaaaggatctcaagaagatcctttgatcttttctacggggtctgacgctca gtggaacgaaaactcacgttaagggattttggtcatgagattatcaaaaaggatcttcacctagatccttttaaattaaaaatgaagttttaaatcaatc taaagtatatatgagtaaacttggtctgacagctcgaggcttggattctcaccaataaaaaacgcccggcggcaaccgagcgttctgaacaaatccagat ggagttctgaggtcattactggatctatcaacaggagtccaagcgagctcgatatcaaattacgccccgccctgccactcatcgcagtactgttgtaatt cattaagcattctgccgacatggaagccatcacaaacggcatgatgaacctgaatcgccagcggcatcagcaccttgtcgccttgcgtataatatttgcc catggtgaaaacgggggcgaagaagttgtccatattggccacgtttaaatcaaaactggtgaaactcacccagggattggctgagacgaaaaacatattc tcaataaaccctttagggaaataggccaggttttcaccgtaacacgccacatcttgcgaatatatgtgtagaaactgccggaaatcgtcgtggtattcac tccagagcgatgaaaacgtttcagtttgctcatggaaaacggtgtaacaagggtgaacactatcccatatcaccagctcaccgtctttcattgccatacg aaattccggatgagcattcatcaggcgggcaagaatgtgaataaaggccggataaaacttgtgcttatttttctttacggtctttaaaaaggccgtaata tccagctgaacggtctggttataggtacattgagcaactgactgaaatgcctcaaaatgttctttacgatgccattgggatatatcaacggtggtatatc cagtgatttttttctccattttagcttccttagctcctgaaaatctcgataactcaaaaaatacgcccggtagtgatcttatttcattatggtgaaagtt ggaacctcttacgtgcccgatcaactcgagtgccacctgacgtctaagaaaccattattatcatgacattaacctataaaaataggcgtatcacgaggca gaatttcagataaaaaaaatccttagctttcgctaaggatgatttctggaattcgcggccgcttctagag`, //http://parts.igem.org/wiki/index.php?title=Part:pSB1K3 PSB1K3: `tactagtagcggccgctgcagtccggcaaaaaagggcaaggtgtcaccaccctgccctttttctttaaaaccgaaaagattacttcgcgttatgcaggct tcctcgctcactgactcgctgcgctcggtcgttcggctgcggcgagcggtatcagctcactcaaaggcggtaatacggttatccacagaatcaggggata acgcaggaaagaacatgtgagcaaaaggccagcaaaaggccaggaaccgtaaaaaggccgcgttgctggcgtttttccacaggctccgcccccctgacga gcatcacaaaaatcgacgctcaagtcagaggtggcgaaacccgacaggactataaagataccaggcgtttccccctggaagctccctcgtgcgctctcct gttccgaccctgccgcttaccggatacctgtccgcctttctcccttcgggaagcgtggcgctttctcatagctcacgctgtaggtatctcagttcggtgt aggtcgttcgctccaagctgggctgtgtgcacgaaccccccgttcagcccgaccgctgcgccttatccggtaactatcgtcttgagtccaacccggtaag acacgacttatcgccactggcagcagccactggtaacaggattagcagagcgaggtatgtaggcggtgctacagagttcttgaagtggtggcctaactac ggctacactagaagaacagtatttggtatctgcgctctgctgaagccagttaccttcggaaaaagagttggtagctcttgatccggcaaacaaaccaccg ctggtagcggtggtttttttgtttgcaagcagcagattacgcgcagaaaaaaaggatctcaagaagatcctttgatcttttctacggggtctgacgctca gtggaacgaaaactcacgttaagggattttggtcatgagattatcaaaaaggatcttcacctagatccttttaaattaaaaatgaagttttaaatcaatc taaagtatatatgagtaaacttggtctgacagctcgagtcccgtcaagtcagcgtaatgctctgccagtgttacaaccaattaaccaattctgattagaa aaactcatcgagcatcaaatgaaactgcaatttattcatatcaggattatcaataccatatttttgaaaaagccgtttctgtaatgaaggagaaaactca ccgaggcagttccataggatggcaagatcctggtatcggtctgcgattccgactcgtccaacatcaatacaacctattaatttcccctcgtcaaaaataa ggttatcaagtgagaaatcaccatgagtgacgactgaatccggtgagaatggcaaaagcttatgcatttctttccagacttgttcaacaggccagccatt acgctcgtcatcaaaatcactcgcatcaaccaaaccgttattcattcgtgattgcgcctgagcgagacgaaatacgcgatcgctgttaaaaggacaatta caaacaggaatcgaatgcaaccggcgcaggaacactgccagcgcatcaacaatattttcacctgaatcaggatattcttctaatacctggaatgctgttt tcccggggatcgcagtggtgagtaaccatgcatcatcaggagtacggataaaatgcttgatggtcggaagaggcataaattccgtcagccagtttagtct gaccatctcatctgtaacatcattggcaacgctacctttgccatgtttcagaaacaactctggcgcatcgggcttcccatacaatcgatagattgtcgca cctgattgcccgacattatcgcgagcccatttatacccatataaatcagcatccatgttggaatttaatcgcggcctggagcaagacgtttcccgttgaa tatggctcataacaccccttgtattactgtttatgtaagcagacagttttattgttcatgatgatatatttttatcttgtgcaatgtaacatcagagatt ttgagacacaacgtggctttgttgaataaatcgaacttttgctgagttgaaggatcagctcgagtgccacctgacgtctaagaaaccattattatcatga cattaacctataaaaataggcgtatcacgaggcagaatttcagataaaaaaaatccttagctttcgctaaggatgatttctggaattcgcggccgcttct agag`, //http://parts.igem.org/wiki/index.php?title=Part:pSB1T3 PSB1T3: `tactagtagcggccgctgcagtccggcaaaaaagggcaaggtgtcaccaccctgccctttttctttaaaaccgaaaagattacttcgcgttatgcaggct tcctcgctcactgactcgctgcgctcggtcgttcggctgcggcgagcggtatcagctcactcaaaggcggtaatacggttatccacagaatcaggggata acgcaggaaagaacatgtgagcaaaaggccagcaaaaggccaggaaccgtaaaaaggccgcgttgctggcgtttttccacaggctccgcccccctgacga gcatcacaaaaatcgacgctcaagtcagaggtggcgaaacccgacaggactataaagataccaggcgtttccccctggaagctccctcgtgcgctctcct gttccgaccctgccgcttaccggatacctgtccgcctttctcccttcgggaagcgtggcgctttctcatagctcacgctgtaggtatctcagttcggtgt aggtcgttcgctccaagctgggctgtgtgcacgaaccccccgttcagcccgaccgctgcgccttatccggtaactatcgtcttgagtccaacccggtaag acacgacttatcgccactggcagcagccactggtaacaggattagcagagcgaggtatgtaggcggtgctacagagttcttgaagtggtggcctaactac ggctacactagaagaacagtatttggtatctgcgctctgctgaagccagttaccttcggaaaaagagttggtagctcttgatccggcaaacaaaccaccg ctggtagcggtggtttttttgtttgcaagcagcagattacgcgcagaaaaaaaggatctcaagaagatcctttgatcttttctacggggtctgacgctca gtggaacgaaaactcacgttaagggattttggtcatgagattatcaaaaaggatcttcacctagatccttttaaattaaaaatgaagttttaaatcaatc taaagtatatatgagtaaacttggtctgacagctcgagattctcatgtttgacagcttatcatcgataagctttaatgcggtagtttatcacagttaaat tgctaacgcagtcaggcaccgtgtatgaaatctaacaatgcgctcatcgtcatcctcggcaccgtcaccctggatgctgtaggcataggcttggttatgc cggtactgccgggcctcttgcgggatatcgtccattccgacagcatcgccagtcactatggcgtgctgctagcgctatatgcgttgatgcaatttctatg cgcacccgttctcggagcactgtccgaccgctttggccgccgcccagtcctgctcgcttcgctacttggagccactatcgactacgcgatcatggcgacc acacccgtcctgtggatcctctacgccggacgcatcgtggccggcatcaccggcgccacaggtgcggttgctggcgcctatatcgccgacatcaccgatg gggaagatcgggctcgccacttcgggctcatgagcgcttgtttcggcgtgggtatggtggcaggccccgtggccgggggactgttgggcgccatctcctt gcatgcaccattccttgcggcggcggtgctcaacggcctcaacctactactgggctgcttcctaatgcaggagtcgcataagggagagcgtcgaccgatg cccttgagagccttcaacccagtcagctccttccggtgggcgcggggcatgactatcgtcgccgcacttatgactgtcttctttatcatgcaactcgtag gacaggtgccggcagcgctctgggtcattttcggcgaggaccgctttcgctggagcgcgacgatgatcggcctgtcgcttgcggtattcggaatcttgca cgccctcgctcaagccttcgtcactggtcccgccaccaaacgtttcggcgagaagcaggccattatcgccggcatggcggccgacgcgctgggctacgtc ttgctggcgttcgcgacgcgaggctggatggccttccccattatgattcttctcgcttccggcggcatcgggatgcccgcgttgcaggccatgctgtcca ggcaggtagatgacgaccatcagggacagcttcaaggatcgctcgcggctcttaccagcctaacttcgatcactggaccgctgatcgtcacggcgattta tgccgcctcggcgagcacatggaacgggttggcatggattgtaggcgccgccctataccttgtctgcctccccgcgttgcgtcgcggtgcatggagccgg gccacctcgacctaactcgagtgccacctgacgtctaagaaaccattattatcatgacattaacctataaaaataggcgtatcacgaggcagaatttcag ataaaaaaaatccttagctttcgctaaggatgatttctggaattcgcggccgcttctagag`, //http://parts.igem.org/wiki/index.php?title=Part:pSB1A7 PSB1A7: `actagtagcggccgctgcaggcttataaacgcagaaaggcccacccgaaggtgagccagtgtgactctagtagagagcgttcaccgacaaacaacagata aaacgaaaggcccagtctttcgactgagcctttcgttttatttgatgcctgggtgcagtccggcaaaaaaacgggcaaggtgtcaccaccctgccctttt tctttaaaaccgaaaagattacttcgcgttatgcaggcttcctcgctcactgactcgctgcgctcggtcgttcggctgcggcgagcggtatcagctcact caaaggcggtaatacggttatccacagaatcaggggataacgcaggaaagaacatgtgagcaaaaggccagcaaaaggccaggaaccgtaaaaaggccgc gttgctggcgtttttccataggctccgcccccctgacgagcatcacaaaaatcgacgctcaagtcagaggtggcgaaacccgacaggactataaagatac caggcgtttccccctggaagctccctcgtgcgctctcctgttccgaccctgccgcttaccggatacctgtccgcctttctcccttcgggaagcgtggcgc tttctcatagctcacgctgtaggtatctcagttcggtgtaggtcgttcgctccaagctgggctgtgtgcacgaaccccccgttcagcccgaccgctgcgc cttatccggtaactatcgtcttgagtccaacccggtaagacacgacttatcgccactggcagcagccactggtaacaggattagcagagcgaggtatgta ggcggtgctacagagttcttgaagtggtggcctaactacggctacactagaaggacagtatttggtatctgcgctctgctgaagccagttaccttcggaa aaagagttggtagctcttgatccggcaaacaaaccaccgctggtagcggtggtttttttgtttgcaagcagcagattacgcgcagaaaaaaaggatctca agaagatcctttgatcttttctacggggtctgacgctcagtggaacgaaaactcacgttaagggattttggtcatgagattatcaaaaaggatcttcacc tagatccttttaaattaaaaatgaagttttaaatcaatctaaagtatatatgagtaaacttggtctgacagttaccaatgcttaatcagtgaggcaccta tctcagcgatctgtctatttcgttcatccatagttgcctgactccccgtcgtgtagataactacgatacgggagggcttaccatctggccccagtgctgc aatgataccgcgagacccacgctcaccggctccagatttatcagcaataaaccagccagccggaagggccgagcgcagaagtggtcctgcaactttatcc gcctccatccagtctattaattgttgccgggaagctagagtaagtagttcgccagttaatagtttgcgcaacgttgttgccattgctacaggcatcgtgg tgtcacgctcgtcgtttggtatggcttcattcagctccggttcccaacgatcaaggcgagttacatgatcccccatgttgtgcaaaaaagcggttagctc cttcggtcctccgatcgttgtcagaagtaagttggccgcagtgttatcactcatggttatggcagcactgcataattctcttactgtcatgccatccgta agatgcttttctgtgactggtgagtactcaaccaagtcattctgagaatagtgtatgcggcgaccgagttgctcttgcccggcgtcaatacgggataata ccgcgccacatagcagaactttaaaagtgctcatcattggaaaacgttcttcggggcgaaaactctcaaggatcttaccgctgttgagatccagttcgat gtaacccactcgtgcacccaactgatcttcagcatcttttactttcaccagcgtttctgggtgagcaaaaacaggaaggcaaaatgccgcaaaaaaggga ataagggcgacacggaaatgttgaatactcatactcttcctttttcaatattattgaagcatttatcagggttattgtctcatgagcggatacatatttg aatgtatttagaaaaataaacaaataggggttccgcgcacatttccccgaaaagtgccacctgacgtctaagaaaccattattatcatgacattaaccta taaaaataggcgtatcacgaggcagaatttcagataaaaaaaatccttagctttcgctaaggatgatttctggaattgccaggcatcaaataaaacgaaa ggctcagtcgaaagactgggcctttcgttttatctgttgtttgtcggtgaacgctctctactagagtcacactggctcaccttcgggtgggcctttctgc gtttatagcagaattcgcggccgcttctaga`, //http://parts.igem.org/wiki/index.php?title=Part:pSB1AC3 PSB1AC3: `tactagtagcggccgctgcagtccggcaaaaaaacgggcaaggtgtcaccaccctgccctttttctttaaaaccgaaaagattacttcgcgttatgcagg cttcctcgctcactgactcgctgcgctcggtcgttcggctgcggcgagcggtatcagctcactcaaaggcggtaatacggttatccacagaatcagggga taacgcaggaaagaacatgtgagcaaaaggccagcaaaaggccaggaaccgtaaaaaggccgcgttgctggcgtttttccataggctccgcccccctgac gagcatcacaaaaatcgacgctcaagtcagaggtggcgaaacccgacaggactataaagataccaggcgtttccccctggaagctccctcgtgcgctctc ctgttccgaccctgccgcttaccggatacctgtccgcctttctcccttcgggaagcgtggcgctttctcatagctcacgctgtaggtatctcagttcggt gtaggtcgttcgctccaagctgggctgtgtgcacgaaccccccgttcagcccgaccgctgcgccttatccggtaactatcgtcttgagtccaacccggta agacacgacttatcgccactggcagcagccactggtaacaggattagcagagcgaggtatgtaggcggtgctacagagttcttgaagtggtggcctaact acggctacactagaaggacagtatttggtatctgcgctctgctgaagccagttaccttcggaaaaagagttggtagctcttgatccggcaaacaaaccac cgctggtagcggtggtttttttgtttgcaagcagcagattacgcgcagaaaaaaaggatctcaagaagatcctttgatcttttctacggggtctgacgct cagtggaacgaaaactcacgttaagggattttggtcatgagattatcaaaaaggatcttcacctagatccttttaaattaaaaatgaagttttaaatcaa tctaaagtatatatgagtaaacttggtctgacagctcgaggcttggattctcaccaataaaaaacgcccggcggcaaccgagcgttctgaacaaatccag atggagttctgaggtcattactggatctatcaacaggagtccaagcgagctcgatatcaaattacgccccgccctgccactcatcgcagtactgttgtaa ttcattaagcattctgccgacatggaagccatcacaaacggcatgatgaacctgaatcgccagcggcatcagcaccttgtcgccttgcgtataatatttg cccatggtgaaaacgggggcgaagaagttgtccatattggccacgtttaaatcaaaactggtgaaactcacccagggattggctgagacgaaaaacatat tctcaataaaccctttagggaaataggccaggttttcaccgtaacacgccacatcttgcgaatatatgtgtagaaactgccggaaatcgtcgtggtattc actccagagcgatgaaaacgtttcagtttgctcatggaaaacggtgtaacaagggtgaacactatcccatatcaccagctcaccgtctttcattgccata cgaaattccggatgagcattcatcaggcgggcaagaatgtgaataaaggccggataaaacttgtgcttatttttctttacggtctttaaaaaggccgtaa tatccagctgaacggtctggttataggtacattgagcaactgactgaaatgcctcaaaatgttctttacgatgccattgggatatatcaacggtggtata tccagtgatttttttctccattttagcttccttagctcctgaaaatctcgataactcaaaaaatacgcccggtagtgatcttatttcattatggtgaaag ttggaacctcttacgtgcccgatcaactcgagttaccaatgcttaatcagtgaggcacctatctcagcgatctgtctatttcgttcatccatagttgcct gactccccgtcgtgtagataactacgatacgggagggcttaccatctggccccagtgctgcaatgataccgcgagacccacgctcaccggctccagattt atcagcaataaaccagccagccggaagggccgagcgcagaagtggtcctgcaactttatccgcctccatccagtctattaattgttgccgggaagctaga gtaagtagttcgccagttaatagtttgcgcaacgttgttgccattgctacaggcatcgtggtgtcacgctcgtcgtttggtatggcttcattcagctccg gttcccaacgatcaaggcgagttacatgatcccccatgttgtgcaaaaaagcggttagctccttcggtcctccgatcgttgtcagaagtaagttggccgc agtgttatcactcatggttatggcagcactgcataattctcttactgtcatgccatccgtaagatgcttttctgtgactggtgagtactcaaccaagtca ttctgagaatagtgtatgcggcgaccgagttgctcttgcccggcgtcaatacgggataataccgcgccacatagcagaactttaaaagtgctcatcattg gaaaacgttcttcggggcgaaaactctcaaggatcttaccgctgttgagatccagttcgatgtaacccactcgtgcacccaactgatcttcagcatcttt tactttcaccagcgtttctgggtgagcaaaaacaggaaggcaaaatgccgcaaaaaagggaataagggcgacacggaaatgttgaatactcatactcttc ctttttcaatattattgaagcatttatcagggttattgtctcatgagcggatacatatttgaatgtatttagaaaaataaacaaataggggttccgcgca catttccccgaaaagtgccacctgacgtctaagaaaccattattatcatgacattaacctataaaaataggcgtatcacgaggcagaatttcagataaaa aaaatccttagctttcgctaaggatgatttctggaattcgcggccgcttctagag`, //http://parts.igem.org/wiki/index.php?title=Part:pSB1AK3 PSB1AK3: `tactagtagcggccgctgcagtccggcaaaaaaacgggcaaggtgtcaccaccctgccctttttctttaaaaccgaaaagattacttcgcgttatgcagg cttcctcgctcactgactcgctgcgctcggtcgttcggctgcggcgagcggtatcagctcactcaaaggcggtaatacggttatccacagaatcagggga taacgcaggaaagaacatgtgagcaaaaggccagcaaaaggccaggaaccgtaaaaaggccgcgttgctggcgtttttccataggctccgcccccctgac gagcatcacaaaaatcgacgctcaagtcagaggtggcgaaacccgacaggactataaagataccaggcgtttccccctggaagctccctcgtgcgctctc ctgttccgaccctgccgcttaccggatacctgtccgcctttctcccttcgggaagcgtggcgctttctcatagctcacgctgtaggtatctcagttcggt gtaggtcgttcgctccaagctgggctgtgtgcacgaaccccccgttcagcccgaccgctgcgccttatccggtaactatcgtcttgagtccaacccggta agacacgacttatcgccactggcagcagccactggtaacaggattagcagagcgaggtatgtaggcggtgctacagagttcttgaagtggtggcctaact acggctacactagaaggacagtatttggtatctgcgctctgctgaagccagttaccttcggaaaaagagttggtagctcttgatccggcaaacaaaccac cgctggtagcggtggtttttttgtttgcaagcagcagattacgcgcagaaaaaaaggatctcaagaagatcctttgatcttttctacggggtctgacgct cagtggaacgaaaactcacgttaagggattttggtcatgagattatcaaaaaggatcttcacctagatccttttaaattaaaaatgaagttttaaatcaa tctaaagtatatatgagtaaacttggtctgacagctcgagtcccgtcaagtcagcgtaatgctctgccagtgttacaaccaattaaccaattctgattag aaaaactcatcgagcatcaaatgaaactgcaatttattcatatcaggattatcaataccatatttttgaaaaagccgtttctgtaatgaaggagaaaact caccgaggcagttccataggatggcaagatcctggtatcggtctgcgattccgactcgtccaacatcaatacaacctattaatttcccctcgtcaaaaat aaggttatcaagtgagaaatcaccatgagtgacgactgaatccggtgagaatggcaaaagcttatgcatttctttccagacttgttcaacaggccagcca ttacgctcgtcatcaaaatcactcgcatcaaccaaaccgttattcattcgtgattgcgcctgagcgagacgaaatacgcgatcgctgttaaaaggacaat tacaaacaggaatcgaatgcaaccggcgcaggaacactgccagcgcatcaacaatattttcacctgaatcaggatattcttctaatacctggaatgctgt tttcccggggatcgcagtggtgagtaaccatgcatcatcaggagtacggataaaatgcttgatggtcggaagaggcataaattccgtcagccagtttagt ctgaccatctcatctgtaacatcattggcaacgctacctttgccatgtttcagaaacaactctggcgcatcgggcttcccatacaatcgatagattgtcg cacctgattgcccgacattatcgcgagcccatttatacccatataaatcagcatccatgttggaatttaatcgcggcctggagcaagacgtttcccgttg aatatggctcataacaccccttgtattactgtttatgtaagcagacagttttattgttcatgatgatatatttttatcttgtgcaatgtaacatcagaga ttttgagacacaacgtggctttgttgaataaatcgaacttttgctgagttgaaggatcagctcgagttaccaatgcttaatcagtgaggcacctatctca gcgatctgtctatttcgttcatccatagttgcctgactccccgtcgtgtagataactacgatacgggagggcttaccatctggccccagtgctgcaatga taccgcgagacccacgctcaccggctccagatttatcagcaataaaccagccagccggaagggccgagcgcagaagtggtcctgcaactttatccgcctc catccagtctattaattgttgccgggaagctagagtaagtagttcgccagttaatagtttgcgcaacgttgttgccattgctacaggcatcgtggtgtca cgctcgtcgtttggtatggcttcattcagctccggttcccaacgatcaaggcgagttacatgatcccccatgttgtgcaaaaaagcggttagctccttcg gtcctccgatcgttgtcagaagtaagttggccgcagtgttatcactcatggttatggcagcactgcataattctcttactgtcatgccatccgtaagatg cttttctgtgactggtgagtactcaaccaagtcattctgagaatagtgtatgcggcgaccgagttgctcttgcccggcgtcaatacgggataataccgcg ccacatagcagaactttaaaagtgctcatcattggaaaacgttcttcggggcgaaaactctcaaggatcttaccgctgttgagatccagttcgatgtaac ccactcgtgcacccaactgatcttcagcatcttttactttcaccagcgtttctgggtgagcaaaaacaggaaggcaaaatgccgcaaaaaagggaataag ggcgacacggaaatgttgaatactcatactcttcctttttcaatattattgaagcatttatcagggttattgtctcatgagcggatacatatttgaatgt atttagaaaaataaacaaataggggttccgcgcacatttccccgaaaagtgccacctgacgtctaagaaaccattattatcatgacattaacctataaaa ataggcgtatcacgaggcagaatttcagataaaaaaaatccttagctttcgctaaggatgatttctggaattcgcggccgcttctagag`, //http://parts.igem.org/wiki/index.php?title=Part:pSB1AT3 PSB1AT3: `tactagtagcggccgctgcagtccggcaaaaaaacgggcaaggtgtcaccaccctgccctttttctttaaaaccgaaaagattacttcgcgttatgcagg cttcctcgctcactgactcgctgcgctcggtcgttcggctgcggcgagcggtatcagctcactcaaaggcggtaatacggttatccacagaatcagggga taacgcaggaaagaacatgtgagcaaaaggccagcaaaaggccaggaaccgtaaaaaggccgcgttgctggcgtttttccataggctccgcccccctgac gagcatcacaaaaatcgacgctcaagtcagaggtggcgaaacccgacaggactataaagataccaggcgtttccccctggaagctccctcgtgcgctctc ctgttccgaccctgccgcttaccggatacctgtccgcctttctcccttcgggaagcgtggcgctttctcatagctcacgctgtaggtatctcagttcggt gtaggtcgttcgctccaagctgggctgtgtgcacgaaccccccgttcagcccgaccgctgcgccttatccggtaactatcgtcttgagtccaacccggta agacacgacttatcgccactggcagcagccactggtaacaggattagcagagcgaggtatgtaggcggtgctacagagttcttgaagtggtggcctaact acggctacactagaaggacagtatttggtatctgcgctctgctgaagccagttaccttcggaaaaagagttggtagctcttgatccggcaaacaaaccac cgctggtagcggtggtttttttgtttgcaagcagcagattacgcgcagaaaaaaaggatctcaagaagatcctttgatcttttctacggggtctgacgct cagtggaacgaaaactcacgttaagggattttggtcatgagattatcaaaaaggatcttcacctagatccttttaaattaaaaatgaagttttaaatcaa tctaaagtatatatgagtaaacttggtctgacagctcgagattctcatgtttgacagcttatcatcgataagctttaatgcggtagtttatcacagttaa attgctaacgcagtcaggcaccgtgtatgaaatctaacaatgcgctcatcgtcatcctcggcaccgtcaccctggatgctgtaggcataggcttggttat gccggtactgccgggcctcttgcgggatatcgtccattccgacagcatcgccagtcactatggcgtgctgctagcgctatatgcgttgatgcaatttcta tgcgcacccgttctcggagcactgtccgaccgctttggccgccgcccagtcctgctcgcttcgctacttggagccactatcgactacgcgatcatggcga ccacacccgtcctgtggatcctctacgccggacgcatcgtggccggcatcaccggcgccacaggtgcggttgctggcgcctatatcgccgacatcaccga tggggaagatcgggctcgccacttcgggctcatgagcgcttgtttcggcgtgggtatggtggcaggccccgtggccgggggactgttgggcgccatctcc ttgcatgcaccattccttgcggcggcggtgctcaacggcctcaacctactactgggctgcttcctaatgcaggagtcgcataagggagagcgtcgaccga tgcccttgagagccttcaacccagtcagctccttccggtgggcgcggggcatgactatcgtcgccgcacttatgactgtcttctttatcatgcaactcgt aggacaggtgccggcagcgctctgggtcattttcggcgaggaccgctttcgctggagcgcgacgatgatcggcctgtcgcttgcggtattcggaatcttg cacgccctcgctcaagccttcgtcactggtcccgccaccaaacgtttcggcgagaagcaggccattatcgccggcatggcggccgacgcgctgggctacg tcttgctggcgttcgcgacgcgaggctggatggccttccccattatgattcttctcgcttccggcggcatcgggatgcccgcgttgcaggccatgctgtc caggcaggtagatgacgaccatcagggacagcttcaaggatcgctcgcggctcttaccagcctaacttcgatcactggaccgctgatcgtcacggcgatt tatgccgcctcggcgagcacatggaacgggttggcatggattgtaggcgccgccctataccttgtctgcctccccgcgttgcgtcgcggtgcatggagcc gggccacctcgacctaactcgagttaccaatgcttaatcagtgaggcacctatctcagcgatctgtctatttcgttcatccatagttgcctgactccccg tcgtgtagataactacgatacgggagggcttaccatctggccccagtgctgcaatgataccgcgagacccacgctcaccggctccagatttatcagcaat aaaccagccagccggaagggccgagcgcagaagtggtcctgcaactttatccgcctccatccagtctattaattgttgccgggaagctagagtaagtagt tcgccagttaatagtttgcgcaacgttgttgccattgctacaggcatcgtggtgtcacgctcgtcgtttggtatggcttcattcagctccggttcccaac gatcaaggcgagttacatgatcccccatgttgtgcaaaaaagcggttagctccttcggtcctccgatcgttgtcagaagtaagttggccgcagtgttatc actcatggttatggcagcactgcataattctcttactgtcatgccatccgtaagatgcttttctgtgactggtgagtactcaaccaagtcattctgagaa tagtgtatgcggcgaccgagttgctcttgcccggcgtcaatacgggataataccgcgccacatagcagaactttaaaagtgctcatcattggaaaacgtt cttcggggcgaaaactctcaaggatcttaccgctgttgagatccagttcgatgtaacccactcgtgcacccaactgatcttcagcatcttttactttcac cagcgtttctgggtgagcaaaaacaggaaggcaaaatgccgcaaaaaagggaataagggcgacacggaaatgttgaatactcatactcttcctttttcaa tattattgaagcatttatcagggttattgtctcatgagcggatacatatttgaatgtatttagaaaaataaacaaataggggttccgcgcacatttcccc gaaaagtgccacctgacgtctaagaaaccattattatcatgacattaacctataaaaataggcgtatcacgaggcagaatttcagataaaaaaaatcctt agctttcgctaaggatgatttctggaattcgcggccgcttctagag`, //http://parts.igem.org/wiki/index.php?title=Part:BBa_K1362091 BBA_K1362091: `tactagtagcggccgctgcagtccggcaaaaaagggcaaggtgtcaccaccctgccctttttctttaaaaccgaaaagattacttcgcgttatgcaggct tcctcgctcactgactcgctgcgctcggtcgttcggctgcggcgagcggtatcagctcactcaaaggcggtaatacggttatccacagaatcaggggata acgcaggaaagaacatgtgagcaaaaggccagcaaaaggccaggaaccgtaaaaaggccgcgttgctggcgtttttccacaggctccgcccccctgacga gcatcacaaaaatcgacgctcaagtcagaggtggcgaaacccgacaggactataaagataccaggcgtttccccctggaagctccctcgtgcgctctcct gttccgaccctgccgcttaccggatacctgtccgcctttctcccttcgggaagcgtggcgctttctcatagctcacgctgtaggtatctcagttcggtgt aggtcgttcgctccaagctgggctgtgtgcacgaaccccccgttcagcccgaccgctgcgccttatccggtaactatcgtcttgagtccaacccggtaag acacgacttatcgccactggcagcagccactggtaacaggattagcagagcgaggtatgtaggcggtgctacagagttcttgaagtggtggcctaactac ggctacactagaagaacagtatttggtatctgcgctctgctgaagccagttaccttcggaaaaagagttggtagctcttgatccggcaaacaaaccaccg ctggtagcggtggtttttttgtttgcaagcagcagattacgcgcagaaaaaaaggatctcaagaagatcctttgatcttttctacggggtctgacgctca gtggaacgaaaactcacgttaagggattttggtcatgagattatcaaaaaggatcttcacctagatccttttaaattaaaaatgaagttttaaatcaatc taaagtatatatgagtaaacttggtctgacagttaccaatgcttaatcagtgaggcacctatctcagcgatctgtctatttcgttcatccatagttgcct gactccccgtcgtgtagataactacgatacgggagggcttaccatctggccccagtgctgcaatgataccgcgagacccacgctcaccggctccagattt atcagcaataaaccagccagccggaagggccgagcgcagaagtggtcctgcaactttatccgcctccatccagtctattaattgttgccgggaagctaga gtaagtagttcgccagttaatagtttgcgcaacgttgttgccattgctacaggcatcgtggtgtcacgctcgtcgtttggtatggcttcattcagctccg gttcccaacgatcaaggcgagttacatgatcccccatgttgtgcaaaaaagcggttagctccttcggtcctccgatcgttgtcagaagtaagttggccgc agtgttatcactcatggttatggcagcactgcataattctcttactgtcatgccatccgtaagatgcttttctgtgactggtgagtactcaaccaagtca ttctgagaatagtgtatgcggcgaccgagttgctcttgcccggcgtcaatacgggataataccgcgccacatagcagaactttaaaagtgctcatcattg gaaaacgttcttcggggcgaaaactctcaaggatcttaccgctgttgagatccagttcgatataacccactcgtgcacccaactgatcttcagcatcttt tactttcaccagcgtttctgggtgagcaaaaacaggaaggcaaaatgccgcaaaaaagggaataagggcgacacggaaatgttgaatactcatactcttc ctttttcaatattattgaagcatttatcagggttattgtctcatgagcggatacatatttgaatgtatttagaaaaataaacaaataggggttccgcgca catttccccgaaaagtgccacctgacgtctaagaaaccattattatcatgacattaacctataaaaataggcgtatcacgaggcagaatttcagataaaa aaaatccttagctttcgctaaggatgatttctggaatttaatacgactcactataggggaattgtgagcggataacaattccccgaattcgcggccgctt ctagag`, //http://parts.igem.org/wiki/index.php?title=Part:BBa_K823055 BBA_K823055: `accggttaatactagtagcggccgctgcagtccggcaaaaaagggcaaggtgtcaccaccctgccctttttctttaaaaccgaaaagattacttcgcgtt atgcaggcttcctcgctcactgactcgctgcgctcggtcgttcggctgcggcgagcggtatcagctcactcaaaggcggtaatacggttatccacagaat caggggataacgcaggaaagaacatgtgagcaaaaggccagcaaaaggccaggaaccgtaaaaaggccgcgttgctggcgtttttccacaggctccgccc ccctgacgagcatcacaaaaatcgacgctcaagtcagaggtggcgaaacccgacaggactataaagataccaggcgtttccccctggaagctccctcgtg cgctctcctgttccgaccctgccgcttaccggatacctgtccgcctttctcccttcgggaagcgtggcgctttctcatagctcacgctgtaggtatctca gttcggtgtaggtcgttcgctccaagctgggctgtgtgcacgaaccccccgttcagcccgaccgctgcgccttatccggtaactatcgtcttgagtccaa cccggtaagacacgacttatcgccactggcagcagccactggtaacaggattagcagagcgaggtatgtaggcggtgctacagagttcttgaagtggtgg cctaactacggctacactagaagaacagtatttggtatctgcgctctgctgaagccagttaccttcggaaaaagagttggtagctcttgatccggcaaac aaaccaccgctggtagcggtggtttttttgtttgcaagcagcagattacgcgcagaaaaaaaggatctcaagaagatcctttgatcttttctacggggtc tgacgctcagtggaacgaaaactcacgttaagggattttggtcatgagattatcaaaaaggatcttcacctagatccttttaaattaaaaatgaagtttt aaatcaatctaaagtatatatgagtaaacttggtctgacagctcgaggcttggattctcaccaataaaaaacgcccggcggcaaccgagcgttctgaaca aatccagatggagttctgaggtcattactggatctatcaacaggagtccaagcgagctcgatatcaaattacgccccgccctgccactcatcgcagtact gttgtaattcattaagcattctgccgacatggaagccatcacaaacggcatgatgaacctgaatcgccagcggcatcagcaccttgtcgccttgcgtata atatttgcccatggtgaaaacgggggcgaagaagttgtccatattggccacgtttaaatcaaaactggtgaaactcacccagggattggctgagacgaaa aacatattctcaataaaccctttagggaaataggccaggttttcaccgtaacacgccacatcttgcgaatatatgtgtagaaactgccggaaatcgtcgt ggtattcactccagagcgatgaaaacgtttcagtttgctcatggaaaacggtgtaacaagggtgaacactatcccatatcaccagctcaccgtctttcat tgccatacgaaattccggatgagcattcatcaggcgggcaagaatgtgaataaaggccggataaaacttgtgcttatttttctttacggtctttaaaaag gccgtaatatccagctgaacggtctggttataggtacattgagcaactgactgaaatgcctcaaaatgttctttacgatgccattgggatatatcaacgg tggtatatccagtgatttttttctccattttagcttccttagctcctgaaaatctcgataactcaaaaaatacgcccggtagtgatcttatttcattatg gtgaaagttggaacctcttacgtgcccgatcaactcgagtgccacctgacgtctaagaaaccattattatcatgacattaacctataaaaataggcgtat cacgaggcagaatttcagataaaaaaaatccttagctttcgctaaggatgatttctggaattcgcggccgcttctagataaggaggaactactatggccg gc` };
the_stack
import { window, commands, Disposable, ExtensionContext, StatusBarAlignment, StatusBarItem, TextDocument, workspace, Position, Range, TextEditor, TextEditorEdit } from 'vscode'; const REGEXP_TOC_START = /\s*<!--(.*)TOC(.*)-->/gi; const REGEXP_TOC_STOP = /\s*<!--(.*)\/TOC(.*)-->/gi; const REGEXP_TOC_CONFIG = /\w+[:=][\w.]+/gi; const REGEXP_TOC_CONFIG_ITEM = /(\w+)[:=]([\w.]+)/; const REGEXP_MARKDOWN_ANCHOR = /^<a id="markdown-.+" name=".+"><\/a\>/; const REGEXP_HEADER = /^(\#{1,6})\s*(.+)/; const REGEXP_CODE_BLOCK1 = /^```/; const REGEXP_CODE_BLOCK2 = /^~~~/; const REGEXP_ANCHOR = /\[.+\]\(#(.+)\)/ const REGEXP_IGNORE_TITLE = /<!-- TOC ignore:true -->/ const DEPTH_FROM = "depthFrom"; const DEPTH_TO = "depthTo"; const INSERT_ANCHOR = "insertAnchor"; const WITH_LINKS = "withLinks"; const ORDERED_LIST = "orderedList"; const UPDATE_ON_SAVE = "updateOnSave"; const ANCHOR_MODE = "anchorMode"; const LOWER_DEPTH_FROM = DEPTH_FROM.toLocaleLowerCase(); const LOWER_DEPTH_TO = DEPTH_TO.toLocaleLowerCase(); const LOWER_INSERT_ANCHOR = INSERT_ANCHOR.toLocaleLowerCase(); const LOWER_WITH_LINKS = WITH_LINKS.toLocaleLowerCase(); const LOWER_ORDERED_LIST = ORDERED_LIST.toLocaleLowerCase(); const LOWER_UPDATE_ON_SAVE = UPDATE_ON_SAVE.toLocaleLowerCase(); const LOWER_ANCHOR_MODE = ANCHOR_MODE.toLocaleLowerCase(); const ANCHOR_MODE_LIST = [ "github.com", "bitbucket.org", "ghost.org", "gitlab.com" ] export function activate(context: ExtensionContext) { // create a MarkdownTocTools let markdownTocTools = new MarkdownTocTools(); let disposable_updateMarkdownToc = commands.registerCommand('extension.updateMarkdownToc', () => { markdownTocTools.updateMarkdownToc(); }); let disposable_deleteMarkdownToc = commands.registerCommand('extension.deleteMarkdownToc', () => { markdownTocTools.deleteMarkdownToc(); }); let disposable_updateMarkdownSections = commands.registerCommand('extension.updateMarkdownSections', () => { markdownTocTools.updateMarkdownSections(); }); let disposable_deleteMarkdownSections = commands.registerCommand('extension.deleteMarkdownSections', () => { markdownTocTools.deleteMarkdownSections(); }); let disposable_saveMarkdownToc = workspace.onDidSaveTextDocument((doc : TextDocument) => { markdownTocTools.notifyDocumentSave(); }); // Add to a list of disposables which are disposed when this extension is deactivated. context.subscriptions.push(disposable_updateMarkdownToc); context.subscriptions.push(disposable_deleteMarkdownToc); context.subscriptions.push(disposable_updateMarkdownSections); context.subscriptions.push(disposable_deleteMarkdownSections); context.subscriptions.push(disposable_saveMarkdownToc); } class MarkdownTocTools { options = { DEPTH_FROM : 1, DEPTH_TO : 6, INSERT_ANCHOR : false, WITH_LINKS : true, ORDERED_LIST : false, UPDATE_ON_SAVE : true, ANCHOR_MODE : ANCHOR_MODE_LIST[0] }; optionsFlag = []; saveBySelf = false; // Public function public updateMarkdownToc(isBySave : boolean = false) { let editor = window.activeTextEditor; let markdownTocTools = this; window.activeTextEditor.edit(function(editBuilder) { let tocRange = markdownTocTools.getTocRange(); markdownTocTools.updateOptions(tocRange); if (isBySave && ((!markdownTocTools.options.UPDATE_ON_SAVE) || (tocRange == null))) return false; let insertPosition = editor.selection.active; // save options, and delete last insert if (tocRange != null) { insertPosition = tocRange.start; editBuilder.delete(tocRange); markdownTocTools.deleteAnchor(editBuilder); } let headerList = markdownTocTools.getHeaderList(); markdownTocTools.createToc(editBuilder, headerList, insertPosition); markdownTocTools.insertAnchor(editBuilder, headerList); }); return true; } public deleteMarkdownToc() { let markdownTocTools = this; window.activeTextEditor.edit(function(editBuilder) { let tocRange = markdownTocTools.getTocRange(); if (tocRange == null) return; editBuilder.delete(tocRange); markdownTocTools.deleteAnchor(editBuilder); }); } public updateMarkdownSections() { let tocRange = this.getTocRange(); this.updateOptions(tocRange); let headerList = this.getHeaderList(); window.activeTextEditor.edit(function(editBuilder) { headerList.forEach(element => { let newHeader = element.header + " " + element.orderedList + " " + element.baseTitle editBuilder.replace(element.range, newHeader); }); }); } public deleteMarkdownSections() { let tocRange = this.getTocRange(); this.updateOptions(tocRange); let headerList = this.getHeaderList(); window.activeTextEditor.edit(function(editBuilder) { headerList.forEach(element => { let newHeader = element.header + " " + element.baseTitle editBuilder.replace(element.range, newHeader); }); }); } public notifyDocumentSave() { // Prevent save again if (this.saveBySelf) { this.saveBySelf = false; return; } let doc = window.activeTextEditor.document; if (doc.languageId != 'markdown') return; if (this.updateMarkdownToc(true)) { doc.save(); this.saveBySelf = true; } } // Private function private getTocRange() { let doc = window.activeTextEditor.document; let start, stop : Position; for(let index = 0; index < doc.lineCount; index++) { let lineText = doc.lineAt(index).text; if ((start == null) && (lineText.match(REGEXP_TOC_START))) { start = new Position(index, 0); } else if (lineText.match(REGEXP_TOC_STOP)) { stop = new Position(index, lineText.length); break; } } if ((start != null) && (stop != null)) { return new Range(start, stop); } return null; } private updateOptions(tocRange : Range) { this.loadConfigurations(); this.loadCustomOptions(tocRange); } private loadConfigurations() { this.options.DEPTH_FROM = <number> workspace.getConfiguration('markdown-toc').get('depthFrom'); this.options.DEPTH_TO = <number> workspace.getConfiguration('markdown-toc').get('depthTo'); this.options.INSERT_ANCHOR = <boolean> workspace.getConfiguration('markdown-toc').get('insertAnchor'); this.options.WITH_LINKS = <boolean> workspace.getConfiguration('markdown-toc').get('withLinks'); this.options.ORDERED_LIST = <boolean> workspace.getConfiguration('markdown-toc').get('orderedList'); this.options.UPDATE_ON_SAVE = <boolean> workspace.getConfiguration('markdown-toc').get('updateOnSave'); this.options.ANCHOR_MODE = <string> workspace.getConfiguration('markdown-toc').get('anchorMode'); } private loadCustomOptions(tocRange : Range) { this.optionsFlag = []; if (tocRange == null) return; let optionsText = window.activeTextEditor.document.lineAt(tocRange.start.line).text; let options = optionsText.match(REGEXP_TOC_CONFIG); if (options == null) return; options.forEach(element => { let pair = REGEXP_TOC_CONFIG_ITEM.exec(element) let key = pair[1].toLocaleLowerCase(); let value = pair[2]; switch (key) { case LOWER_DEPTH_FROM: this.optionsFlag.push(DEPTH_FROM); this.options.DEPTH_FROM = this.parseValidNumber(value); break; case LOWER_DEPTH_TO: this.optionsFlag.push(DEPTH_TO); this.options.DEPTH_TO = Math.max(this.parseValidNumber(value), this.options.DEPTH_FROM); break; case LOWER_INSERT_ANCHOR: this.optionsFlag.push(INSERT_ANCHOR); this.options.INSERT_ANCHOR = this.parseBool(value); break; case LOWER_WITH_LINKS: this.optionsFlag.push(WITH_LINKS); this.options.WITH_LINKS = this.parseBool(value); break; case LOWER_ORDERED_LIST: this.optionsFlag.push(ORDERED_LIST); this.options.ORDERED_LIST = this.parseBool(value); break; case LOWER_UPDATE_ON_SAVE: this.optionsFlag.push(UPDATE_ON_SAVE); this.options.UPDATE_ON_SAVE = this.parseBool(value); break; case LOWER_ANCHOR_MODE: this.optionsFlag.push(ANCHOR_MODE); this.options.ANCHOR_MODE = this.parseValidAnchorMode(value); break; } }); } private insertAnchor(editBuilder : TextEditorEdit, headerList : any[]) { if (!this.options.INSERT_ANCHOR) return; headerList.forEach(element => { let name = element.hash.match(REGEXP_ANCHOR)[1]; let text = [ '<a id="markdown-', name, '" name="', name, '"></a>\n' ]; let insertPosition = new Position(element.line, 0); editBuilder.insert(insertPosition, text.join('')); }); } private deleteAnchor(editBuilder : TextEditorEdit) { let doc = window.activeTextEditor.document; for(let index = 0; index < doc.lineCount; index++) { let lineText = doc.lineAt(index).text; if(lineText.match(REGEXP_MARKDOWN_ANCHOR) == null) continue; let range = new Range(new Position(index, 0), new Position(index + 1, 0)); editBuilder.delete(range); } } private createToc(editBuilder : TextEditorEdit, headerList : any[], insertPosition : Position) { let lineEnding = <string> workspace.getConfiguration("files").get("eol"); let tabSize = <number> workspace.getConfiguration("[markdown]")["editor.tabSize"]; let insertSpaces = <boolean> workspace.getConfiguration("[markdown]")["editor.insertSpaces"]; if(tabSize === undefined || tabSize === null) { tabSize = <number> workspace.getConfiguration("editor").get("tabSize"); } if(insertSpaces === undefined || insertSpaces === null) { insertSpaces = <boolean> workspace.getConfiguration("editor").get("insertSpaces"); } let tab = '\t'; if (insertSpaces && tabSize > 0) { tab = " ".repeat(tabSize); } let optionsText = []; optionsText.push('<!-- TOC '); if (this.optionsFlag.indexOf(DEPTH_FROM) != -1) optionsText.push(DEPTH_FROM + ':' + this.options.DEPTH_FROM +' '); if (this.optionsFlag.indexOf(DEPTH_TO) != -1) optionsText.push(DEPTH_TO + ':' + this.options.DEPTH_TO +' '); if (this.optionsFlag.indexOf(INSERT_ANCHOR) != -1) optionsText.push(INSERT_ANCHOR + ':' + this.options.INSERT_ANCHOR +' '); if (this.optionsFlag.indexOf(ORDERED_LIST) != -1) optionsText.push(ORDERED_LIST + ':' + this.options.ORDERED_LIST +' '); if (this.optionsFlag.indexOf(UPDATE_ON_SAVE)!= -1) optionsText.push(UPDATE_ON_SAVE + ':' + this.options.UPDATE_ON_SAVE +' '); if (this.optionsFlag.indexOf(WITH_LINKS) != -1) optionsText.push(WITH_LINKS + ':' + this.options.WITH_LINKS +' '); if (this.optionsFlag.indexOf(ANCHOR_MODE) != -1) optionsText.push(ANCHOR_MODE + ':' + this.options.ANCHOR_MODE +' '); optionsText.push('-->' + lineEnding); let text = []; text.push(optionsText.join('')); let indicesOfDepth = Array.apply(null, new Array(this.options.DEPTH_TO - this.options.DEPTH_FROM + 1)).map(Number.prototype.valueOf, 0); let waitResetList = Array.apply(null, new Array(indicesOfDepth.length)).map(Boolean.prototype.valueOf, false); let minDepth = 6; headerList.forEach(element => { minDepth = Math.min(element.depth, minDepth); }); let startDepth = Math.max(minDepth , this.options.DEPTH_FROM); headerList.forEach(element => { if (element.depth <= this.options.DEPTH_TO) { let length = element.depth - startDepth; for (var index = 0; index < waitResetList.length; index++) { if (waitResetList[index] && (length < index)) { indicesOfDepth[index] = 0; waitResetList[index] = false; } } let row = [ tab.repeat(length), this.options.ORDERED_LIST ? (++indicesOfDepth[length] + '. ') : '- ', this.options.WITH_LINKS ? element.hash : element.title ]; text.push(row.join('')); waitResetList[length] = true; } }); text.push(lineEnding + "<!-- /TOC -->"); editBuilder.insert(insertPosition, text.join(lineEnding)); } private getHeaderList() { let doc = window.activeTextEditor.document; let headerList = []; let hashMap = {}; let isInCode = 0; let indicesOfDepth = Array.apply(null, new Array(6)).map(Number.prototype.valueOf, 0); for (let index = 0; index < doc.lineCount; index++) { let lineText = doc.lineAt(index).text; let codeResult1 = lineText.match(REGEXP_CODE_BLOCK1); let codeResult2 = lineText.match(REGEXP_CODE_BLOCK2); if (isInCode == 0) { isInCode = codeResult1 != null ? 1 : (codeResult2 != null ? 2 : isInCode); } else if (isInCode == 1) { isInCode = codeResult1 != null ? 0 : isInCode; } else if (isInCode == 2) { isInCode = codeResult2 != null ? 0 : isInCode; } if (isInCode) continue; let headerResult = lineText.match(REGEXP_HEADER); if (headerResult == null) continue; let depth = headerResult[1].length; if (depth < this.options.DEPTH_FROM) continue; if (depth > this.options.DEPTH_TO) continue; if (lineText.match(REGEXP_IGNORE_TITLE)) continue; for (var i = depth; i <= this.options.DEPTH_TO; i++) { indicesOfDepth[depth] = 0; } indicesOfDepth[depth - 1]++; let orderedListStr = "" for (var i = this.options.DEPTH_FROM - 1; i < depth; i++) { orderedListStr += indicesOfDepth[i].toString() + "."; } let title = lineText.substr(depth).trim(); let baseTitle = title.replace(/^(?:\d+\.)+/, "").trim(); // title without section number title = title.replace(/\[(.+)]\([^)]*\)/gi, "$1"); // replace link title = title.replace(/<!--.+-->/gi, ""); // replace comment title = title.replace(/\#*_/gi, "").trim(); // replace special char if (hashMap[title] == null) { hashMap[title] = 0 } else { hashMap[title] += 1; } let hash = this.getHash(title, this.options.ANCHOR_MODE, hashMap[title]); headerList.push({ line : index, depth : depth, title : title, hash : hash, range : new Range(index, 0, index, lineText.length), header : headerResult[1], orderedList : orderedListStr, baseTitle : baseTitle }); } return headerList; } private getHash(headername : string, mode : string, repetition : number) { let anchor = require('anchor-markdown-header'); return decodeURI(anchor(headername, mode, repetition)); } private parseValidNumber(value : string) { let num = parseInt(value); if (num < 1) { return 1; } if (num > 6) { return 6; } return num; } private parseValidAnchorMode(value : string) { if (ANCHOR_MODE_LIST.indexOf(value) != -1) { return value; } return ANCHOR_MODE_LIST[0]; } private parseBool(value : string) { return value.toLocaleLowerCase() == 'true'; } dispose() { } }
the_stack
interface ClassInfo { /** * 类的id,默认使用类名,不能重复 */ id?: string; /** * 类的类型 */ type: any; /** * 记录装饰器调用的位置 */ pos: any; } /** * 序列化时需要忽略的字段 */ const transientFields = new Map<any, any>(); const classInfos = new Map<any, ClassInfo>(); /** * 通过 classId 获取 classInfo * @param {string} id * @returns {ClassInfo} */ const getClassInfoById = (id: string) => { for (let entry of classInfos) { let classInfo = entry[1]; if (classInfo.id == id) { return classInfo; } } return null; }; /** * 序列化和反序列化工具类,目前在整个框架中只有两个地方用到: * 1. QueueManager 中保存和加载运行状态 * 2. JobManager 中对 job 进行序列化保存和反序列化加载 */ export class SerializableUtil { /** * 序列化 * @param obj * @returns {any | string | {}} */ static serialize(obj: any): string[] { if (!this.shouldSerialize(obj)) { return [ "-1", JSON.stringify(obj) ]; } const serializedCaches = new Map<any, string>(); const magicNum = (Math.random() * 10000).toFixed(0); const serializedRes = [magicNum]; // 第一行为magicNum this._serialize(obj, serializedCaches, serializedRes); return serializedRes; } private static shouldSerialize(obj: any) { if (obj == null || obj == undefined) return false; const objType = typeof obj; return !(objType == "string" || objType == "number" || objType == "boolean"); } private static _serialize(obj: any, serializedCaches: Map<any, string>, serializedRes: string[]) { if (!this.shouldSerialize(obj)) { return obj; } let serializedCache = serializedCaches.get(obj); if (serializedCache == undefined) { const objConstructor = obj.constructor; if (typeof obj == "function" || !objConstructor) { // 方法不需要进一步序列化 return undefined; } // 保存当前处理的实例的ref id serializedCache = serializedRes[0] + "_" + serializedCaches.size; serializedCaches.set(obj, serializedCache); let res = null; if (obj instanceof Array) { res = []; (obj as Array<any>).forEach((value, index) => { res.push(this._serialize(value, serializedCaches, serializedRes)); // 数组中每个元素需要进一步序列化 }); } else { res = {}; const transients = transientFields[objConstructor]; for (let field in obj) { if (transients && transients[field]) { // 忽略字段 } else res[field] = this._serialize(obj[field], serializedCaches, serializedRes); // 进一步序列化类成员的值 } let classInfo = classInfos.get(objConstructor); if (classInfo && classInfo.id) res.serializeClassId = classInfo.id; // 设置 classId,在反序列化时获取类信息 } serializedRes.push(serializedCache + " " + JSON.stringify(res)); } return "ref(" + serializedCache + ")"; } /** * 反序列化 * @param lines * @returns {any} */ static deserialize(lines: string[]): any { if (lines[0] == "-1") { return JSON.parse(lines[1]); } const deserializedCaches = {}; this._deserialize(lines, deserializedCaches, {}); return deserializedCaches[lines[0] + "_0"]; } private static _deserialize(lines: string[], deserializedCaches: any, refCaches: any): any { const magicNum = lines[0]; const objIdRegex = new RegExp("^ref\\((" + magicNum + "_\\d+)\\)$"); for (let i = 1, len = lines.length; i < len; i++) { const line = lines[i]; const spaceI = line.indexOf(" "); const objId = line.substring(0, spaceI); if (!objId.startsWith(magicNum + "_")) { throw new Error("bad serialized line, wrong magic num: " + line); } let obj = JSON.parse(line.substring(spaceI + 1)); if (obj instanceof Array) { for (let j = 0, objLen = obj.length; j < objLen; j++) { this.checkRefCache(objIdRegex, obj, j, deserializedCaches, refCaches); } } else { const serializeClassId = obj.serializeClassId; const serializeClassInfo = serializeClassId ? getClassInfoById(serializeClassId) : null; if (serializeClassInfo) { delete obj.serializeClassId; const serializeClass = serializeClassInfo.type; const newObj = new serializeClass(); Object.assign(newObj, obj); obj = newObj; } for (let key of Object.keys(obj)) { this.checkRefCache(objIdRegex, obj, key, deserializedCaches, refCaches); } } deserializedCaches[objId] = obj; let refs = refCaches[objId]; if (refs) { for (let ref of refs) { ref.obj[ref.keyOrIndex] = obj; } delete refCaches[objId]; } } } private static checkRefCache(objIdRegex: RegExp, obj: any, keyOrIndex: any, deserializedCaches: any, refCaches: any) { let m; const value = obj[keyOrIndex]; if (typeof value == "string" && (m = objIdRegex.exec(value))) { let refId = m[1]; let refObj = deserializedCaches[refId]; if (refObj) { obj[keyOrIndex] = refObj; } else { let refs = refCaches[refId]; if (refs == null) { refs = []; refCaches[refId] = refs; } refs.push({ obj: obj, keyOrIndex: keyOrIndex }); } } } } /** * @deprecated */ export class SerializableUtil_old { /** * 反序列化 * @param obj * @returns {any} */ static deserialize(obj: any): any { return this._deserialize(obj, {}, obj, "$"); } private static _deserialize(obj: any, deserializedCaches: any, root: any, path: string): any { if (obj == null) return obj; const objType = typeof obj; if (objType == "number" || objType == "boolean") { return obj; // number | boolean 不需要反序列化,直接返回 } else if (objType == "string") { const str = obj as string; if (str.startsWith("ref($") && str.endsWith(")")) { const refPath = str.substring(4, str.length - 1); let deserializedCache = deserializedCaches[refPath]; if (deserializedCache === undefined) { const $ = root; try { deserializedCache = deserializedCaches[refPath] = eval(refPath); // 根据绝对路径计算引用表达式的值 } catch (e) { return str; // 根据路径获取值失败,当做普通 string 返回 } } return deserializedCache; } else return obj; // 普通的 string 值,直接返回结果 } let res = null; if (obj instanceof Array) { res = deserializedCaches[path] = []; (obj as Array<any>).forEach((value, index) => { res.push(this._deserialize(value, deserializedCaches, root, path + "[" + index + "]")); // 进一步反序列化数组中每一个元素 }); } else { const serializeClassId = (obj as any).serializeClassId; const serializeClassInfo = serializeClassId ? getClassInfoById(serializeClassId) : null; if (serializeClassInfo) { const serializeClass = serializeClassInfo.type; res = deserializedCaches[path] = new serializeClass(); for (let field of Object.keys(obj)) { if (field != "serializeClassId") res[field] = this._deserialize(obj[field], deserializedCaches, root, path + "[" + JSON.stringify(field) + "]"); } } else { res = deserializedCaches[path] = {}; for (let field of Object.keys(obj)) { res[field] = this._deserialize(obj[field], deserializedCaches, root, path + "[" + JSON.stringify(field) + "]"); } } } return res; } } const stackPosReg = new RegExp("^at .* \\((.*)\\)$"); /** * 获取 @Serialize 的装饰位置,以便在后续报错时能指出正确的位置 * @returns {string} */ function getDecoratorPos() { const stack = new Error("test").stack.split("\n"); const pos = stack[3].trim(); const stackPosM = stackPosReg.exec(pos); return stackPosM ? stackPosM[1] : null; } export interface SerializableConfig { classId?: string; } /** * 在js加载的过程中,有这个装饰器的类的类信息会保存到 classInfos 中,用于序列化和反序列化 * @param {SerializableConfig} config * @returns {(target) => void} * @constructor */ export function Serializable(config?: SerializableConfig) { const decoratorPos = getDecoratorPos(); return function (target) { if (!config) config = {}; const id = config.classId || target.name; let existed = classInfos.get(id); if (!existed) { existed = { id: config.classId || target.name, type: target, pos: decoratorPos, transients: transientFields[target], } as ClassInfo; classInfos.set(target, existed); } else { throw new Error("duplicate classId(" + existed.id + ") at: \n" + existed.pos + "\n" + existed.pos); } } } /** * 类在序列化时要忽略的字段 * 不能作用于类静态字段 * @returns {(target: any, field: string) => void} * @constructor */ export function Transient() { return function (target: any, field: string) { const isStatic = target.constructor.name === "Function"; if (isStatic) throw new Error("cannot decorate static field with Transient"); // @Transient 不能作用于类静态成员 const type = target.constructor; let transients = transientFields[type]; if (!transients) { transientFields[type] = transients = {}; } transients[field] = true; }; } export function Assign(target, source) { if (source && target && typeof source == "object" && typeof target == "object") { const transients = transientFields[target.constructor]; if (transients) { for (let field of Object.keys(source)) { if (!transients[field]) { target[field] = source[field]; } } } else { Object.assign(target, source); } } }
the_stack
import {Mutable, FromAny, AnyTiming, Timing} from "@swim/util"; import {Affinity, FastenerOwner, Property, AnimatorInit, AnimatorClass, Animator} from "@swim/component"; import {AnyLength, Length, AnyAngle, Angle, AnyTransform, Transform} from "@swim/math"; import {AnyFont, Font, AnyColor, Color, AnyFocus, Focus, AnyPresence, Presence, AnyExpansion, Expansion} from "@swim/style"; import {Look} from "../look/Look"; import type {MoodVector} from "../mood/MoodVector"; import type {ThemeMatrix} from "../theme/ThemeMatrix"; import {ThemeContext} from "../theme/ThemeContext"; import {StringThemeAnimator} from "./"; // forward import import {NumberThemeAnimator} from "./"; // forward import import {BooleanThemeAnimator} from "./"; // forward import import {AngleThemeAnimator} from "./"; // forward import import {LengthThemeAnimator} from "./"; // forward import import {TransformThemeAnimator} from "./"; // forward import import {ColorThemeAnimator} from "./"; // forward import import {FontThemeAnimator} from "./"; // forward import import {FocusThemeAnimatorInit, FocusThemeAnimator} from "./"; // forward import import {PresenceThemeAnimatorInit, PresenceThemeAnimator} from "./"; // forward import import {ExpansionThemeAnimatorInit, ExpansionThemeAnimator} from "./"; // forward import /** @public */ export interface ThemeAnimatorInit<T = unknown, U = T> extends AnimatorInit<T, U> { extends?: {prototype: ThemeAnimator<any, any>} | string | boolean | null; look?: Look<T>; willSetLook?(newLook: Look<T> | null, oldLook: Look<T> | null, timing: Timing | boolean): void; didSetLook?(newLook: Look<T> | null, oldLook: Look<T> | null, timing: Timing | boolean): void; } /** @public */ export type ThemeAnimatorDescriptor<O = unknown, T = unknown, U = T, I = {}> = ThisType<ThemeAnimator<O, T, U> & I> & ThemeAnimatorInit<T, U> & Partial<I>; /** @public */ export interface ThemeAnimatorClass<A extends ThemeAnimator<any, any> = ThemeAnimator<any, any>> extends AnimatorClass<A> { } /** @public */ export interface ThemeAnimatorFactory<A extends ThemeAnimator<any, any> = ThemeAnimator<any, any>> extends ThemeAnimatorClass<A> { extend<I = {}>(className: string, classMembers?: Partial<I> | null): ThemeAnimatorFactory<A> & I; specialize(type: unknown): ThemeAnimatorFactory | null; define<O, T, U = T>(className: string, descriptor: ThemeAnimatorDescriptor<O, T, U>): ThemeAnimatorFactory<ThemeAnimator<any, T, U>>; define<O, T, U = T, I = {}>(className: string, descriptor: {implements: unknown} & ThemeAnimatorDescriptor<O, T, U, I>): ThemeAnimatorFactory<ThemeAnimator<any, T, U> & I>; <O, T extends Angle | null | undefined = Angle | null | undefined, U extends AnyAngle | null | undefined = AnyAngle | null | undefined>(descriptor: {type: typeof Angle} & ThemeAnimatorDescriptor<O, T, U>): PropertyDecorator; <O, T extends Length | null | undefined = Length | null | undefined, U extends AnyLength | null | undefined = AnyLength | null | undefined>(descriptor: {type: typeof Length} & ThemeAnimatorDescriptor<O, T, U>): PropertyDecorator; <O, T extends Transform | null | undefined = Transform | null | undefined, U extends AnyTransform | null | undefined = AnyTransform | null | undefined>(descriptor: {type: typeof Transform} & ThemeAnimatorDescriptor<O, T, U>): PropertyDecorator; <O, T extends Color | null | undefined = Color | null | undefined, U extends AnyColor | null | undefined = AnyColor | null | undefined>(descriptor: {type: typeof Color} & ThemeAnimatorDescriptor<O, T, U>): PropertyDecorator; <O, T extends Font | null | undefined = Font | null | undefined, U extends AnyFont | null | undefined = AnyFont | null | undefined>(descriptor: {type: typeof Font} & ThemeAnimatorDescriptor<O, T, U>): PropertyDecorator; <O, T extends Focus | null | undefined = Focus | null | undefined, U extends AnyFocus | null | undefined = AnyFocus | null | undefined>(descriptor: {type: typeof Focus} & ThemeAnimatorDescriptor<O, T, U> & FocusThemeAnimatorInit): PropertyDecorator; <O, T extends Presence | null | undefined = Presence | null | undefined, U extends AnyPresence | null | undefined = AnyPresence | null | undefined>(descriptor: {type: typeof Presence} & ThemeAnimatorDescriptor<O, T, U> & PresenceThemeAnimatorInit): PropertyDecorator; <O, T extends Expansion | null | undefined = Expansion | null | undefined, U extends AnyExpansion | null | undefined = AnyExpansion | null | undefined>(descriptor: {type: typeof Expansion} & ThemeAnimatorDescriptor<O, T, U> & ExpansionThemeAnimatorInit): PropertyDecorator; <O, T extends string | undefined = string | undefined, U extends string | undefined = string | undefined>(descriptor: {type: typeof String} & ThemeAnimatorDescriptor<O, T, U>): PropertyDecorator; <O, T extends number | undefined = number | undefined, U extends number | string | undefined = number | string | undefined>(descriptor: {type: typeof Number} & ThemeAnimatorDescriptor<O, T, U>): PropertyDecorator; <O, T extends boolean | undefined = boolean | undefined, U extends boolean | string | undefined = boolean | string | undefined>(descriptor: {type: typeof Boolean} & ThemeAnimatorDescriptor<O, T, U>): PropertyDecorator; <O, T, U = T>(descriptor: ({type: FromAny<T, U>} | {fromAny(value: T | U): T}) & ThemeAnimatorDescriptor<O, T, U>): PropertyDecorator; <O, T, U = T>(descriptor: ThemeAnimatorDescriptor<O, T, U>): PropertyDecorator; <O, T, U = T, I = {}>(descriptor: {implements: unknown} & ThemeAnimatorDescriptor<O, T, U, I>): PropertyDecorator; } /** @public */ export interface ThemeAnimator<O = unknown, T = unknown, U = T> extends Animator<O, T, U> { /** @protected @override */ onSetAffinity(newAffinity: Affinity, oldAffinity: Affinity): void; /** @protected @override */ onInherit(superFastener: Property<unknown, T>): void; get superLook(): Look<T> | null; getSuperLook(): Look<T>; getSuperLookOr<E>(elseLook: E): Look<T> | E; readonly look: Look<T> | null; getLook(): Look<T>; getLookOr<E>(elseLook: E): Look<T> | E; setLook(newLook: Look<T> | null, timingOrAffinity: Affinity | AnyTiming | boolean | null | undefined): void; setLook(newLook: Look<T> | null, timing?: AnyTiming | boolean | null, affinity?: Affinity): void; /** @protected */ willSetLook(newLook: Look<T> | null, oldLook: Look<T> | null, timing: Timing | boolean): void; /** @protected */ onSetLook(newLook: Look<T> | null, oldLook: Look<T> | null, timing: Timing | boolean): void; /** @protected */ didSetLook(newLook: Look<T> | null, oldLook: Look<T> | null, timing: Timing | boolean): void; /** @internal */ applyLook(look: Look<T>, timing: Timing | boolean): void; applyTheme(theme: ThemeMatrix, mood: MoodVector, timing: Timing | boolean): void; /** @internal @protected @override */ tweenInherited(t: number): void; /** @protected @override */ onMount(): void; } /** @public */ export const ThemeAnimator = (function (_super: typeof Animator) { const ThemeAnimator: ThemeAnimatorFactory = _super.extend("ThemeAnimator"); ThemeAnimator.prototype.onSetAffinity = function (this: ThemeAnimator, newAffinity: Affinity, oldAffinity: Affinity): void { if (newAffinity > Affinity.Intrinsic) { this.setLook(null, newAffinity); } _super.prototype.onSetAffinity.call(this, newAffinity, oldAffinity); }; ThemeAnimator.prototype.onInherit = function <T>(this: ThemeAnimator<unknown, T>, superFastener: Property<any, T>): void { if (superFastener instanceof ThemeAnimator) { this.setLook(superFastener.look, superFastener.timing, Affinity.Reflexive); } else { this.setLook(null, Affinity.Reflexive); } if (this.look === null) { _super.prototype.onInherit.call(this, superFastener); } }; Object.defineProperty(ThemeAnimator.prototype, "superLook", { get: function <T>(this: ThemeAnimator<unknown, T>): Look<T> | null { const superFastener = this.superFastener; return superFastener instanceof ThemeAnimator ? superFastener.look : null; }, configurable: true, }); ThemeAnimator.prototype.getSuperLook = function <T>(this: ThemeAnimator<unknown, T>): Look<T> { const superLook = this.superLook; if (superLook === null) { throw new TypeError(superLook + " " + this.name + " super look"); } return superLook; }; ThemeAnimator.prototype.getSuperLookOr = function <T, E>(this: ThemeAnimator<unknown, T>, elseLook: E): Look<T> | E { let superLook: Look<T> | E | null = this.superLook; if (superLook === null) { superLook = elseLook; } return superLook; }; ThemeAnimator.prototype.getLook = function <T>(this: ThemeAnimator<unknown, T>): Look<T> { const look = this.look; if (look === null) { throw new TypeError(look + " " + this.name + " look"); } return look; }; ThemeAnimator.prototype.getLookOr = function <T, E>(this: ThemeAnimator<unknown, T>, elseLook: E): Look<T> | E { let look: Look<T> | E | null = this.look; if (look === null) { look = elseLook; } return look; }; ThemeAnimator.prototype.setLook = function <T>(this: ThemeAnimator<unknown, T>, newLook: Look<T> | null, timing?: Affinity | AnyTiming | boolean | null, affinity?: Affinity): void { if (typeof timing === "number") { affinity = timing; timing = void 0; } if (affinity === void 0) { affinity = Affinity.Extrinsic; } if (this.minAffinity(affinity)) { const oldLook = this.look; if (newLook !== oldLook) { if (timing === void 0 || timing === null) { timing = false; } else { timing = Timing.fromAny(timing); } this.willSetLook(newLook, oldLook, timing as Timing | boolean); (this as Mutable<typeof this>).look = newLook; this.onSetLook(newLook, oldLook, timing as Timing | boolean); this.didSetLook(newLook, oldLook, timing as Timing | boolean); } } }; ThemeAnimator.prototype.willSetLook = function <T>(this: ThemeAnimator<unknown, T>, newLook: Look<T> | null, oldLook: Look<T> | null, timing: Timing | boolean): void { // hook }; ThemeAnimator.prototype.onSetLook = function <T>(this: ThemeAnimator<unknown, T>, newLook: Look<T> | null, oldLook: Look<T> | null, timing: Timing | boolean): void { if (newLook !== null) { this.applyLook(newLook, timing); } }; ThemeAnimator.prototype.didSetLook = function <T>(this: ThemeAnimator<unknown, T>, newLook: Look<T> | null, oldLook: Look<T> | null, timing: Timing | boolean): void { // hook }; ThemeAnimator.prototype.applyLook = function <T>(this: ThemeAnimator<unknown, T>, look: Look<T>, timing: Timing | boolean): void { const themeContext = this.owner; if (this.mounted && ThemeContext.is(themeContext)) { const state = themeContext.getLook(look); if (state !== void 0) { if (timing === true) { timing = themeContext.getLookOr(Look.timing, true); } this.setState(state, timing, Affinity.Reflexive); } } }; ThemeAnimator.prototype.applyTheme = function <T>(this: ThemeAnimator<unknown, T>, theme: ThemeMatrix, mood: MoodVector, timing: Timing | boolean | undefined): void { const look = this.look; if (look !== null) { const state = theme.get(look, mood); if (state !== void 0) { if (timing === true) { timing = theme.get(Look.timing, mood); if (timing === void 0) { timing = true; } } this.setState(state, timing, Affinity.Reflexive); } } }; ThemeAnimator.prototype.tweenInherited = function <T>(this: ThemeAnimator<unknown, T>, t: number): void { const superFastener = this.superFastener; if (superFastener instanceof ThemeAnimator) { this.setLook(superFastener.look, superFastener.timing, Affinity.Reflexive); } else { this.setLook(null, Affinity.Reflexive); } if (this.look !== null) { _super.prototype.tween.call(this, t); } else { _super.prototype.tweenInherited.call(this, t); } } ThemeAnimator.prototype.onMount = function (this: ThemeAnimator): void { _super.prototype.onMount.call(this); const look = this.look; if (look !== null) { this.applyLook(look, false); } }; ThemeAnimator.construct = function <A extends ThemeAnimator<any, any>>(animatorClass: {prototype: A}, animator: A | null, owner: FastenerOwner<A>): A { animator = _super.construct(animatorClass, animator, owner) as A; (animator as Mutable<typeof animator>).look = null; return animator; }; ThemeAnimator.specialize = function (type: unknown): ThemeAnimatorFactory | null { if (type === String) { return StringThemeAnimator; } else if (type === Number) { return NumberThemeAnimator; } else if (type === Boolean) { return BooleanThemeAnimator; } else if (type === Angle) { return AngleThemeAnimator; } else if (type === Length) { return LengthThemeAnimator; } else if (type === Transform) { return TransformThemeAnimator; } else if (type === Color) { return ColorThemeAnimator; } else if (type === Font) { return FontThemeAnimator; } else if (type === Focus) { return FocusThemeAnimator; } else if (type === Presence) { return PresenceThemeAnimator; } else if (type === Expansion) { return ExpansionThemeAnimator; } return null; }; ThemeAnimator.define = function <O, T, U>(className: string, descriptor: ThemeAnimatorDescriptor<O, T, U>): ThemeAnimatorFactory<ThemeAnimator<any, T, U>> { let superClass = descriptor.extends as ThemeAnimatorFactory | null | undefined; const affinity = descriptor.affinity; const inherits = descriptor.inherits; const look = descriptor.look; const value = descriptor.value; const initValue = descriptor.initValue; delete descriptor.extends; delete descriptor.implements; delete descriptor.affinity; delete descriptor.inherits; delete descriptor.look; delete descriptor.value; delete descriptor.initValue; if (superClass === void 0 || superClass === null) { superClass = this.specialize(descriptor.type); } if (superClass === null) { superClass = this; if (descriptor.fromAny === void 0 && FromAny.is<T, U>(descriptor.type)) { descriptor.fromAny = descriptor.type.fromAny; } } const animatorClass = superClass.extend(className, descriptor); animatorClass.construct = function (animatorClass: {prototype: ThemeAnimator<any, any>}, animator: ThemeAnimator<O, T, U> | null, owner: O): ThemeAnimator<O, T, U> { animator = superClass!.construct(animatorClass, animator, owner); if (affinity !== void 0) { animator.initAffinity(affinity); } if (inherits !== void 0) { animator.initInherits(inherits); } if (look !== void 0) { (animator as Mutable<typeof animator>).look = look; } if (initValue !== void 0) { (animator as Mutable<typeof animator>).value = animator.fromAny(initValue()); (animator as Mutable<typeof animator>).state = animator.value; } else if (value !== void 0) { (animator as Mutable<typeof animator>).value = animator.fromAny(value); (animator as Mutable<typeof animator>).state = animator.value; } return animator; }; return animatorClass; }; return ThemeAnimator; })(Animator);
the_stack
module CorsicaTests { var testElementId = "accent-test-element"; var testElementId2 = "foo"; var testElement: HTMLDivElement; var testElement2: HTMLDivElement; var Accents = WinJS.UI._Accents; function getDynamicStyleElement() { return document.head.querySelector("#WinJSAccentsStyle"); } export class AccentTests { setUp() { Accents._reset(); testElement = document.createElement("div"); testElement2 = document.createElement("div"); testElement.id = testElementId; testElement2.id = testElementId; document.body.appendChild(testElement); document.body.appendChild(testElement2); } tearDown() { document.body.parentElement.classList.remove("win-ui-light"); testElement && testElement.parentElement && testElement.parentElement.removeChild(testElement); testElement2 && testElement2.parentElement && testElement2.parentElement.removeChild(testElement2); testElement = testElement2 = null; } testCreateAccentRuleSimple(complete) { LiveUnit.Assert.areNotEqual(Accents._colors[Accents.ColorTypes.accent], getComputedStyle(testElement).color); Accents.createAccentRule("#accent-test-element", [{ name: "color", value: Accents.ColorTypes.accent }]); WinJS.Promise.timeout().done(() => { LiveUnit.Assert.stringContains(getDynamicStyleElement().textContent, "#accent-test-element"); LiveUnit.Assert.areEqual(Accents._colors[Accents.ColorTypes.accent], getComputedStyle(testElement).color); complete(); }); } testCreateAccentRuleInverse(complete) { document.body.parentElement.classList.add("win-ui-light"); var cs = getComputedStyle(testElement); LiveUnit.Assert.areNotEqual(Accents._colors[Accents.ColorTypes._listSelectRestInverse], cs.backgroundColor); LiveUnit.Assert.areNotEqual(Accents._colors[Accents.ColorTypes._listSelectHoverInverse], cs.borderBottomColor); LiveUnit.Assert.areNotEqual(Accents._colors[Accents.ColorTypes._listSelectPressInverse], cs.outlineColor); Accents.createAccentRule("#accent-test-element", [ { name: "background-color", value: Accents.ColorTypes.listSelectRest }, { name: "border-bottom-color", value: Accents.ColorTypes.listSelectHover }, { name: "outline-color", value: Accents.ColorTypes.listSelectPress }, ]); WinJS.Promise.timeout().done(() => { var expectedlistSelectPressInverseColor = Accents._colors[Accents.ColorTypes._listSelectPressInverse]; LiveUnit.Assert.areEqual(Accents._colors[Accents.ColorTypes._listSelectRestInverse], getComputedStyle(testElement).backgroundColor); LiveUnit.Assert.areEqual(Accents._colors[Accents.ColorTypes._listSelectHoverInverse], getComputedStyle(testElement).borderBottomColor); // Some browsers end up computing 'rgba(x,x,x,0.7)' to 'rgba(x,x,x,0.70196)' so we have to change the assertion LiveUnit.Assert.stringContains(getComputedStyle(testElement).outlineColor, (expectedlistSelectPressInverseColor.substr(0, expectedlistSelectPressInverseColor.length - 2))); complete(); }); } testCreateAccentRuleInverseHover(complete) { LiveUnit.Assert.areNotEqual(Accents._colors[Accents.ColorTypes.listSelectHover], getComputedStyle(testElement).color); Accents.createAccentRule("html.win-hoverable #accent-test-element", [{ name: "color", value: Accents.ColorTypes.listSelectHover }]); WinJS.Promise.timeout().done(() => { LiveUnit.Assert.stringContains(getDynamicStyleElement().textContent, "html.win-hoverable #accent-test-element"); LiveUnit.Assert.stringContains(getDynamicStyleElement().textContent, "html.win-hoverable .win-ui-light #accent-test-element"); LiveUnit.Assert.stringContains(getDynamicStyleElement().textContent, "html.win-hoverable .win-ui-light#accent-test-element"); complete(); }); } testCreateAccentRuleInverseHoverNoLeadingToken(complete) { LiveUnit.Assert.areNotEqual(Accents._colors[Accents.ColorTypes.listSelectHover], getComputedStyle(testElement).color); Accents.createAccentRule("html.win-hoverable randomTag", [{ name: "color", value: Accents.ColorTypes.listSelectHover }]); WinJS.Promise.timeout().done(() => { LiveUnit.Assert.stringContains(getDynamicStyleElement().textContent, "html.win-hoverable randomTag"); LiveUnit.Assert.stringContains(getDynamicStyleElement().textContent, "html.win-hoverable .win-ui-light randomTag"); LiveUnit.Assert.stringDoesNotContain(getDynamicStyleElement().textContent, "html.win-hoverable .win-ui-lightrandomTag"); complete(); }); } testCreateAccentRuleInverseHoverWithWhitespace(complete) { LiveUnit.Assert.areNotEqual(Accents._colors[Accents.ColorTypes.listSelectHover], getComputedStyle(testElement).color); Accents.createAccentRule(" html.win-hoverable #accent-test-element ", [{ name: "color", value: Accents.ColorTypes.listSelectHover }]); WinJS.Promise.timeout().done(() => { LiveUnit.Assert.stringContains(getDynamicStyleElement().textContent, "html.win-hoverable #accent-test-element"); LiveUnit.Assert.stringContains(getDynamicStyleElement().textContent, "html.win-hoverable .win-ui-light #accent-test-element"); LiveUnit.Assert.stringContains(getDynamicStyleElement().textContent, "html.win-hoverable .win-ui-light#accent-test-element"); complete(); }); } testCreateAccentRuleInverseNoLeadingToken(complete) { LiveUnit.Assert.areNotEqual(Accents._colors[Accents.ColorTypes.listSelectHover], getComputedStyle(testElement).color); Accents.createAccentRule("randomTag", [{ name: "color", value: Accents.ColorTypes.listSelectHover }]); WinJS.Promise.timeout().done(() => { LiveUnit.Assert.stringContains(getDynamicStyleElement().textContent, "randomTag"); LiveUnit.Assert.stringContains(getDynamicStyleElement().textContent, ".win-ui-light randomTag"); LiveUnit.Assert.stringDoesNotContain(getDynamicStyleElement().textContent, ".win-ui-lightrandomTag"); complete(); }); } testMultipleSelectors(complete) { LiveUnit.Assert.areNotEqual(Accents._colors[Accents.ColorTypes.accent], getComputedStyle(testElement).color); Accents.createAccentRule("#accent-test-element, #foo", [{ name: "color", value: Accents.ColorTypes.accent }]); WinJS.Promise.timeout().done(() => { LiveUnit.Assert.stringContains(getDynamicStyleElement().textContent, "#accent-test-element"); LiveUnit.Assert.stringContains(getDynamicStyleElement().textContent, "#foo"); LiveUnit.Assert.areEqual(Accents._colors[Accents.ColorTypes.accent], getComputedStyle(testElement).color); LiveUnit.Assert.areEqual(Accents._colors[Accents.ColorTypes.accent], getComputedStyle(testElement2).color); complete(); }); } testMultipleSelectorsWithWhitespace(complete) { Accents.createAccentRule(" #accent-test-element , #foo ", [{ name: "color", value: Accents.ColorTypes.accent }]); WinJS.Promise.timeout().done(() => { LiveUnit.Assert.stringContains(getDynamicStyleElement().textContent, "#accent-test-element"); LiveUnit.Assert.stringContains(getDynamicStyleElement().textContent, "#foo"); LiveUnit.Assert.areEqual(Accents._colors[Accents.ColorTypes.accent], getComputedStyle(testElement).color); LiveUnit.Assert.areEqual(Accents._colors[Accents.ColorTypes.accent], getComputedStyle(testElement2).color); complete(); }); } testMultipleSelectorsInverse(complete) { document.body.parentElement.classList.add("win-ui-light"); var cs = getComputedStyle(testElement); LiveUnit.Assert.areNotEqual(Accents._colors[Accents.ColorTypes._listSelectRestInverse], cs.backgroundColor); LiveUnit.Assert.areNotEqual(Accents._colors[Accents.ColorTypes._listSelectHoverInverse], cs.borderBottomColor); Accents.createAccentRule("randomTag, #accent-test-element", [ { name: "background-color", value: Accents.ColorTypes.listSelectRest }, { name: "border-bottom-color", value: Accents.ColorTypes.listSelectHover }, ]); WinJS.Promise.timeout().done(() => { LiveUnit.Assert.stringContains(getDynamicStyleElement().textContent, "randomTag"); LiveUnit.Assert.stringContains(getDynamicStyleElement().textContent, "#accent-test-element"); LiveUnit.Assert.stringContains(getDynamicStyleElement().textContent, ".win-ui-light #accent-test-element"); LiveUnit.Assert.stringContains(getDynamicStyleElement().textContent, ".win-ui-light#accent-test-element"); LiveUnit.Assert.stringContains(getDynamicStyleElement().textContent, ".win-ui-light randomTag"); LiveUnit.Assert.stringDoesNotContain(getDynamicStyleElement().textContent, ".win-ui-lightrandomTag"); LiveUnit.Assert.areEqual(Accents._colors[Accents.ColorTypes._listSelectRestInverse], getComputedStyle(testElement).backgroundColor); LiveUnit.Assert.areEqual(Accents._colors[Accents.ColorTypes._listSelectHoverInverse], getComputedStyle(testElement).borderBottomColor); complete(); }); } testMultiPropertyRule(complete) { var cs = getComputedStyle(testElement); LiveUnit.Assert.areNotEqual(Accents._colors[Accents.ColorTypes.accent], cs.color); LiveUnit.Assert.areNotEqual(Accents._colors[Accents.ColorTypes.listSelectRest], cs.backgroundColor); LiveUnit.Assert.areNotEqual(Accents._colors[Accents.ColorTypes.listSelectHover], cs.borderBottomColor); Accents.createAccentRule("#accent-test-element", [ { name: "color", value: Accents.ColorTypes.accent }, { name: "background-color", value: Accents.ColorTypes.listSelectRest }, { name: "border-bottom-color", value: Accents.ColorTypes.listSelectHover }, { name: "outline-color", value: Accents.ColorTypes.listSelectPress }, ]); WinJS.Promise.timeout().done(() => { var expectedlistSelectPressColor = Accents._colors[Accents.ColorTypes.listSelectPress]; cs = getComputedStyle(testElement); LiveUnit.Assert.stringContains(getDynamicStyleElement().textContent, "#accent-test-element"); LiveUnit.Assert.areEqual(Accents._colors[Accents.ColorTypes.accent], cs.color); LiveUnit.Assert.areEqual(Accents._colors[Accents.ColorTypes.listSelectRest], cs.backgroundColor); LiveUnit.Assert.areEqual(Accents._colors[Accents.ColorTypes.listSelectHover], cs.borderBottomColor); // Some browsers end up computing 'rgba(x,x,x,0.9)' to 'rgba(x,x,x,0.90196)' so we have to change the assertion LiveUnit.Assert.stringContains(getComputedStyle(testElement).outlineColor, (expectedlistSelectPressColor.substr(0, expectedlistSelectPressColor.length - 2))); complete(); }); } verifyThemeDetection(args: { iframeSrc: string; verify(iframeWinJS: typeof WinJS): void; complete(): void; }) { var iframe = document.createElement("iframe"); iframe.src = args.iframeSrc; iframe.width = "500"; iframe.height = "500"; iframe.onload = function () { var iframeGlobal = iframe.contentWindow; var iframeWinJS = <typeof WinJS>(<any>iframe.contentWindow).WinJS; args.verify(iframeWinJS); args.complete(); }; testElement.appendChild(iframe); } testThemeDetectionUiDark(complete) { this.verifyThemeDetection({ iframeSrc: "$(TESTDATA)/WinJSSandbox.html", verify: (iframeWinJS) => { LiveUnit.Assert.isTrue(iframeWinJS.UI._Accents._isDarkTheme, "Accent color system should have detected the dark stylesheet theme"); }, complete: complete }); } testThemeDetectionUiLight(complete) { this.verifyThemeDetection({ iframeSrc: "$(TESTDATA)/WinJSSandboxLight.html", verify: (iframeWinJS) => { LiveUnit.Assert.isFalse(iframeWinJS.UI._Accents._isDarkTheme, "Accent color system should have detected the light stylesheet theme"); }, complete: complete }); } testAccentsInDisplayNoneIFrameDoesNotCrash(complete) { var iframe = document.createElement("iframe"); iframe.style.display = "none"; iframe.src = "$(TESTDATA)/WinJSSandbox.html"; document.body.appendChild(iframe); iframe.contentWindow.onerror = () => { LiveUnit.Assert.fail("Exception in loading WinJS in a display:none iframe"); }; iframe.onload = complete; } } } LiveUnit.registerTestClass("CorsicaTests.AccentTests");
the_stack
import 'nativescript-tslib'; import {BackgroundGeolocation} from "./background-geolocation"; import "./HeadlessJobService"; import "./HeadlessBroadcastReceiver"; import app = require('application'); declare var com: any; let TSConfig = com.transistorsoft.locationmanager.adapter.TSConfig; let TSCallback = com.transistorsoft.locationmanager.adapter.callback.TSCallback; let TSLocationCallback = com.transistorsoft.locationmanager.adapter.callback.TSLocationCallback; let TSLocation = com.transistorsoft.locationmanager.location.TSLocation; let TSPlayServicesConnectErrorCallback = com.transistorsoft.locationmanager.adapter.callback.TSPlayServicesConnectErrorCallback; let TSSyncCallback = com.transistorsoft.locationmanager.adapter.callback.TSSyncCallback; let TSGetLocationsCallback = com.transistorsoft.locationmanager.adapter.callback.TSGetLocationsCallback; let TSGetCountCallback = com.transistorsoft.locationmanager.adapter.callback.TSGetCountCallback; let TSInsertLocationCallback = com.transistorsoft.locationmanager.adapter.callback.TSInsertLocationCallback; let TSGetGeofencesCallback = com.transistorsoft.locationmanager.adapter.callback.TSGetGeofencesCallback; let TSGetLogCallback = com.transistorsoft.locationmanager.adapter.callback.TSGetLogCallback; let TSEmailLogCallback = com.transistorsoft.locationmanager.adapter.callback.TSEmailLogCallback; let TSActivityChangeCallback = com.transistorsoft.locationmanager.adapter.callback.TSActivityChangeCallback; let TSHttpResponseCallback = com.transistorsoft.locationmanager.adapter.callback.TSHttpResponseCallback; let TSGeofenceCallback = com.transistorsoft.locationmanager.adapter.callback.TSGeofenceCallback; let TSGeofencesChangeCallback = com.transistorsoft.locationmanager.adapter.callback.TSGeofencesChangeCallback; let TSHeartbeatCallback = com.transistorsoft.locationmanager.adapter.callback.TSHeartbeatCallback; let TSLocationProviderChangeCallback = com.transistorsoft.locationmanager.adapter.callback.TSLocationProviderChangeCallback; let TSScheduleCallback = com.transistorsoft.locationmanager.adapter.callback.TSScheduleCallback; let TSPowerSaveChangeCallback = com.transistorsoft.locationmanager.adapter.callback.TSPowerSaveChangeCallback; let TSEnabledChangeCallback = com.transistorsoft.locationmanager.adapter.callback.TSEnabledChangeCallback; let TSConnectivityChangeCallback = com.transistorsoft.locationmanager.adapter.callback.TSConnectivityChangeCallback; let TSCurrentPositionRequest = com.transistorsoft.locationmanager.location.TSCurrentPositionRequest; let TSWatchPositionRequest = com.transistorsoft.locationmanager.location.TSWatchPositionRequest; let TSSensors = com.transistorsoft.locationmanager.util.Sensors; let TSGeofence = com.transistorsoft.locationmanager.geofence.TSGeofence; let TSLog = com.transistorsoft.locationmanager.logger.TSLog; let TAG = "TSLocationnManager"; let REQUEST_ACTION_START = 1; let REQUEST_ACTION_GET_CURRENT_POSITION = 2; let REQUEST_ACTION_START_GEOFENCES = 3; let emptyFn = function() {}; let HEADLESS_JOB_SERVICE = "com.transistorsoft.backgroundgeolocation.HeadlessJobService"; // Inform adapter.BackgroundGeolocation when Activity is destroyed. app.android.on(app.AndroidApplication.activityDestroyedEvent, function(args) { console.log('[BackgroundGeolocation] onActivityDestroyedEvent -', args.activity); if (!app.android.startActivity) { Api.onActivityDestroyed(args); } }); class Api { private static forceReload: boolean; private static intent:android.content.Intent = null; public static onActivityDestroyed(args) { com.transistorsoft.locationmanager.adapter.BackgroundGeolocation.getInstance(app.android.context.getApplicationContext()).onActivityDestroy(); this.intent = null; } public static addListener(event:any, success:Function, failure?:Function) { failure = failure || emptyFn; var cb; switch (event) { case 'location': cb = this.createLocationCallback(success, failure); this.getAdapter().onLocation(cb); break; case 'motionchange': cb = this.createMotionChangeCallback(success); this.getAdapter().onMotionChange(cb); break; case 'activitychange': cb = this.createActivityChangeCallback(success); this.getAdapter().onActivityChange(cb); break; case 'http': cb = this.createHttpCallback(success, failure); this.getAdapter().onHttp(cb); break; case 'geofence': cb = this.createGeofenceCallback(success); this.getAdapter().onGeofence(cb); break; case 'geofenceschange': cb = this.createGeofencesChangeCallback(success); this.getAdapter().onGeofencesChange(cb); break; case 'schedule': cb = this.createScheduleCallback(success); this.getAdapter().onSchedule(cb); break; case 'heartbeat': cb = this.createHeartbeatCallback(success); this.getAdapter().onHeartbeat(cb); break; case 'providerchange': cb = this.createProviderChangeCallback(success); this.getAdapter().onLocationProviderChange(cb); break; case 'powersavechange': cb = this.createPowerSaveChangeCallback(success); this.getAdapter().onPowerSaveChange(cb); break; case 'enabledchange': cb = this.createEnabledChangeCallback(success); this.getAdapter().onEnabledChange(cb); break; case 'connectivitychange': cb = this.createConnectivityChangeCallback(success); this.getAdapter().onConnectivityChange(cb); break; } return cb; } protected static removeListener(event:string, callback:Function) { return new Promise((resolve, reject) => { this.getAdapter().removeListener(event, callback); resolve(); }); } public static removeListeners(event?:string) { return new Promise((resolve, reject) => { if (event) { this.getAdapter().removeListeners(event); } else { this.getAdapter().removeListeners(); } resolve(); }); } /** * Configuration Methods */ public static ready(params:any) { return new Promise((resolve, reject) => { let config = TSConfig.getInstance(this.getContext()); if (config.isFirstBoot()) { config.updateWithJSONObject(new org.json.JSONObject(JSON.stringify(this.applyHeadlessJobService(params)))); } else if (params.reset === true) { config.reset(); config.updateWithJSONObject(new org.json.JSONObject(JSON.stringify(this.applyHeadlessJobService(params)))); } this.getAdapter().ready(new TSCallback({ onSuccess: () => { resolve(JSON.parse(config.toJson().toString())) }, onFailure: (error:string) => { reject(error) } })); }); } public static configure(params:any) { return new Promise((resolve, reject) => { let config = TSConfig.getInstance(this.getContext()); config.updateWithJSONObject(new org.json.JSONObject(JSON.stringify(this.applyHeadlessJobService(params)))); this.getAdapter().ready(new TSCallback({ onSuccess: () => { resolve(JSON.parse(config.toJson().toString())); }, onFailure: (error:string) => { reject(error); } })); }); } public static setConfig(params:any) { return new Promise((resolve, reject) => { let config = TSConfig.getInstance(this.getContext()); config.updateWithJSONObject(new org.json.JSONObject(JSON.stringify(this.applyHeadlessJobService(params)))); resolve(JSON.parse(config.toJson().toString())); }); } public static reset(params:any) { return new Promise((resolve, reject) => { let config = TSConfig.getInstance(this.getContext()); config.reset(); config.updateWithJSONObject(new org.json.JSONObject(JSON.stringify(this.applyHeadlessJobService(params)))); resolve(JSON.parse(config.toJson().toString())); }); } public static getState() { return new Promise((resolve, reject) => { let config = TSConfig.getInstance(this.getContext()); resolve(JSON.parse(config.toJson().toString())); }); } /** * Tracking Methods */ public static start() { return new Promise((resolve, reject) => { var adapter = this.getAdapter(); let config = TSConfig.getInstance(this.getContext()); adapter.start(new TSCallback({ onSuccess: () => { resolve(JSON.parse(config.toJson().toString())); }, onFailure: (error:string) => { reject(error); } })); }); } public static stop() { return new Promise((resolve, reject) => { let adapter = this.getAdapter(); let config = TSConfig.getInstance(this.getContext()); adapter.stop(new TSCallback({ onSuccess: function() { resolve(JSON.parse(config.toJson().toString())); }, onFailure: (error:string) => { reject(error); } })); }); } public static changePace(value: boolean) { return new Promise((resolve, reject) => { let adapter = this.getAdapter(); adapter.changePace(value, new TSCallback({ onSuccess: () => { resolve(); }, onFailure: (error:string) => { reject(error); } })); }); } public static startSchedule() { return new Promise((resolve, reject) => { let config = TSConfig.getInstance(this.getContext()); if (this.getAdapter().startSchedule()) { resolve(JSON.parse(config.toJson().toString())); } else { reject("Failed to start schedule. Did you configure a #schedule?"); } }); } public static stopSchedule() { return new Promise((resolve, reject) => { let config = TSConfig.getInstance(this.getContext()); this.getAdapter().stopSchedule(); resolve(JSON.parse(config.toJson().toString())); }); } public static startGeofences() { return new Promise((resolve, reject) => { let config = TSConfig.getInstance(this.getContext()); this.getAdapter().startGeofences(new TSCallback({ onSuccess: () => { resolve(JSON.parse(config.toJson().toString())); }, onFailure: (error:string) => { reject(error); } })); }); } public static getCurrentPosition(options?:any) { return new Promise((resolve, reject) => { let builder = new TSCurrentPositionRequest.Builder(this.getContext()); if (typeof(options.samples) === 'number') { builder.setSamples(options.samples); } if (typeof(options.extras) === 'object') { builder.setExtras(new org.json.JSONObject(JSON.stringify(options.extras))); } if (typeof(options.persist) === 'boolean') { builder.setPersist(options.persist); } if (typeof(options.timeout) === 'number') { builder.setTimeout(options.timeout); } if (typeof(options.maximumAge) === 'number') { builder.setMaximumAge(new java.lang.Long(options.maximumAge)); } if (typeof(options.desiredAccuracy) === 'number') { builder.setDesiredAccuracy(options.desiredAccuracy); } builder.setCallback(new TSLocationCallback({ onLocation: (tsLocation:any) => { resolve(JSON.parse(tsLocation.toJson().toString())); }, onError: (error:any) => { reject(error); } })); this.getAdapter().getCurrentPosition(builder.build()); }); } public static watchPosition(success:Function, failure:Function, options:any) { let builder = new TSWatchPositionRequest.Builder(this.getContext()); if (typeof(options.interval) === 'number') { builder.setInterval(new java.lang.Long(options.interval)); } if (typeof(options.extras) === 'object') { builder.setExtras(new org.json.JSONObject(JSON.stringify(options.extras))); } if (typeof(options.persist) === 'boolean') { builder.setPersist(options.persist); } if (typeof(options.desiredAccuracy) === 'number') { builder.setDesiredAccuracy(options.desiredAccuracy); } builder.setCallback(new TSLocationCallback({ onLocation: (tsLocation:any) => { success(JSON.parse(tsLocation.toJson().toString())); }, onError: (error:number) => { failure(error); } })); this.getAdapter().watchPosition(builder.build()); } public static stopWatchPosition() { return new Promise((resolve, reject) => { this.getAdapter().stopWatchPosition(new TSCallback({ onSuccess: () => { resolve(); }, onFailure: (error: string) => { reject(error); } })); }); } public static getOdometer() { return new Promise((resolve, reject) => { resolve(this.getAdapter().getOdometer()); }); } public static setOdometer(value:number) { return new Promise((resolve, reject) => { this.getAdapter().setOdometer(new java.lang.Float(value), new TSLocationCallback({ onLocation: (tsLocation:any) => { resolve(JSON.parse(tsLocation.toJson().toString())); }, onError: function(error:number) { reject(error); } })); }); } public static resetOdometer(value:number) { return this.setOdometer(0); } /** * HTTP & Persistence Methods */ public static sync() { return new Promise((resolve, reject) => { this.getAdapter().sync(new TSSyncCallback({ onSuccess: function(records:any) { let size = records.size(); let result = []; for (let i=0;i<size;i++) { let record = records.get(i); result.push(JSON.parse(record.json.toString())); } resolve(result); }, onFailure: function(error:string) { reject(error); } })); }); } public static getLocations() { return new Promise((resolve, reject) => { this.getAdapter().getLocations(new TSGetLocationsCallback({ onSuccess: (records:any) => { let size = records.size(); let result = []; for (let i=0;i<size;i++) { let record = records.get(i); result.push(JSON.parse(record.json.toString())); } resolve(result); }, onFailure: (error:string) => { reject(error); } })); }); } public static getCount() { return new Promise((resolve, reject) => { this.getAdapter().getCount(new TSGetCountCallback({ onSuccess: (count:number) => { resolve(count); }, onFailure: (error:string) => { reject(error); } })); }); } public static insertLocation(data:any) { return new Promise((resolve, reject) => { let callback = new TSInsertLocationCallback({ onSuccess: (uuid:string) => { resolve(uuid); }, onFailure: (error: string) => { reject(error); } }); this.getAdapter().insertLocation(new org.json.JSONObject(JSON.stringify(data)), callback); }); } // @deprecated public static clearDatabase() { return this.destroyLocations(); } public static destroyLocations() { return new Promise((resolve, reject) => { this.getAdapter().destroyLocations(new TSCallback({ onSuccess: () => { resolve(); }, onFailure: (error:string) => { reject(error); } })); }); } /** * Geofencing Methods */ public static addGeofence(params:any) { return new Promise((resolve, reject) => { try { this.getAdapter().addGeofence(this.buildGeofence(params), new TSCallback({ onSuccess: () => { resolve(); }, onFailure: (error:string) => { reject(error); } })); } catch (error) { reject(error.getMessage()); } }); } public static removeGeofence(identifier:string) { return new Promise((resolve, reject) => { this.getAdapter().removeGeofence(identifier, new TSCallback({ onSuccess: () => { resolve(); }, onFailure: (error:string) => { reject(error); } })); }); } public static addGeofences(geofences:Array<any>) { return new Promise((resolve, reject) => { let list = new java.util.ArrayList(); for (var n=0,len=geofences.length;n<len;n++) { try { list.add(this.buildGeofence(geofences[n])); } catch (error) { reject(error.getMessage()); return; } } this.getAdapter().addGeofences(list, new TSCallback({ onSuccess: () => { resolve(); }, onFailure: (error:string) => { reject(error); } })); }); } private static buildGeofence(params:any) { let builder = new TSGeofence.Builder(); builder.setIdentifier(params.identifier); builder.setLatitude(params.latitude); builder.setLongitude(params.longitude); builder.setRadius(params.radius); if (typeof(params.notifyOnEntry) === 'boolean') { builder.setNotifyOnEntry(params.notifyOnEntry); } if (typeof(params.notifyOnExit) === 'boolean') { builder.setNotifyOnExit(params.notifyOnExit); } if (typeof(params.notifyOnDwell) === 'boolean') { builder.setNotifyOnDwell(params.notifyOnDwell); } if (typeof(params.loiteringDelay) === 'number') { builder.setLoiteringDelay(params.loiteringDelay); } if (typeof(params.extras) === 'object') { builder.setExtras(new org.json.JSONObject(JSON.stringify(params.extras))); } return builder.build(); } public static removeGeofences(geofences?:Array<string>) { return new Promise((resolve, reject) => { // Handle case where no geofences are provided (ie: remove all geofences). geofences = geofences || []; let identifiers = new java.util.ArrayList(); geofences.forEach((identifier) => { identifiers.add(identifier); }); this.getAdapter().removeGeofences(identifiers, new TSCallback({ onSuccess: () => { resolve(); }, onFailure: (error:string) => { reject(error); } })); }); } public static getGeofences() { return new Promise((resolve, reject) => { this.getAdapter().getGeofences(new TSGetGeofencesCallback({ onSuccess: (records:any) => { let size = records.size(); let result = []; for (let i=0;i<size;i++) { let geofence = records.get(i); result.push(JSON.parse(geofence.toJson())); } resolve(result); }, onFailure: (error:string) => { reject(error); } })); }); } /** * Logging & Debug methods */ public static getLog() { return new Promise((resolve, reject) => { this.getAdapter().getLog(new TSGetLogCallback({ onSuccess: (log:string) => { resolve(log) }, onFailure: (error:string) => { reject(error); } })); }); } public static emailLog(email:string) { return new Promise((resolve, reject) => { this.getAdapter().emailLog(email, app.android.foregroundActivity, new TSEmailLogCallback({ onSuccess: () => { resolve() }, onFailure: (error:string) => { reject(error); } })); }); } public static destroyLog() { return new Promise((resolve, reject) => { this.getAdapter().destroyLog(new TSCallback({ onSuccess: () => { resolve(); }, onFailure: (error:string) => { reject(error); } })); }); } public static getSensors() { return new Promise((resolve, reject) => { let sensors = TSSensors.getInstance(app.android.context); let result = { "platform": "android", "accelerometer": sensors.hasAccelerometer(), "magnetometer": sensors.hasMagnetometer(), "gyroscope": sensors.hasGyroscope(), "significant_motion": sensors.hasSignificantMotion() }; resolve(result); }); } public static isPowerSaveMode(success: Function, failure?:Function) { return new Promise((resolve, reject) => { let isPowerSaveMode = this.getAdapter().isPowerSaveMode(); resolve(isPowerSaveMode); }); } public static startBackgroundTask(success:Function) { // Just return 0 for compatibility with iOS API. Android has no concept of these iOS-only background-tasks. return new Promise((resolve, reject) => { resolve(0); }); } public static finish(taskId:number) { // Just an empty function for compatibility with iOS. Android has no concept of these iOS-only background-tasks. } public static playSound(soundId) { return new Promise((resolve, reject) => { this.getAdapter().startTone(soundId); resolve(); }); } public static log(level, msg) { TSLog.log(level, msg); } private static createLocationCallback(success:Function, failure?:Function) { failure = failure || emptyFn; return new TSLocationCallback({ onLocation: (tsLocation:any) => { success(JSON.parse(tsLocation.toJson().toString())); }, onError: (error) => { failure(error); } }); } private static createMotionChangeCallback(callback:Function) { return new TSLocationCallback({ onLocation: (tsLocation:any) => { let isMoving = tsLocation.getIsMoving(); callback(isMoving, JSON.parse(tsLocation.toJson().toString())); }, onError: (error:number) => { } }); } private static createHttpCallback(success:Function, failure?:Function) { return new TSHttpResponseCallback({ onHttpResponse: function(response:any) { let params = { success: response.isSuccess().booleanValue(), status: response.status, responseText: response.responseText }; if (response.isSuccess().booleanValue()) { success(params); } else { failure(params); } } }); } private static createActivityChangeCallback(callback:Function) { return new TSActivityChangeCallback({ onActivityChange: (event:any) => { callback(JSON.parse(event.toJson().toString())); } }); } private static createGeofenceCallback(callback:Function) { return new TSGeofenceCallback({ onGeofence: (event:any) => { callback(JSON.parse(event.toJson().toString())); } }); } private static createGeofencesChangeCallback(callback:Function) { return new TSGeofencesChangeCallback({ onGeofencesChange: (event:any) => { callback(JSON.parse(event.toJson().toString())); } }); } private static createScheduleCallback(callback:Function) { return new TSScheduleCallback({ onSchedule: (event:any) => { callback(JSON.parse(event.toJson().toString())); } }) } private static createProviderChangeCallback(callback:Function) { return new TSLocationProviderChangeCallback({ onLocationProviderChange: (event:any) => { callback(JSON.parse(event.toJson().toString())); } }) } private static createHeartbeatCallback(callback:Function) { return new TSHeartbeatCallback({ onHeartbeat: (event:any) => { callback(JSON.parse(event.toJson().toString())); } }) } private static createPowerSaveChangeCallback(callback:Function) { return new TSPowerSaveChangeCallback({ onPowerSaveChange: (isPowerSaveMode) => { callback(isPowerSaveMode); } }); } private static createEnabledChangeCallback(callback:Function) { return new TSEnabledChangeCallback({ onEnabledChange: (enabled:boolean) => { console.log('- enabledchange: ', enabled); callback({enabled: enabled}); } }); } private static createConnectivityChangeCallback(callback:Function) { return new TSConnectivityChangeCallback({ onConnectivityChange: (event:any) => { callback({connected: event.hasConnection()}); } }); } private static applyHeadlessJobService(params):any { params.headlessJobService = HEADLESS_JOB_SERVICE; return params; } private static init() { if (!app.android.startActivity || (this.intent !== null)) { return; } this.intent = app.android.startActivity.getIntent(); // Handle Google Play Services errors this.getAdapter().onPlayServicesConnectError(new TSPlayServicesConnectErrorCallback({ onPlayServicesConnectError: (errorCode:number) => { this.handleGooglePlayServicesConnectError(errorCode); } })); let config = TSConfig.getInstance(this.getContext()); config.useCLLocationAccuracy(new java.lang.Boolean(true)); } private static getContext() { return app.android.context; } private static getIntent() { let activity = (app.android.startActivity) ? app.android.startActivity : app.android.foregroundActivity; return (activity) ? activity.getIntent() : this.intent; } protected static getAdapter(): any { if (!this.intent) { this.init(); } return com.transistorsoft.locationmanager.adapter.BackgroundGeolocation.getInstance(app.android.context.getApplicationContext(), this.getIntent()); } private static handleGooglePlayServicesConnectError(errorCode:number) { com.google.android.gms.common.GoogleApiAvailability.getInstance().getErrorDialog(app.android.foregroundActivity, errorCode, 1001).show(); } } BackgroundGeolocation.mountNativeApi(Api); export {BackgroundGeolocation};
the_stack
import { EventEmitter } from "./EventEmitter"; import { UkuleleUtil } from "../util/UkuleleUtil"; import { BoundItemAttributeFactory } from './BoundItemAttributeFactory'; import { BoundItemExpression } from '../model/BoundItemExpression'; import { BoundItemInnerText } from '../model/BoundItemInnerText'; import { BoundItemRepeat } from '../model/BoundItemRepeat'; import { BoundItemComponentAttribute } from "../model/BoundItemComponentAttribute"; import { elementChangedBinder } from "./ElementActionBinder"; import { IUkulele } from "./IUkulele"; import { EventListener } from "../extend/EventListener"; import { Selector } from "../extend/Selector"; import { Event as UkuEvent } from "./Event"; export class Analyzer extends EventEmitter { private uku: IUkulele; private defMgr; static ANALYIZE_COMPLETED: string = 'analyizeCompleted'; constructor(_uku: IUkulele) { super(); this.uku = _uku; this.defMgr = this.uku._internal_getDefinitionManager(); } public analyizeElement(ele): void { this.searchComponent(ele).then((element) => { this.searchExpression(element); this.searchUkuAttribute(element); //this.defMgr.copyAllController(); if (this.hasListener(Analyzer.ANALYIZE_COMPLETED)) { this.dispatchEvent(new UkuEvent(Analyzer.ANALYIZE_COMPLETED, element)); } }); } private sortAttributes(subElement): Array<any> { let orderAttrs = []; let listenerAttrs = []; for (let i = 0; i < subElement.attributes.length; i++) { let attribute = subElement.attributes[i]; if (attribute.nodeName.search("uku-on") !== -1) { //orderAttrs.push(attribute); listenerAttrs.push(attribute); } else { orderAttrs.push(attribute); } } orderAttrs = orderAttrs.concat(listenerAttrs); return orderAttrs; } private searchUkuAttribute(element): void { let subElements = []; //scan element which has uku-* tag let isSelfHasUkuTag = Selector.fuzzyFind(element, 'uku-'); if (isSelfHasUkuTag) { subElements.push(isSelfHasUkuTag); } let allChildren = Selector.querySelectorAll(element, "*"); for (let i = 0; i < allChildren.length; i++) { let child: HTMLElement = allChildren[i] as HTMLElement; let matchElement = Selector.fuzzyFind(child, 'uku-'); if (matchElement && !UkuleleUtil.isInRepeat(matchElement)) { subElements.push(matchElement); } } //解析绑定 attribute,注册event for (let n = 0; n < subElements.length; n++) { let subElement = subElements[n]; let orderAttrs = this.sortAttributes(subElement); for (let j = 0; j < orderAttrs.length; j++) { let attribute = orderAttrs[j]; if (UkuleleUtil.searchUkuAttrTag(attribute.nodeName) > -1) { let tempArr = attribute.nodeName.split('-'); tempArr.shift(); let attrName = tempArr.join('-'); if (attrName !== "application") { if (attrName.search('on') === 0) { //is an event if (!UkuleleUtil.isRepeat(subElement) && !UkuleleUtil.isInRepeat(subElement)) { this.dealWithEvent(subElement, attrName); } } else if (attrName.search('repeat') !== -1) { //is an repeat this.dealWithRepeat(subElement); } else { //is an attribute if (!UkuleleUtil.isRepeat(subElement) && !UkuleleUtil.isInRepeat(subElement)) { if (attrName !== "text") { this.dealWithAttribute(subElement, attrName); } else { this.dealWithInnerText(subElement); } } } } } } } } private async searchComponent(element): Promise<any> { let comp = this.defMgr.getComponent(element.localName); if (comp) { if (!comp.lazy) { let attrs = element.attributes; let compDef = this.defMgr.getComponentsDefinition()[comp.tagName]; if (!UkuleleUtil.isRepeat(element) && !UkuleleUtil.isInRepeat(element)) { return this.dealWithComponent(element, compDef.template, compDef.controllerClazz, attrs); } else { return element; } } else { await this.defMgr.addLazyComponentDefinition(comp.tagName, comp.templateUrl); let attrs = element.attributes; let compDef = this.defMgr.getComponentsDefinition()[comp.tagName]; if (!UkuleleUtil.isRepeat(element) && !UkuleleUtil.isInRepeat(element)) { return this.dealWithComponent(element, compDef.template, compDef.controllerClazz, attrs); } else { return element; } } } else { if (element.children && element.children.length > 0) { for (let i = 0; i < element.children.length; i++) { let child = element.children[i]; await this.searchComponent(child); } return element; } else { return element; } } } private async dealWithComponent(tag, template, Clazz, attrs): Promise<any> { let time = new Date().getTime(); let randomAlias = 'cc_' + Math.floor(time * Math.random()).toString(); //should consider white space between characters template = template.replace(new RegExp("\'cc\\.", 'gm'), "'" + randomAlias + '.'); template = template.replace(new RegExp('"cc\\.', 'gm'), '"' + randomAlias + '.'); template = template.replace(new RegExp('\{\{cc\\.', 'gm'), "{{" + randomAlias + '.'); template = template.replace(new RegExp(' cc\\.', 'gm'), ' ' + randomAlias + '.'); template = template.replace(new RegExp('\\(cc\\.', 'gm'), '(' + randomAlias + '.'); template = template.replace(new RegExp('\\,cc\\.', 'gm'), ',' + randomAlias + '.'); template = template.replace(new RegExp('\\.cc\\.', 'gm'), '.' + randomAlias + '.'); template = template.replace(new RegExp('\\!cc\\.', 'gm'), '!' + randomAlias + '.'); let tempFragment = document.createElement('div'); tempFragment.insertAdjacentHTML('afterBegin' as InsertPosition, template); if (tempFragment.children.length > 1) { template = tempFragment.outerHTML; } tag.insertAdjacentHTML('beforeBegin', template); let htmlDom = tag.previousElementSibling; htmlDom.classList.add(tag.localName); let cc; if (Clazz) { cc = new Clazz(this.uku); cc._dom = htmlDom; cc.fire = (eventType: string, data: any, bubbles: boolean = false, cancelable: boolean = true) => { let event = new CustomEvent(eventType.toLowerCase(), { "bubbles": bubbles, "cancelable": cancelable }); event['data'] = data; cc._dom.dispatchEvent(event); }; this.uku.registerController(randomAlias, cc); for (let i = 0; i < attrs.length; i++) { let attr = attrs[i]; //todo need Refactor if (UkuleleUtil.searchUkuAttrTag(attr.nodeName) !== 0 || attr.nodeName.search("uku-on") !== -1 || attr.nodeName === "uku-render" || attr.nodeName === "uku-visible") { htmlDom.setAttribute(attr.nodeName, attr.nodeValue); } else { let tagName = UkuleleUtil.getAttrFromUkuTag(attr.nodeName, true); let controllerModels = this.defMgr.getControllerModelByName(attr.nodeValue); if (controllerModels && controllerModels.length > 0) { let boundItem = new BoundItemComponentAttribute(attr.nodeValue, tagName, cc, this.uku); let controllers = []; controllerModels.forEach(controllerModel => { controllerModel.addBoundItem(boundItem); controllers.push(controllerModel.controllerInstance); }); boundItem.render(controllers); }else{ //native value, not expression let boundItem = new BoundItemComponentAttribute(attr.nodeValue, tagName, cc, this.uku); boundItem.render([]); } } } } else { for (let i = 0; i < attrs.length; i++) { let attr = attrs[i]; //todo:need Refactor if (UkuleleUtil.searchUkuAttrTag(attr.nodeName) !== 0 || attr.nodeName.search("uku-on") !== -1 || attr.nodeName === "uku-render" || attr.nodeName === "uku-visible") { htmlDom.setAttribute(attr.nodeName, attr.nodeValue); } } } tag.parentNode.removeChild(tag); if (htmlDom.children && htmlDom.children.length > 0) { for (let j = 0; j < htmlDom.children.length; j++) { let child = htmlDom.children[j]; await this.searchComponent(child); } if (cc && cc._initialized && typeof (cc._initialized) === 'function') { cc._initialized(randomAlias,cc._dom); } return htmlDom; } else { if (cc && cc._initialized && typeof (cc._initialized) === 'function') { cc._initialized(randomAlias,cc._dom); } return htmlDom; } } //todo: 处理 tag之间使用{{}}括起的表达式,用以显示文字 private searchExpression(element: HTMLElement): void { if (UkuleleUtil.searchUkuExpTag(Selector.directText(element)) !== -1) { if (!UkuleleUtil.isRepeat(element) && !UkuleleUtil.isInRepeat(element)) { //normal expression this.dealWithExpression(element); } } for (let i = 0; i < element.children.length; i++) { this.searchExpression(element.children[i] as HTMLElement); } } private dealWithExpression(element) { //通常的花括号声明方式 let expression = Selector.directText(element); if (UkuleleUtil.searchUkuExpTag(expression) !== -1) { let attr = expression.slice(2, -2); let controllerModels = this.defMgr.getControllerModelByName(attr); if (controllerModels && controllerModels.length > 0) { let boundItem = new BoundItemExpression(attr, expression, element, this.uku); let controllers = []; controllerModels.forEach(controllerModel => { controllerModel.addBoundItem(boundItem); controllers.push(controllerModel.controllerInstance); }); boundItem.render(controllers); } } } //处理绑定的attribute private dealWithAttribute: Function = function (element, tagName) { let attr = element.getAttribute("uku-" + tagName); //let elementName = element.tagName; let controllerModels = this.defMgr.getControllerModelByName(attr); if (controllerModels && controllerModels.length > 0) { let boundItem = BoundItemAttributeFactory.getInstance().generateInstance(attr, tagName, element, this.uku); let controllers = []; controllerModels.forEach(controllerModel => { controllerModel.addBoundItem(boundItem); elementChangedBinder(element, tagName, controllerModel, this.uku.refresh, this.uku); controllers.push(controllerModel.controllerInstance) }); boundItem.render(controllers); } } //处理 uku-text private dealWithInnerText(element) { let attr = element.getAttribute("uku-text"); if (attr) { let controllerModels = this.defMgr.getControllerModelByName(attr); if (controllerModels && controllerModels.length > 0) { let boundItem = new BoundItemInnerText(attr, element, this.uku); let controllers = []; controllerModels.forEach(controllerModel => { controllerModel.addBoundItem(boundItem); controllers.push(controllerModel.controllerInstance); }); boundItem.render(controllers); } } } //处理 事件 event private dealWithEvent(element, eventName) { let expression = element.getAttribute("uku-" + eventName); let eventNameInListener = eventName.substring(2); eventNameInListener = eventNameInListener.toLowerCase(); let controllerModels = this.defMgr.getControllerModelByName(expression); if(!controllerModels || controllerModels.length === 0){ controllerModels = []; } EventListener.addEventListener(element, eventNameInListener, (event) => { let alias_list = []; controllerModels.forEach(controllerModel => { //this.defMgr.copyControllerInstance(controllerModel.controllerInstance, controllerModels.alias); alias_list.push(controllerModel.alias); }); let index = UkuleleUtil.searchUkuFuncArg(expression); if(index === -1){ // is an expression, not a function let handler = new Function("event","return " + expression); console.log(handler.toString()); handler(event); }else{ // is a function let i = expression.search(/\(/); let arg = 'event'; if(expression[i+1] !== ')'){ // has argument arg = 'event,' } let arr = expression.split('('); arr[1] = arg + arr[1]; let new_expression = arr.join("("); (function(e){ let tempScope = {}; tempScope['event'] = e; eval(new_expression); tempScope = null; })(event); } this.uku.refresh(alias_list, element); }); } //处理 repeat private dealWithRepeat(element) { let repeatExpression = element.getAttribute("uku-repeat"); let tempArr = repeatExpression.split(' in '); let itemName = tempArr[0]; let attr = tempArr[1]; let controllerModels = this.defMgr.getControllerModelByName(attr); if (controllerModels && controllerModels.length > 0) { let controllers = []; //let controllerInst = controllerModel.controllerInstance; let boundItem = new BoundItemRepeat(attr, itemName, element, this.uku); controllerModels.forEach(controllerModel => { controllerModel.addBoundItem(boundItem); controllers.push(controllerModel.controllerInstance); }); boundItem.render(controllers); } } }
the_stack
import { GraphQLResolveInfo, GraphQLSchema } from 'graphql'; import { IResolvers } from 'graphql-tools/dist/Interfaces'; import { Options } from 'graphql-binding'; import { makePrismaBindingClass, BasePrismaOptions } from 'prisma-binding'; export interface Query { users: <T = User[]>( args: { where?: UserWhereInput; orderBy?: UserOrderByInput; skip?: Int; after?: String; before?: String; first?: Int; last?: Int; }, info?: GraphQLResolveInfo | string, options?: Options ) => Promise<T>; user: <T = User | null>( args: { where: UserWhereUniqueInput }, info?: GraphQLResolveInfo | string, options?: Options ) => Promise<T>; usersConnection: <T = UserConnection>( args: { where?: UserWhereInput; orderBy?: UserOrderByInput; skip?: Int; after?: String; before?: String; first?: Int; last?: Int; }, info?: GraphQLResolveInfo | string, options?: Options ) => Promise<T>; node: <T = Node | null>( args: { id: ID_Output }, info?: GraphQLResolveInfo | string, options?: Options ) => Promise<T>; } export interface Mutation { createUser: <T = User>( args: { data: UserCreateInput }, info?: GraphQLResolveInfo | string, options?: Options ) => Promise<T>; updateUser: <T = User | null>( args: { data: UserUpdateInput; where: UserWhereUniqueInput }, info?: GraphQLResolveInfo | string, options?: Options ) => Promise<T>; deleteUser: <T = User | null>( args: { where: UserWhereUniqueInput }, info?: GraphQLResolveInfo | string, options?: Options ) => Promise<T>; upsertUser: <T = User>( args: { where: UserWhereUniqueInput; create: UserCreateInput; update: UserUpdateInput; }, info?: GraphQLResolveInfo | string, options?: Options ) => Promise<T>; updateManyUsers: <T = BatchPayload>( args: { data: UserUpdateInput; where?: UserWhereInput }, info?: GraphQLResolveInfo | string, options?: Options ) => Promise<T>; deleteManyUsers: <T = BatchPayload>( args: { where?: UserWhereInput }, info?: GraphQLResolveInfo | string, options?: Options ) => Promise<T>; } export interface Subscription { user: <T = UserSubscriptionPayload | null>( args: { where?: UserSubscriptionWhereInput }, info?: GraphQLResolveInfo | string, options?: Options ) => Promise<AsyncIterator<T>>; } export interface Exists { User: (where?: UserWhereInput) => Promise<boolean>; } export interface Prisma { query: Query; mutation: Mutation; subscription: Subscription; exists: Exists; request: <T = any>( query: string, variables?: { [key: string]: any } ) => Promise<T>; delegate( operation: 'query' | 'mutation', fieldName: string, args: { [key: string]: any; }, infoOrQuery?: GraphQLResolveInfo | string, options?: Options ): Promise<any>; delegateSubscription( fieldName: string, args?: { [key: string]: any; }, infoOrQuery?: GraphQLResolveInfo | string, options?: Options ): Promise<AsyncIterator<any>>; getAbstractResolvers(filterSchema?: GraphQLSchema | string): IResolvers; } export interface BindingConstructor<T> { new (options: BasePrismaOptions): T; } /** * Type Defs */ const typeDefs = `type AggregateUser { count: Int! } type BatchPayload { """The number of nodes that have been affected by the Batch operation.""" count: Long! } scalar DateTime """ The \`Long\` scalar type represents non-fractional signed whole numeric values. Long can represent values between -(2^63) and 2^63 - 1. """ scalar Long type Mutation { createUser(data: UserCreateInput!): User! updateUser(data: UserUpdateInput!, where: UserWhereUniqueInput!): User deleteUser(where: UserWhereUniqueInput!): User upsertUser(where: UserWhereUniqueInput!, create: UserCreateInput!, update: UserUpdateInput!): User! updateManyUsers(data: UserUpdateInput!, where: UserWhereInput): BatchPayload! deleteManyUsers(where: UserWhereInput): BatchPayload! } enum MutationType { CREATED UPDATED DELETED } """An object with an ID""" interface Node { """The id of the object.""" id: ID! } """Information about pagination in a connection.""" type PageInfo { """When paginating forwards, are there more items?""" hasNextPage: Boolean! """When paginating backwards, are there more items?""" hasPreviousPage: Boolean! """When paginating backwards, the cursor to continue.""" startCursor: String """When paginating forwards, the cursor to continue.""" endCursor: String } type Query { users(where: UserWhereInput, orderBy: UserOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): [User]! user(where: UserWhereUniqueInput!): User usersConnection(where: UserWhereInput, orderBy: UserOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): UserConnection! """Fetches an object given its ID""" node( """The ID of an object""" id: ID! ): Node } type Subscription { user(where: UserSubscriptionWhereInput): UserSubscriptionPayload } type User implements Node { id: ID! email: String! password: String! name: String! inviteToken: String inviteAccepted: Boolean! emailConfirmed: Boolean! emailConfirmToken: String resetToken: String resetExpires: DateTime deletedAt: DateTime lastLogin: DateTime joinedAt: DateTime! isSuper: Boolean! } """A connection to a list of items.""" type UserConnection { """Information to aid in pagination.""" pageInfo: PageInfo! """A list of edges.""" edges: [UserEdge]! aggregate: AggregateUser! } input UserCreateInput { email: String! password: String! name: String! inviteToken: String inviteAccepted: Boolean emailConfirmed: Boolean emailConfirmToken: String resetToken: String resetExpires: DateTime deletedAt: DateTime lastLogin: DateTime joinedAt: DateTime! isSuper: Boolean } """An edge in a connection.""" type UserEdge { """The item at the end of the edge.""" node: User! """A cursor for use in pagination.""" cursor: String! } enum UserOrderByInput { id_ASC id_DESC email_ASC email_DESC password_ASC password_DESC name_ASC name_DESC inviteToken_ASC inviteToken_DESC inviteAccepted_ASC inviteAccepted_DESC emailConfirmed_ASC emailConfirmed_DESC emailConfirmToken_ASC emailConfirmToken_DESC resetToken_ASC resetToken_DESC resetExpires_ASC resetExpires_DESC deletedAt_ASC deletedAt_DESC lastLogin_ASC lastLogin_DESC joinedAt_ASC joinedAt_DESC isSuper_ASC isSuper_DESC updatedAt_ASC updatedAt_DESC createdAt_ASC createdAt_DESC } type UserPreviousValues { id: ID! email: String! password: String! name: String! inviteToken: String inviteAccepted: Boolean! emailConfirmed: Boolean! emailConfirmToken: String resetToken: String resetExpires: DateTime deletedAt: DateTime lastLogin: DateTime joinedAt: DateTime! isSuper: Boolean! } type UserSubscriptionPayload { mutation: MutationType! node: User updatedFields: [String!] previousValues: UserPreviousValues } input UserSubscriptionWhereInput { """Logical AND on all given filters.""" AND: [UserSubscriptionWhereInput!] """Logical OR on all given filters.""" OR: [UserSubscriptionWhereInput!] """Logical NOT on all given filters combined by AND.""" NOT: [UserSubscriptionWhereInput!] """ The subscription event gets dispatched when it's listed in mutation_in """ mutation_in: [MutationType!] """ The subscription event gets only dispatched when one of the updated fields names is included in this list """ updatedFields_contains: String """ The subscription event gets only dispatched when all of the field names included in this list have been updated """ updatedFields_contains_every: [String!] """ The subscription event gets only dispatched when some of the field names included in this list have been updated """ updatedFields_contains_some: [String!] node: UserWhereInput } input UserUpdateInput { email: String password: String name: String inviteToken: String inviteAccepted: Boolean emailConfirmed: Boolean emailConfirmToken: String resetToken: String resetExpires: DateTime deletedAt: DateTime lastLogin: DateTime joinedAt: DateTime isSuper: Boolean } input UserWhereInput { """Logical AND on all given filters.""" AND: [UserWhereInput!] """Logical OR on all given filters.""" OR: [UserWhereInput!] """Logical NOT on all given filters combined by AND.""" NOT: [UserWhereInput!] id: ID """All values that are not equal to given value.""" id_not: ID """All values that are contained in given list.""" id_in: [ID!] """All values that are not contained in given list.""" id_not_in: [ID!] """All values less than the given value.""" id_lt: ID """All values less than or equal the given value.""" id_lte: ID """All values greater than the given value.""" id_gt: ID """All values greater than or equal the given value.""" id_gte: ID """All values containing the given string.""" id_contains: ID """All values not containing the given string.""" id_not_contains: ID """All values starting with the given string.""" id_starts_with: ID """All values not starting with the given string.""" id_not_starts_with: ID """All values ending with the given string.""" id_ends_with: ID """All values not ending with the given string.""" id_not_ends_with: ID email: String """All values that are not equal to given value.""" email_not: String """All values that are contained in given list.""" email_in: [String!] """All values that are not contained in given list.""" email_not_in: [String!] """All values less than the given value.""" email_lt: String """All values less than or equal the given value.""" email_lte: String """All values greater than the given value.""" email_gt: String """All values greater than or equal the given value.""" email_gte: String """All values containing the given string.""" email_contains: String """All values not containing the given string.""" email_not_contains: String """All values starting with the given string.""" email_starts_with: String """All values not starting with the given string.""" email_not_starts_with: String """All values ending with the given string.""" email_ends_with: String """All values not ending with the given string.""" email_not_ends_with: String password: String """All values that are not equal to given value.""" password_not: String """All values that are contained in given list.""" password_in: [String!] """All values that are not contained in given list.""" password_not_in: [String!] """All values less than the given value.""" password_lt: String """All values less than or equal the given value.""" password_lte: String """All values greater than the given value.""" password_gt: String """All values greater than or equal the given value.""" password_gte: String """All values containing the given string.""" password_contains: String """All values not containing the given string.""" password_not_contains: String """All values starting with the given string.""" password_starts_with: String """All values not starting with the given string.""" password_not_starts_with: String """All values ending with the given string.""" password_ends_with: String """All values not ending with the given string.""" password_not_ends_with: String name: String """All values that are not equal to given value.""" name_not: String """All values that are contained in given list.""" name_in: [String!] """All values that are not contained in given list.""" name_not_in: [String!] """All values less than the given value.""" name_lt: String """All values less than or equal the given value.""" name_lte: String """All values greater than the given value.""" name_gt: String """All values greater than or equal the given value.""" name_gte: String """All values containing the given string.""" name_contains: String """All values not containing the given string.""" name_not_contains: String """All values starting with the given string.""" name_starts_with: String """All values not starting with the given string.""" name_not_starts_with: String """All values ending with the given string.""" name_ends_with: String """All values not ending with the given string.""" name_not_ends_with: String inviteToken: String """All values that are not equal to given value.""" inviteToken_not: String """All values that are contained in given list.""" inviteToken_in: [String!] """All values that are not contained in given list.""" inviteToken_not_in: [String!] """All values less than the given value.""" inviteToken_lt: String """All values less than or equal the given value.""" inviteToken_lte: String """All values greater than the given value.""" inviteToken_gt: String """All values greater than or equal the given value.""" inviteToken_gte: String """All values containing the given string.""" inviteToken_contains: String """All values not containing the given string.""" inviteToken_not_contains: String """All values starting with the given string.""" inviteToken_starts_with: String """All values not starting with the given string.""" inviteToken_not_starts_with: String """All values ending with the given string.""" inviteToken_ends_with: String """All values not ending with the given string.""" inviteToken_not_ends_with: String inviteAccepted: Boolean """All values that are not equal to given value.""" inviteAccepted_not: Boolean emailConfirmed: Boolean """All values that are not equal to given value.""" emailConfirmed_not: Boolean emailConfirmToken: String """All values that are not equal to given value.""" emailConfirmToken_not: String """All values that are contained in given list.""" emailConfirmToken_in: [String!] """All values that are not contained in given list.""" emailConfirmToken_not_in: [String!] """All values less than the given value.""" emailConfirmToken_lt: String """All values less than or equal the given value.""" emailConfirmToken_lte: String """All values greater than the given value.""" emailConfirmToken_gt: String """All values greater than or equal the given value.""" emailConfirmToken_gte: String """All values containing the given string.""" emailConfirmToken_contains: String """All values not containing the given string.""" emailConfirmToken_not_contains: String """All values starting with the given string.""" emailConfirmToken_starts_with: String """All values not starting with the given string.""" emailConfirmToken_not_starts_with: String """All values ending with the given string.""" emailConfirmToken_ends_with: String """All values not ending with the given string.""" emailConfirmToken_not_ends_with: String resetToken: String """All values that are not equal to given value.""" resetToken_not: String """All values that are contained in given list.""" resetToken_in: [String!] """All values that are not contained in given list.""" resetToken_not_in: [String!] """All values less than the given value.""" resetToken_lt: String """All values less than or equal the given value.""" resetToken_lte: String """All values greater than the given value.""" resetToken_gt: String """All values greater than or equal the given value.""" resetToken_gte: String """All values containing the given string.""" resetToken_contains: String """All values not containing the given string.""" resetToken_not_contains: String """All values starting with the given string.""" resetToken_starts_with: String """All values not starting with the given string.""" resetToken_not_starts_with: String """All values ending with the given string.""" resetToken_ends_with: String """All values not ending with the given string.""" resetToken_not_ends_with: String resetExpires: DateTime """All values that are not equal to given value.""" resetExpires_not: DateTime """All values that are contained in given list.""" resetExpires_in: [DateTime!] """All values that are not contained in given list.""" resetExpires_not_in: [DateTime!] """All values less than the given value.""" resetExpires_lt: DateTime """All values less than or equal the given value.""" resetExpires_lte: DateTime """All values greater than the given value.""" resetExpires_gt: DateTime """All values greater than or equal the given value.""" resetExpires_gte: DateTime deletedAt: DateTime """All values that are not equal to given value.""" deletedAt_not: DateTime """All values that are contained in given list.""" deletedAt_in: [DateTime!] """All values that are not contained in given list.""" deletedAt_not_in: [DateTime!] """All values less than the given value.""" deletedAt_lt: DateTime """All values less than or equal the given value.""" deletedAt_lte: DateTime """All values greater than the given value.""" deletedAt_gt: DateTime """All values greater than or equal the given value.""" deletedAt_gte: DateTime lastLogin: DateTime """All values that are not equal to given value.""" lastLogin_not: DateTime """All values that are contained in given list.""" lastLogin_in: [DateTime!] """All values that are not contained in given list.""" lastLogin_not_in: [DateTime!] """All values less than the given value.""" lastLogin_lt: DateTime """All values less than or equal the given value.""" lastLogin_lte: DateTime """All values greater than the given value.""" lastLogin_gt: DateTime """All values greater than or equal the given value.""" lastLogin_gte: DateTime joinedAt: DateTime """All values that are not equal to given value.""" joinedAt_not: DateTime """All values that are contained in given list.""" joinedAt_in: [DateTime!] """All values that are not contained in given list.""" joinedAt_not_in: [DateTime!] """All values less than the given value.""" joinedAt_lt: DateTime """All values less than or equal the given value.""" joinedAt_lte: DateTime """All values greater than the given value.""" joinedAt_gt: DateTime """All values greater than or equal the given value.""" joinedAt_gte: DateTime isSuper: Boolean """All values that are not equal to given value.""" isSuper_not: Boolean } input UserWhereUniqueInput { id: ID email: String } `; export const Prisma = makePrismaBindingClass<BindingConstructor<Prisma>>({ typeDefs }); /** * Types */ export type UserOrderByInput = | 'id_ASC' | 'id_DESC' | 'email_ASC' | 'email_DESC' | 'password_ASC' | 'password_DESC' | 'name_ASC' | 'name_DESC' | 'inviteToken_ASC' | 'inviteToken_DESC' | 'inviteAccepted_ASC' | 'inviteAccepted_DESC' | 'emailConfirmed_ASC' | 'emailConfirmed_DESC' | 'emailConfirmToken_ASC' | 'emailConfirmToken_DESC' | 'resetToken_ASC' | 'resetToken_DESC' | 'resetExpires_ASC' | 'resetExpires_DESC' | 'deletedAt_ASC' | 'deletedAt_DESC' | 'lastLogin_ASC' | 'lastLogin_DESC' | 'joinedAt_ASC' | 'joinedAt_DESC' | 'isSuper_ASC' | 'isSuper_DESC' | 'updatedAt_ASC' | 'updatedAt_DESC' | 'createdAt_ASC' | 'createdAt_DESC'; export type MutationType = 'CREATED' | 'UPDATED' | 'DELETED'; export interface UserWhereUniqueInput { id?: ID_Input; email?: String; } export interface UserCreateInput { email: String; password: String; name: String; inviteToken?: String; inviteAccepted?: Boolean; emailConfirmed?: Boolean; emailConfirmToken?: String; resetToken?: String; resetExpires?: DateTime; deletedAt?: DateTime; lastLogin?: DateTime; joinedAt: DateTime; isSuper?: Boolean; } export interface UserUpdateInput { email?: String; password?: String; name?: String; inviteToken?: String; inviteAccepted?: Boolean; emailConfirmed?: Boolean; emailConfirmToken?: String; resetToken?: String; resetExpires?: DateTime; deletedAt?: DateTime; lastLogin?: DateTime; joinedAt?: DateTime; isSuper?: Boolean; } export interface UserSubscriptionWhereInput { AND?: UserSubscriptionWhereInput[] | UserSubscriptionWhereInput; OR?: UserSubscriptionWhereInput[] | UserSubscriptionWhereInput; NOT?: UserSubscriptionWhereInput[] | UserSubscriptionWhereInput; mutation_in?: MutationType[] | MutationType; updatedFields_contains?: String; updatedFields_contains_every?: String[] | String; updatedFields_contains_some?: String[] | String; node?: UserWhereInput; } export interface UserWhereInput { AND?: UserWhereInput[] | UserWhereInput; OR?: UserWhereInput[] | UserWhereInput; NOT?: UserWhereInput[] | UserWhereInput; id?: ID_Input; id_not?: ID_Input; id_in?: ID_Input[] | ID_Input; id_not_in?: ID_Input[] | ID_Input; id_lt?: ID_Input; id_lte?: ID_Input; id_gt?: ID_Input; id_gte?: ID_Input; id_contains?: ID_Input; id_not_contains?: ID_Input; id_starts_with?: ID_Input; id_not_starts_with?: ID_Input; id_ends_with?: ID_Input; id_not_ends_with?: ID_Input; email?: String; email_not?: String; email_in?: String[] | String; email_not_in?: String[] | String; email_lt?: String; email_lte?: String; email_gt?: String; email_gte?: String; email_contains?: String; email_not_contains?: String; email_starts_with?: String; email_not_starts_with?: String; email_ends_with?: String; email_not_ends_with?: String; password?: String; password_not?: String; password_in?: String[] | String; password_not_in?: String[] | String; password_lt?: String; password_lte?: String; password_gt?: String; password_gte?: String; password_contains?: String; password_not_contains?: String; password_starts_with?: String; password_not_starts_with?: String; password_ends_with?: String; password_not_ends_with?: String; name?: String; name_not?: String; name_in?: String[] | String; name_not_in?: String[] | String; name_lt?: String; name_lte?: String; name_gt?: String; name_gte?: String; name_contains?: String; name_not_contains?: String; name_starts_with?: String; name_not_starts_with?: String; name_ends_with?: String; name_not_ends_with?: String; inviteToken?: String; inviteToken_not?: String; inviteToken_in?: String[] | String; inviteToken_not_in?: String[] | String; inviteToken_lt?: String; inviteToken_lte?: String; inviteToken_gt?: String; inviteToken_gte?: String; inviteToken_contains?: String; inviteToken_not_contains?: String; inviteToken_starts_with?: String; inviteToken_not_starts_with?: String; inviteToken_ends_with?: String; inviteToken_not_ends_with?: String; inviteAccepted?: Boolean; inviteAccepted_not?: Boolean; emailConfirmed?: Boolean; emailConfirmed_not?: Boolean; emailConfirmToken?: String; emailConfirmToken_not?: String; emailConfirmToken_in?: String[] | String; emailConfirmToken_not_in?: String[] | String; emailConfirmToken_lt?: String; emailConfirmToken_lte?: String; emailConfirmToken_gt?: String; emailConfirmToken_gte?: String; emailConfirmToken_contains?: String; emailConfirmToken_not_contains?: String; emailConfirmToken_starts_with?: String; emailConfirmToken_not_starts_with?: String; emailConfirmToken_ends_with?: String; emailConfirmToken_not_ends_with?: String; resetToken?: String; resetToken_not?: String; resetToken_in?: String[] | String; resetToken_not_in?: String[] | String; resetToken_lt?: String; resetToken_lte?: String; resetToken_gt?: String; resetToken_gte?: String; resetToken_contains?: String; resetToken_not_contains?: String; resetToken_starts_with?: String; resetToken_not_starts_with?: String; resetToken_ends_with?: String; resetToken_not_ends_with?: String; resetExpires?: DateTime; resetExpires_not?: DateTime; resetExpires_in?: DateTime[] | DateTime; resetExpires_not_in?: DateTime[] | DateTime; resetExpires_lt?: DateTime; resetExpires_lte?: DateTime; resetExpires_gt?: DateTime; resetExpires_gte?: DateTime; deletedAt?: DateTime; deletedAt_not?: DateTime; deletedAt_in?: DateTime[] | DateTime; deletedAt_not_in?: DateTime[] | DateTime; deletedAt_lt?: DateTime; deletedAt_lte?: DateTime; deletedAt_gt?: DateTime; deletedAt_gte?: DateTime; lastLogin?: DateTime; lastLogin_not?: DateTime; lastLogin_in?: DateTime[] | DateTime; lastLogin_not_in?: DateTime[] | DateTime; lastLogin_lt?: DateTime; lastLogin_lte?: DateTime; lastLogin_gt?: DateTime; lastLogin_gte?: DateTime; joinedAt?: DateTime; joinedAt_not?: DateTime; joinedAt_in?: DateTime[] | DateTime; joinedAt_not_in?: DateTime[] | DateTime; joinedAt_lt?: DateTime; joinedAt_lte?: DateTime; joinedAt_gt?: DateTime; joinedAt_gte?: DateTime; isSuper?: Boolean; isSuper_not?: Boolean; } /* * An object with an ID */ export interface Node { id: ID_Output; } /* * Information about pagination in a connection. */ export interface PageInfo { hasNextPage: Boolean; hasPreviousPage: Boolean; startCursor?: String; endCursor?: String; } export interface UserPreviousValues { id: ID_Output; email: String; password: String; name: String; inviteToken?: String; inviteAccepted: Boolean; emailConfirmed: Boolean; emailConfirmToken?: String; resetToken?: String; resetExpires?: DateTime; deletedAt?: DateTime; lastLogin?: DateTime; joinedAt: DateTime; isSuper: Boolean; } export interface User extends Node { id: ID_Output; email: String; password: String; name: String; inviteToken?: String; inviteAccepted: Boolean; emailConfirmed: Boolean; emailConfirmToken?: String; resetToken?: String; resetExpires?: DateTime; deletedAt?: DateTime; lastLogin?: DateTime; joinedAt: DateTime; isSuper: Boolean; } /* * An edge in a connection. */ export interface UserEdge { node: User; cursor: String; } /* * A connection to a list of items. */ export interface UserConnection { pageInfo: PageInfo; edges: UserEdge[]; aggregate: AggregateUser; } export interface UserSubscriptionPayload { mutation: MutationType; node?: User; updatedFields?: String[]; previousValues?: UserPreviousValues; } export interface AggregateUser { count: Int; } export interface BatchPayload { count: Long; } export type DateTime = Date | string; /* The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as `"4"`) or integer (such as `4`) input value will be accepted as an ID. */ export type ID_Input = string | number; export type ID_Output = string; /* The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1. */ export type Int = number; /* The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text. */ export type String = string; /* The `Boolean` scalar type represents `true` or `false`. */ export type Boolean = boolean; /* The `Long` scalar type represents non-fractional signed whole numeric values. Long can represent values between -(2^63) and 2^63 - 1. */ export type Long = string;
the_stack
import { Channel, Emoji, GuildMember, integer, Internal, PresenceUpdateEvent, Role, snowflake, StageInstance, Sticker, timestamp, User, VoiceState } from '.' /** https://discord.com/developers/docs/resources/guild#guild-object-guild-structure */ export interface Guild { /** guild id */ id: snowflake /** guild name (2-100 characters, excluding trailing and leading whitespace) */ name: string /** icon hash */ icon?: string /** icon hash, returned when in the template object */ icon_hash?: string /** splash hash */ splash?: string /** discovery splash hash; only present for guilds with the "DISCOVERABLE" feature */ discovery_splash?: string /** true if the user is the owner of the guild */ owner?: boolean /** id of owner */ owner_id: snowflake /** total permissions for the user in the guild (excludes overwrites) */ permissions?: string /** voice region id for the guild (deprecated) */ region?: string /** id of afk channel */ afk_channel_id?: snowflake /** afk timeout in seconds */ afk_timeout: integer /** true if the server widget is enabled */ widget_enabled?: boolean /** the channel id that the widget will generate an invite to, or null if set to no invite */ widget_channel_id?: snowflake /** verification level required for the guild */ verification_level: integer /** default message notifications level */ default_message_notifications: integer /** explicit content filter level */ explicit_content_filter: integer /** roles in the guild */ roles: Role[] /** custom guild emojis */ emojis: Emoji[] /** enabled guild features */ features: GuildFeature[] /** required MFA level for the guild */ mfa_level: integer /** application id of the guild creator if it is bot-created */ application_id?: snowflake /** the id of the channel where guild notices such as welcome messages and boost events are posted */ system_channel_id?: snowflake /** system channel flags */ system_channel_flags: integer /** the id of the channel where Community guilds can display rules and/or guidelines */ rules_channel_id?: snowflake /** when this guild was joined at */ joined_at?: timestamp /** true if this is considered a large guild */ large?: boolean /** true if this guild is unavailable due to an outage */ unavailable?: boolean /** total number of members in this guild */ member_count?: integer /** states of members currently in voice channels; lacks the guild_id key */ voice_states?: Partial<VoiceState>[] /** users in the guild */ members?: GuildMember[] /** channels in the guild */ channels?: Channel[] /** all active threads in the guild that current user has permission to view */ threads?: Channel[] /** presences of the members in the guild, will only include non-offline members if the size is greater than large threshold */ presences?: Partial<PresenceUpdateEvent>[] /** the maximum number of presences for the guild (null is always returned, apart from the largest of guilds) */ max_presences?: integer /** the maximum number of members for the guild */ max_members?: integer /** the vanity url code for the guild */ vanity_url_code?: string /** the description of a Community guild */ description?: string /** banner hash */ banner?: string /** premium tier (Server Boost level) */ premium_tier: integer /** the number of boosts this guild currently has */ premium_subscription_count?: integer /** the preferred locale of a Community guild; used in server discovery and notices from Discord; defaults to "en-US" */ preferred_locale: string /** the id of the channel where admins and moderators of Community guilds receive notices from Discord */ public_updates_channel_id?: snowflake /** the maximum amount of users in a video channel */ max_video_channel_users?: integer /** approximate number of members in this guild, returned from the GET /guilds/<id> endpoint when with_counts is true */ approximate_member_count?: integer /** approximate number of non-offline members in this guild, returned from the GET /guilds/<id> endpoint when with_counts is true */ approximate_presence_count?: integer /** the welcome screen of a Community guild, shown to new members, returned in an Invite's guild object */ welcome_screen?: WelcomeScreen /** guild NSFW level */ nsfw_level: integer /** Stage instances in the guild */ stage_instances?: StageInstance[] /** custom guild stickers */ stickers?: Sticker[] } /** https://discord.com/developers/docs/resources/guild#guild-object-system-channel-flags */ export enum SystemChannelFlag { /** Suppress member join notifications */ SUPPRESS_JOIN_NOTIFICATIONS = 1 << 0, /** Suppress server boost notifications */ SUPPRESS_PREMIUM_SUBSCRIPTIONS = 1 << 1, /** Suppress server setup tips */ SUPPRESS_GUILD_REMINDER_NOTIFICATIONS = 1 << 2, } /** https://discord.com/developers/docs/resources/guild#guild-object-guild-features */ export enum GuildFeature { /** guild has access to set an animated guild icon */ ANIMATED_ICON = 'ANIMATED_ICON', /** guild has access to set a guild banner image */ BANNER = 'BANNER', /** guild has access to use commerce features (i.e. create store channels) */ COMMERCE = 'COMMERCE', /** guild can enable welcome screen, Membership Screening, stage channels and discovery, and receives community updates */ COMMUNITY = 'COMMUNITY', /** guild is able to be discovered in the directory */ DISCOVERABLE = 'DISCOVERABLE', /** guild is able to be featured in the directory */ FEATURABLE = 'FEATURABLE', /** guild has access to set an invite splash background */ INVITE_SPLASH = 'INVITE_SPLASH', /** guild has enabled Membership Screening */ MEMBER_VERIFICATION_GATE_ENABLED = 'MEMBER_VERIFICATION_GATE_ENABLED', /** guild has enabled monetization */ MONETIZATION_ENABLED = 'MONETIZATION_ENABLED', /** guild has increased custom sticker slots */ MORE_STICKERS = 'MORE_STICKERS', /** guild has access to create news channels */ NEWS = 'NEWS', /** guild is partnered */ PARTNERED = 'PARTNERED', /** guild can be previewed before joining via Membership Screening or the directory */ PREVIEW_ENABLED = 'PREVIEW_ENABLED', /** guild has access to create private threads */ PRIVATE_THREADS = 'PRIVATE_THREADS', /** guild is able to set role icons */ ROLE_ICONS = 'ROLE_ICONS', /** guild has access to the seven day archive time for threads */ SEVEN_DAY_THREAD_ARCHIVE = 'SEVEN_DAY_THREAD_ARCHIVE', /** guild has access to the three day archive time for threads */ THREE_DAY_THREAD_ARCHIVE = 'THREE_DAY_THREAD_ARCHIVE', /** guild has enabled ticketed events */ TICKETED_EVENTS_ENABLED = 'TICKETED_EVENTS_ENABLED', /** guild has access to set a vanity URL */ VANITY_URL = 'VANITY_URL', /** guild is verified */ VERIFIED = 'VERIFIED', /** guild has access to set 384kbps bitrate in voice (previously VIP voice servers) */ VIP_REGIONS = 'VIP_REGIONS', /** guild has enabled the welcome screen */ WELCOME_SCREEN_ENABLED = 'WELCOME_SCREEN_ENABLED', } /** https://discord.com/developers/docs/resources/guild#guild-preview-object-guild-preview-structure */ export interface GuildPreview { /** guild id */ id: snowflake /** guild name (2-100 characters) */ name: string /** icon hash */ icon?: string /** splash hash */ splash?: string /** discovery splash hash */ discovery_splash?: string /** custom guild emojis */ emojis: Emoji[] /** enabled guild features */ features: GuildFeature[] /** approximate number of members in this guild */ approximate_member_count: integer /** approximate number of online members in this guild */ approximate_presence_count: integer /** the description for the guild, if the guild is discoverable */ description?: string } /** https://discord.com/developers/docs/resources/guild#guild-widget-object-guild-widget-structure */ export interface GuildWidget { /** whether the widget is enabled */ enabled: boolean /** the widget channel id */ channel_id?: snowflake } /** https://discord.com/developers/docs/resources/guild#ban-object-ban-structure */ export interface Ban { /** the reason for the ban */ reason?: string /** the banned user */ user: User } /** https://discord.com/developers/docs/resources/guild#welcome-screen-object-welcome-screen-structure */ export interface WelcomeScreen { /** the server description shown in the welcome screen */ description?: string /** the channels shown in the welcome screen, up to 5 */ welcome_channels: WelcomeScreenChannel[] } /** https://discord.com/developers/docs/resources/guild#welcome-screen-object-welcome-screen-channel-structure */ export interface WelcomeScreenChannel { /** the channel's id */ channel_id: snowflake /** the description shown for the channel */ description: string /** the emoji id, if the emoji is custom */ emoji_id?: snowflake /** the emoji name if custom, the unicode character if standard, or null if no emoji is set */ emoji_name?: string } export interface GuildCreateEvent extends Guild {} export interface GuildUpdateEvent extends Guild {} export interface GuildDeleteEvent extends Guild {} /** https://discord.com/developers/docs/topics/gateway#guild-ban-add-guild-ban-add-event-fields */ export interface GuildBanAddEvent { /** id of the guild */ guild_id: snowflake /** the banned user */ user: User } /** https://discord.com/developers/docs/topics/gateway#guild-ban-remove-guild-ban-remove-event-fields */ export interface GuildBanRemoveEvent { /** id of the guild */ guild_id: snowflake /** the unbanned user */ user: User } declare module './gateway' { interface GatewayEvents { /** lazy-load for unavailable guild, guild became available, or user joined a new guild */ GUILD_CREATE: GuildCreateEvent /** guild was updated */ GUILD_UPDATE: GuildUpdateEvent /** guild became unavailable, or user left/was removed from a guild */ GUILD_DELETE: GuildDeleteEvent /** user was banned from a guild */ GUILD_BAN_ADD: GuildBanAddEvent /** user was unbanned from a guild */ GUILD_BAN_REMOVE: GuildBanRemoveEvent } } declare module './internal' { interface Internal { /** https://discord.com/developers/docs/resources/user#get-current-user-guilds */ getCurrentUserGuilds(): Promise<Guild[]> /** https://discord.com/developers/docs/resources/user#leave-guild */ leaveGuild(guild_id: snowflake): Promise<void> } } Internal.define({ '/users/@me/guilds': { GET: 'getCurrentUserGuilds', }, '/users/@me/guilds/{guild.id}': { DELETE: 'leaveGuild', }, }) declare module './internal' { interface Internal { /** https://discord.com/developers/docs/resources/guild#get-guild */ getGuild(guild_id: snowflake): Promise<Guild> /** https://discord.com/developers/docs/resources/guild#get-guild-preview */ getGuildPreview(guild_id: snowflake): Promise<GuildPreview> /** https://discord.com/developers/docs/resources/guild#modify-guild */ modifyGuild(guild_id: snowflake, options: Partial<Guild>): Promise<Guild> } } Internal.define({ '/guilds': { POST: 'createGuild', }, '/guilds/{guild.id}': { GET: 'getGuild', PATCH: 'modifyGuild', DELETE: 'deleteGuild', }, '/guilds/{guild.id}/preview': { GET: 'getGuildPreview', }, '/guilds/{guild.id}/threads/active': { GET: 'listActiveThreads', }, '/guilds/{guild.id}/bans': { GET: 'getGuildBans', }, '/guilds/{guild.id}/bans/{user.id}': { GET: 'getGuildBan', PUT: 'createGuildBan', DELETE: 'removeGuildBan', }, '/guilds/{guild.id}/roles': { GET: 'getGuildRoles', POST: 'createGuildRole', PATCH: 'modifyGuildRolePositions', }, '/guilds/{guild.id}/roles/{role.id}': { PATCH: 'modifyGuildRole', DELETE: 'deleteGuildRole', }, '/guilds/{guild.id}/prune': { GET: 'getGuildPruneCount', POST: 'beginGuildPrune', }, '/guilds/{guild.id}/regions': { GET: 'getGuildVoiceRegions', }, '/guilds/{guild.id}/invites': { GET: 'getGuildInvites', }, '/guilds/{guild.id}/integrations': { GET: 'getGuildIntegrations', }, '/guilds/{guild.id}/integrations/{integration.id}': { DELETE: 'deleteGuildIntegration', }, '/guilds/{guild.id}/widget': { GET: 'getGuildWidgetSettings', PATCH: 'modifyGuildWidget', }, '/guilds/{guild.id}/widget.json': { GET: 'getGuildWidget', }, '/guilds/{guild.id}/vanity-url': { GET: 'getGuildVanityURL', }, '/guilds/{guild.id}/widget.png': { GET: 'getGuildWidgetImage', }, '/guilds/{guild.id}/welcome-screen': { GET: 'getGuildWelcomeScreen', PATCH: 'modifyGuildWelcomeScreen', }, '/guilds/{guild.id}/voice-states/@me': { PATCH: 'modifyCurrentUserVoiceState', }, '/guilds/{guild.id}/voice-states/{user.id}': { PATCH: 'modifyUserVoiceState', }, })
the_stack
import { ContainerIterator, SequentialContainerType } from "../Base/Base"; export interface DequeType<T> extends SequentialContainerType<T> { /** * Push the element to the front. */ pushFront: (element: T) => void; /** * Remove the first element. */ popFront: () => void; /** * Remove useless space. */ shrinkToFit: () => void; /** * Remove all elements after the specified position (excluding the specified position). */ cut: (pos: number) => void; } const DequeIterator = function <T>( this: ContainerIterator<T>, index: number, size: () => number, getElementByPos: (pos: number) => T, setElementByPos: (pos: number, element: T) => void, iteratorType: 'normal' | 'reverse' = 'normal', ) { Object.defineProperties(this, { iteratorType: { value: iteratorType }, node: { value: index, }, pointer: { get: () => { if (index < 0 || index >= size()) { throw new Error("Deque iterator access denied!"); } return getElementByPos(index); }, set: (newValue: T) => { setElementByPos(index, newValue); }, enumerable: true } }); this.equals = function (obj: ContainerIterator<T>) { if (obj.constructor.name !== this.constructor.name) { throw new Error(`obj's constructor is not ${this.constructor.name}!`); } if (this.iteratorType !== obj.iteratorType) { throw new Error("iterator type error!"); } // @ts-ignore return this.node === obj.node; }; this.pre = function () { if (this.iteratorType === 'reverse') { if (index === size() - 1) throw new Error("Deque iterator access denied!"); return new DequeIterator(index + 1, size, getElementByPos, setElementByPos, this.iteratorType); } if (index === 0) throw new Error("Deque iterator access denied!"); return new DequeIterator(index - 1, size, getElementByPos, setElementByPos); }; this.next = function () { if (this.iteratorType === 'reverse') { if (index === -1) throw new Error("Deque iterator access denied!"); return new DequeIterator(index - 1, size, getElementByPos, setElementByPos, this.iteratorType); } if (index === size()) throw new Error("Iterator access denied!"); return new DequeIterator(index + 1, size, getElementByPos, setElementByPos); }; } as unknown as { new <T>( pos: number, size: () => number, getElementByPos: (pos: number) => T, setElementByPos: (pos: number, element: T) => void, type?: 'normal' | 'reverse', ): ContainerIterator<T> }; Deque.sigma = 3; // growth factor Deque.bucketSize = (1 << 12); function Deque<T>(this: DequeType<T>, container: { forEach: (callback: (element: T) => void) => void, size?: () => number, length?: number } = []) { let map: (T[])[] = []; let first = 0; let curFirst = 0; let last = 0; let curLast = 0; let bucketNum = 0; let len = 0; this.size = function () { return len; }; this.empty = function () { return len === 0; }; this.clear = function () { first = last = curFirst = curLast = bucketNum = len = 0; reAllocate.call(this, Deque.bucketSize); len = 0; }; this.begin = function () { return new DequeIterator(0, this.size, this.getElementByPos, this.setElementByPos); }; this.end = function () { return new DequeIterator(len, this.size, this.getElementByPos, this.setElementByPos); }; this.rBegin = function () { return new DequeIterator(len - 1, this.size, this.getElementByPos, this.setElementByPos, 'reverse'); } this.rEnd = function () { return new DequeIterator(-1, this.size, this.getElementByPos, this.setElementByPos, 'reverse'); } this.front = function () { return map[first][curFirst]; }; this.back = function () { return map[last][curLast]; }; this.forEach = function (callback: (element: T, index: number) => void) { if (this.empty()) return; let index = 0; if (first === last) { for (let i = curFirst; i <= curLast; ++i) { callback(map[first][i], index++); } return; } for (let i = curFirst; i < Deque.bucketSize; ++i) { callback(map[first][i], index++); } for (let i = first + 1; i < last; ++i) { for (let j = 0; j < Deque.bucketSize; ++j) { callback(map[i][j], index++); } } for (let i = 0; i <= curLast; ++i) { callback(map[last][i], index++); } }; const getElementIndex = function (pos: number) { const curFirstIndex = first * Deque.bucketSize + curFirst; const curNodeIndex = curFirstIndex + pos; const curLastIndex = last * Deque.bucketSize + curLast; if (curNodeIndex < curFirstIndex || curNodeIndex > curLastIndex) throw new Error("pos should more than 0 and less than queue's size"); const curNodeBucketIndex = Math.floor(curNodeIndex / Deque.bucketSize); const curNodePointerIndex = curNodeIndex % Deque.bucketSize; return { curNodeBucketIndex, curNodePointerIndex }; }; this.getElementByPos = function (pos: number) { const { curNodeBucketIndex, curNodePointerIndex } = getElementIndex(pos); return map[curNodeBucketIndex][curNodePointerIndex]; }; this.eraseElementByPos = function (pos: number) { if (pos < 0 || pos > len) throw new Error("pos should more than 0 and less than queue's size"); if (pos === 0) this.popFront(); else if (pos === this.size()) this.popBack(); else { const arr = []; for (let i = pos + 1; i < len; ++i) { arr.push(this.getElementByPos(i)); } this.cut(pos); this.popBack(); arr.forEach(element => this.pushBack(element)); } }; this.eraseElementByValue = function (value: T) { if (this.empty()) return; const arr: T[] = []; this.forEach(element => { if (element !== value) { arr.push(element); } }); const _len = arr.length; for (let i = 0; i < _len; ++i) this.setElementByPos(i, arr[i]); this.cut(_len - 1); }; this.eraseElementByIterator = function (iter: ContainerIterator<T>) { const nextIter = iter.next(); // @ts-ignore this.eraseElementByPos(iter.node); iter = nextIter; return iter; }; const reAllocate = function (this: DequeType<T>, originalSize: number) { const newMap = []; const needSize = originalSize * Deque.sigma; const newBucketNum = Math.max(Math.ceil(needSize / Deque.bucketSize), 2); for (let i = 0; i < newBucketNum; ++i) { newMap.push(new Array(Deque.bucketSize)); } const needBucketNum = Math.ceil(originalSize / Deque.bucketSize); const newFirst = Math.floor(newBucketNum / 2) - Math.floor(needBucketNum / 2); let newLast = newFirst, newCurLast = 0; if (this.size()) { for (let i = 0; i < needBucketNum; ++i) { for (let j = 0; j < Deque.bucketSize; ++j) { newMap[newFirst + i][j] = this.front(); this.popFront(); if (this.empty()) { newLast = newFirst + i; newCurLast = j; break; } } if (this.empty()) break; } } map = newMap; first = newFirst; curFirst = 0; last = newLast; curLast = newCurLast; bucketNum = newBucketNum; len = originalSize; }; this.pushBack = function (element: T) { if (!this.empty()) { if (last === bucketNum - 1 && curLast === Deque.bucketSize - 1) { reAllocate.call(this, this.size()); } if (curLast < Deque.bucketSize - 1) { ++curLast; } else if (last < bucketNum - 1) { ++last; curLast = 0; } } ++len; map[last][curLast] = element; }; this.popBack = function () { if (this.empty()) return; if (this.size() !== 1) { if (curLast > 0) { --curLast; } else if (first < last) { --last; curLast = Deque.bucketSize - 1; } } if (len > 0) --len; }; this.setElementByPos = function (pos: number, element: T) { if (element === undefined || element === null) { this.eraseElementByPos(pos); return; } const { curNodeBucketIndex, curNodePointerIndex } = getElementIndex(pos); map[curNodeBucketIndex][curNodePointerIndex] = element; }; this.insert = function (pos: number, element: T, num = 1) { if (element === undefined || element === null) { throw new Error("you can't push undefined or null here"); } if (pos === 0) { while (num--) this.pushFront(element); } else if (pos === this.size()) { while (num--) this.pushBack(element); } else { const arr: T[] = []; for (let i = pos; i < len; ++i) { arr.push(this.getElementByPos(i)); } this.cut(pos - 1); for (let i = 0; i < num; ++i) this.pushBack(element); arr.forEach(element => this.pushBack(element)); } }; this.find = function (element: T) { function getIndex(curNodeBucketIndex: number, curNodePointerIndex: number) { if (curNodeBucketIndex === first) return curNodePointerIndex - curFirst; if (curNodeBucketIndex === last) return len - (curLast - curNodePointerIndex) - 1; return (Deque.bucketSize - first) + (curNodeBucketIndex - 2) * Deque.bucketSize + curNodePointerIndex; } let resIndex: number | undefined = undefined; if (first === last) { for (let i = curFirst; i <= curLast; ++i) { if (map[first][i] === element) resIndex = getIndex(first, i); } return this.end(); } for (let i = curFirst; i < Deque.bucketSize; ++i) { if (map[first][i] === element) resIndex = getIndex(first, i); } if (resIndex === undefined) { for (let i = first + 1; i < last; ++i) { for (let j = 0; j < Deque.bucketSize; ++j) { if (map[i][j] === element) resIndex = getIndex(first, i); } } } if (resIndex === undefined) { for (let i = 0; i <= curLast; ++i) { if (map[last][i] === element) resIndex = getIndex(first, i); } } if (resIndex === undefined) return this.end(); if (resIndex === 0) return this.begin(); return new DequeIterator(resIndex, this.size, this.getElementByPos, this.setElementByPos); }; this.reverse = function () { let l = 0, r = len - 1; while (l < r) { const tmp = this.getElementByPos(l); this.setElementByPos(l, this.getElementByPos(r)); this.setElementByPos(r, tmp); ++l; --r; } }; this.unique = function () { if (this.empty()) return; const arr: T[] = []; let pre = this.front(); this.forEach((element, index) => { if (index === 0 || element !== pre) { arr.push(element); pre = element; } }); for (let i = 0; i < len; ++i) { this.setElementByPos(i, arr[i]); } this.cut(arr.length - 1); }; this.sort = function (cmp?: (x: T, y: T) => number) { const arr: T[] = []; this.forEach(element => { arr.push(element); }); arr.sort(cmp); for (let i = 0; i < len; ++i) this.setElementByPos(i, arr[i]); }; this.pushFront = function (element: T) { if (element === undefined || element === null) { throw new Error("you can't push undefined or null here"); } if (!this.empty()) { if (first === 0 && curFirst === 0) { reAllocate.call(this, this.size()); } if (curFirst > 0) { --curFirst; } else if (first > 0) { --first; curFirst = Deque.bucketSize - 1; } } ++len; map[first][curFirst] = element; }; this.popFront = function () { if (this.empty()) return; if (this.size() !== 1) { if (curFirst < Deque.bucketSize - 1) { ++curFirst; } else if (first < last) { ++first; curFirst = 0; } } if (len > 0) --len; }; this.shrinkToFit = function () { const arr: T[] = []; this.forEach((element) => { arr.push(element); }); const _len = arr.length; map = []; const bucketNum = Math.ceil(_len / Deque.bucketSize); for (let i = 0; i < bucketNum; ++i) { map.push(new Array(Deque.bucketSize)); } this.clear(); arr.forEach(element => this.pushBack(element)); }; this.cut = function (pos: number) { if (pos < 0) { this.clear(); return; } const { curNodeBucketIndex, curNodePointerIndex } = getElementIndex(pos); last = curNodeBucketIndex; curLast = curNodePointerIndex; len = pos + 1; }; if (typeof Symbol.iterator === 'symbol') { this[Symbol.iterator] = function () { return (function* () { if (len === 0) return; if (first === last) { for (let i = curFirst; i <= curLast; ++i) { yield map[first][i]; } return; } for (let i = curFirst; i < Deque.bucketSize; ++i) { yield map[first][i]; } for (let i = first + 1; i < last; ++i) { for (let j = 0; j < Deque.bucketSize; ++j) { yield map[i][j]; } } for (let i = 0; i <= curLast; ++i) { yield map[last][i]; } })(); }; } (() => { let _len = Deque.bucketSize; if (container.size) { _len = container.size(); } else if (container.length) { _len = container.length; } const needSize = _len * Deque.sigma; bucketNum = Math.ceil(needSize / Deque.bucketSize); bucketNum = Math.max(bucketNum, 3); for (let i = 0; i < bucketNum; ++i) { map.push(new Array(Deque.bucketSize)); } const needBucketNum = Math.ceil(_len / Deque.bucketSize); first = Math.floor(bucketNum / 2) - Math.floor(needBucketNum / 2); last = first; container.forEach(element => this.pushBack(element)); })(); } export default (Deque as unknown as { new <T>(arr: T[]): DequeType<T>; });
the_stack
import { Client, Collection, GuildMember, Message, MessageEmbed, TextChannel, Guild, VoiceChannel, MessageReaction, User } from "discord.js"; import { connect } from "mongoose"; import * as pogger from "pogger"; import { IVoiceModel, VoiceModel } from "./voiceModel"; import { IChannelModel, ChannelModel } from "./channelModel"; import { CONFIG } from "./config"; import ms from "parse-ms"; import { scheduleJob } from "node-schedule"; import { stringify } from "querystring"; const channelJoined = new Collection<string, number>(); const client = new Client({ disableMentions: "everyone", fetchAllMembers: true, partials: [ "CHANNEL", "GUILD_MEMBER", "USER" ], presence: { activity: { type: "PLAYING", name: "Zade ❤️ Labirent" } }, ws: { intents: [ "GUILDS", "GUILD_MEMBERS", "GUILD_MESSAGES", "GUILD_VOICE_STATES", ] } }); client.on("ready", async () => { pogger.info("Leaderboards mesajları fetchleniyor"); const channel = await client.channels.fetch(CONFIG.LEADERBOARDS_CHANNEL) as TextChannel; if (!channel) throw "Leaderboards kanalı bulunamadı."; const textMessage = await channel.messages.fetch(CONFIG.LEADERBOARDS_MESSAGE_TEXT); if (!textMessage) throw "Yazı leaderboards mesajı bulunamadı."; const voiceMessage = await channel.messages.fetch(CONFIG.LEADERBOARDS_MESSAGE_VOICE); if (!voiceMessage) throw "Sesli leaderboards mesajı bulunamadı."; pogger.success("Tüm doğrulama işlemleri başarılı"); pogger.success(`Bot ${client.user?.tag} adı ile giriş yaptı.`); scheduleJob("*/30 * * * *", () => fetchLeaderBoards(channel, textMessage, voiceMessage)); }); client.on("message", async (message) => { if ( !message.guild || message.guild.id != CONFIG.GUILD_ID || !message.content || message.author.bot ) return; let channelModel = await ChannelModel.findOne({ channelID: message.channel.id, guildID: message.guild.id, userID: message.author.id }); if (!channelModel) channelModel = new ChannelModel({ channelID: message.channel.id, guildID: message.guild.id, userID: message.author.id }); channelModel.type = "text"; channelModel.data += 1; await channelModel.save(); let voiceModel = await VoiceModel.findOne({ userID: message.author.id, guildID: message.guild.id }); if (!voiceModel) { voiceModel = new VoiceModel({ userID: message.author.id, guildID: message.guild.id }); } const time = channelJoined.get(message.author.id); if (time) { const diffrence = Date.now() - time; voiceModel.voice += diffrence; channelJoined.set(message.author.id, Date.now()); } voiceModel.messages += 1; await checkReward(message.member as GuildMember, voiceModel); await voiceModel.save(); if (message.content === "!me") { const channelData = await ChannelModel.find({ userID: message.author.id, guildID: message.guild.id }); const voiceData = channelData .filter(data => data.type === "voice") .sort((a, c) => c.data - a.data) .slice(0, 30) .map((data, i) => { const channel = client.channels.cache.get(data.channelID) as VoiceChannel; const mention = channel.name ? channel.name : data.channelID; const formatted = ms(data.data); return `\`${i + 1}.\` ${mention}: \`${formatted.days} gün ${formatted.hours} saat ${formatted.minutes} dakika ${formatted.seconds} saniye\``; }) const textData = channelData .filter(data => data.type === "text") .sort((a, c) => c.data - a.data) .slice(0, 30) .map((data, i) => { const channel = client.channels.cache.get(data.channelID) as TextChannel; const mention = channel.name ? channel.name : data.channelID; return `\`${i + 1}.\` ${mention}: \`${data.data}\`\n`; }) const formatted = ms(voiceModel.voice); const embed = new MessageEmbed() .setColor("BLACK") .setAuthor(message.author.tag, message.author.avatarURL({ dynamic: true }) || undefined) .setDescription(` ${message.author.toString()} (${message?.member?.roles?.highest}) kişisinin sunucu verileri `) .addField(`❯ Kanal Sıralaması (Toplam: ${formatted.days} gün ${formatted.hours} saat ${formatted.minutes} dakika ${formatted.seconds} saniye)`, `${voiceData.length ? voiceData.join() : "Ses Veriniz Bulunmamaktadır."}`) .addField(`❯ Kanal Sıralaması (Toplam: ${voiceModel.messages})`, textData.join("")) .setTimestamp(Date.now()) .setFooter("Kullanıcı İstatistikleri") .setThumbnail(message.author.displayAvatarURL({ dynamic: true })) message.channel.send(/*`**${message.member?.nickname || message.author.username}** kullanıcısının istatistikleri`,*/ embed); } if (message.content === "!toptext") { const [text] = await generateLeaderboardsEmbed(message.guild); message.channel.send(text); } if (message.content === "!topvoice") { const [, voice] = await generateLeaderboardsEmbed(message.guild); message.channel.send(voice); } if (message.content === "!top") { const top = await generateTopEmbed(message.guild); message.channel.send(top); } if (message.content === "!topchannel") { await generateChannelEmbed(message.member as GuildMember, message.channel as TextChannel) } }); client.on("voiceStateUpdate", async (oldState, newState) => { if ( !oldState.member || !newState.member || oldState.member.guild.id != CONFIG.GUILD_ID || oldState.member.user.bot || newState.member.user.bot ) return; let voiceModel = await VoiceModel.findOne({ userID: newState.member.user.id, guildID: newState.guild.id }); let updated = false; if (!voiceModel) { voiceModel = new VoiceModel({ userID: newState.member.user.id, guildID: newState.guild.id }); updated = true; } /* Kanala katılırsa */ if (!oldState.channelID && newState.channelID) { if (!newState.selfDeaf && !newState.selfMute) { channelJoined.set(newState.member.id, Date.now()); } } /* kanaldan ayrılırsa */ if (oldState.channel && !newState.channelID) { const time = channelJoined.get(oldState.member.id); if (time) { const diffrence = Date.now() - time; voiceModel.voice += diffrence; channelJoined.delete(oldState.member.id); updated = true; await checkReward(oldState.member, voiceModel); let channelModel = await ChannelModel.findOne({ channelID: oldState.channel.id, guildID: oldState.guild.id, userID: oldState.member.id }); if (!channelModel) channelModel = new ChannelModel({ channelID: oldState.channel.id, guildID: oldState.guild.id, userID: oldState.member.id }); channelModel.type = "voice"; channelModel.data += diffrence; await channelModel.save(); } } /* kanal değişirse */ if (oldState.channel && newState.channelID) { const time = channelJoined.get(oldState.member.id); if (time) { const diffrence = Date.now() - time; voiceModel.voice += diffrence; channelJoined.set(newState.member.id, Date.now()); updated = true; await checkReward(oldState.member, voiceModel); let channelModel = await ChannelModel.findOne({ channelID: oldState.channel.id, guildID: oldState.guild.id, userID: oldState.member.id }); if (!channelModel) channelModel = new ChannelModel({ channelID: oldState.channel.id, guildID: oldState.guild.id, userID: oldState.member.id }); channelModel.type = "voice"; channelModel.data += diffrence; await channelModel.save(); } } /* Kulaklık - mic kaparsa */ if (newState.channelID && (newState.selfDeaf || newState.selfMute)) { const time = channelJoined.get(newState.member.id); if (time) { const diffrence = Date.now() - time; voiceModel.voice += diffrence; channelJoined.delete(oldState.member.id); updated = true; await checkReward(oldState.member, voiceModel); let channelModel = await ChannelModel.findOne({ channelID: (newState.channel as VoiceChannel).id, guildID: newState.guild.id, userID: newState.member.id }); if (!channelModel) channelModel = new ChannelModel({ channelID: (newState.channel as VoiceChannel).id, guildID: newState.guild.id, userID: newState.member.id }); channelModel.type = "voice"; channelModel.data += diffrence; await channelModel.save(); } } /* Kulaklık - mic açarsa */ if ( (oldState.selfDeaf || oldState.selfMute) && !newState.selfDeaf && !newState.selfMute ) { channelJoined.set(newState.member.id, Date.now()); } if (updated) await voiceModel.save(); }); async function checkReward(member: GuildMember, voiceModel: IVoiceModel): Promise<void> { const voiceRewards = CONFIG.VOICE_REWARDS.filter(reward => member.guild.roles.cache.has(reward.role) && reward.rank <= voiceModel.voice && !member.roles.cache.has(reward.role) ) .map(reward => reward.role) const textRewards = CONFIG.TEXT_REWARDS.filter(reward => member.guild.roles.cache.has(reward.role) && reward.rank <= voiceModel.messages && !member.roles.cache.has(reward.role) ) .map(reward => reward.role) const channel = member.guild.channels.cache.get(CONFIG.REWARD_CHANNEL) as TextChannel; if (voiceRewards.length > 0) { await member.roles.add(voiceRewards); // if (channel) await channel.send(`Tebrikler ${member.toString()}! Sesli kanallarda vakit geçirerek **${voiceRewards.map(id => member.guild.roles.cache.get(id)?.name).join(", ")}** rol(lerini) kazandın!`); if (channel) await channel.send(`🎉 ${member.toString()} tebrikler! Ses istatistiklerin bir sonraki seviyeye atlaman için yeterli oldu. **"${voiceRewards.map(id => member.guild.roles.cache.get(id)?.name).join(", ")}"** rolüne terfi edildin!`); } if (textRewards.length > 0) { await member.roles.add(textRewards); if (channel) await channel.send(`🎉 ${member.toString()} tebrikler! Mesaj istatistiklerin bir sonraki seviyeye atlaman için yeterli oldu. **"${textRewards.map(id => member.guild.roles.cache.get(id)?.name).join(", ")}"** rolüne terfi edildin!`); // if (channel) await channel.send(`Tebrikler ${member.toString()}! Sohbet kanallarında vakit geçirerek **${textRewards.map(id => member.guild.roles.cache.get(id)?.name).join(", ")}** rol(lerini) kazandın!`); } } async function fetchLeaderBoards(channel: TextChannel, textMessage: Message, voiceMessage: Message): Promise<void> { const [text, voice] = await generateLeaderboardsEmbed(channel.guild); await textMessage.edit(text); await voiceMessage.edit(voice); } async function generateLeaderboardsEmbed(guild: Guild): Promise<[MessageEmbed, MessageEmbed]> { const voiceList = await VoiceModel.find({ guildID: guild.id }).sort("-voice").limit(20); const textList = await VoiceModel.find({ guildID: guild.id }).sort("-messages").limit(20); const voice = new MessageEmbed() .setAuthor("Labirent Ses sıralaması | Tüm zamanlar") .setFooter("Son güncelleme") .setColor("BLACK") .setTimestamp(Date.now()); const text = new MessageEmbed() .setAuthor("Labirent Mesaj sıralaması | Tüm zamanlar") .setFooter("Son güncelleme") .setColor("BLACK") .setTimestamp(Date.now()); let voiceDescription = ""; let textDescription = ""; for (let i = 0; i < voiceList.length; i++) { const data = voiceList[i]; const user = client.users.cache.get(data.userID); const mention = user ? user.toString() : data.userID; const formatted = ms(data.voice); voiceDescription += `**${i + 1}.** ${mention}: ${formatted.days} gün ${formatted.hours} saat ${formatted.minutes} dakika ${formatted.seconds} saniye\n`; } for (let i = 0; i < textList.length; i++) { const data = textList[i]; const user = client.users.cache.get(data.userID); const mention = user ? user.toString() : data.userID; textDescription += `**${i + 1}.** ${mention}: ${data.messages} mesaj\n`; } voice.setDescription(voiceDescription); text.setDescription(textDescription); return [text, voice]; } async function generateTopEmbed(guild: Guild): Promise<MessageEmbed> { const voiceList = await VoiceModel.find({ guildID: guild.id }).sort("-voice").limit(10); const textList = await VoiceModel.find({ guildID: guild.id }).sort("-messages").limit(10); const top = new MessageEmbed() .setAuthor("Labirent Top sıralaması | Tüm zamanlar") .setFooter("Son güncelleme") .setColor("BLACK") .setTimestamp(Date.now()); let voiceDescription = ""; let textDescription = ""; for (let i = 0; i < voiceList.length; i++) { const data = voiceList[i]; const user = client.users.cache.get(data.userID); const mention = user ? user.toString() : data.userID; const formatted = ms(data.voice); voiceDescription += `**${i + 1}.** ${mention}: ${formatted.days} gün ${formatted.hours} saat ${formatted.minutes} dakika ${formatted.seconds} saniye\n`; } for (let i = 0; i < textList.length; i++) { const data = textList[i]; const user = client.users.cache.get(data.userID); const mention = user ? user.toString() : data.userID; textDescription += `**${i + 1}.** ${mention}: ${data.messages} mesaj\n`; } top.setDescription(`**Sesli Sıralaması:**\n${voiceDescription}\n\n**Mesaj Sıralaması:**\n${textDescription}`); return top; } async function generateChannelEmbed(member: GuildMember, channel: TextChannel): Promise<void> { const channelData = await ChannelModel.find({ userID: member.id, guildID: member.guild.id }); const voiceData = channelData .filter(data => data.type === "voice") .sort((a, c) => c.data - a.data) .slice(0, 30) .map((data, i) => { const channel = client.channels.cache.get(data.channelID) as VoiceChannel; const mention = channel ? channel.toString() : data.channelID; const formatted = ms(data.data); return `**${i + 1}.** ${mention}: ${formatted.days} gün ${formatted.hours} saat ${formatted.minutes} dakika ${formatted.seconds} saniye\n`; }) const textData = channelData .filter(data => data.type === "text") .sort((a, c) => c.data - a.data) .slice(0, 30) .map((data, i) => { const channel = client.channels.cache.get(data.channelID) as TextChannel; const mention = channel ? channel.toString() : data.channelID; return `**${i + 1}.** ${mention}: ${data.data} mesaj\n`; }) const embed = new MessageEmbed() .setTitle("Kanal Sıralaması") .setTimestamp(Date.now()) .setDescription( `**Sesli Sıralaması:**\n${voiceData.join("")}\n\n**Mesaj Sıralaması:**\n${textData.join("")}` ) .setColor("BLACK") .setFooter("Kanal Sıralaması") await channel.send(embed); } connect(CONFIG.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false, useCreateIndex: true }) .then(async () => { pogger.success("MongoDB'ye bağlanıldı."); await client.login(CONFIG.BOT_TOKEN); });
the_stack
import * as gregor1 from '../gregor1' import * as keybase1 from '../keybase1' import * as stellar1 from '../stellar1' export type ConvIDStr = string export type TLFIDStr = string export type FlipGameIDStr = string export type RateLimitRes = { tank: string capacity: number reset: number gas: number } /** * A Keybase chat channel. This can be a channel in a team, or just an informal channel between two users. * name: the name of the team or comma-separated list of participants */ export type ChatChannel = { name: string public?: boolean membersType?: string topicType?: string topicName?: string } /** * A chat message. The content goes in the `body` property! */ export type ChatMessage = { body: string } export type MsgSender = { uid: keybase1.UID username?: string deviceId: keybase1.DeviceID deviceName?: string } export type MsgBotInfo = { botUid: keybase1.UID botUsername?: string } export type DeviceInfo = { id: keybase1.DeviceID description: string type: keybase1.DeviceTypeV2 ctime: number } export type UIPagination = { next: string previous: string num: number last: boolean } export enum UIInboxBigTeamRowTyp { LABEL = 'label', CHANNEL = 'channel', } export enum UIParticipantType { NONE = 'none', USER = 'user', PHONENO = 'phoneno', EMAIL = 'email', } export type UIAssetUrlInfo = { previewUrl: string fullUrl: string fullUrlCached: boolean mimeType: string videoDuration?: string inlineVideoPlayable: boolean } export type UIPaymentInfo = { accountId?: stellar1.AccountID amountDescription: string worth: string worthAtSendTime: string delta: stellar1.BalanceDelta note: string paymentId: stellar1.PaymentID status: stellar1.PaymentStatus statusDescription: string statusDetail: string showCancel: boolean fromUsername: string toUsername: string sourceAmount: string sourceAsset: stellar1.Asset issuerDescription: string } export type UIRequestInfo = { amount: string amountDescription: string asset?: stellar1.Asset currency?: stellar1.OutsideCurrencyCode worthAtRequestTime: string status: stellar1.RequestStatus } export enum MessageUnboxedState { VALID = 'valid', ERROR = 'error', OUTBOX = 'outbox', PLACEHOLDER = 'placeholder', JOURNEYCARD = 'journeycard', } export enum UITextDecorationTyp { PAYMENT = 'payment', ATMENTION = 'atmention', CHANNELNAMEMENTION = 'channelnamemention', MAYBEMENTION = 'maybemention', LINK = 'link', MAILTO = 'mailto', KBFSPATH = 'kbfspath', EMOJI = 'emoji', } export enum UIMaybeMentionStatus { UNKNOWN = 'unknown', USER = 'user', TEAM = 'team', NOTHING = 'nothing', } export type UILinkDecoration = { url: string punycode: string } export enum UIChatThreadStatusTyp { NONE = 'none', SERVER = 'server', VALIDATING = 'validating', VALIDATED = 'validated', } export type UIChatThreadStatus = | {typ: UIChatThreadStatusTyp.NONE} | {typ: UIChatThreadStatusTyp.SERVER} | {typ: UIChatThreadStatusTyp.VALIDATING; VALIDATING: number} | {typ: UIChatThreadStatusTyp.VALIDATED} | { typ: Exclude< UIChatThreadStatusTyp, UIChatThreadStatusTyp.NONE | UIChatThreadStatusTyp.SERVER | UIChatThreadStatusTyp.VALIDATING | UIChatThreadStatusTyp.VALIDATED > } export type UIChatSearchTeamHits = { hits: keybase1.TeamSearchItem[] | null suggestedMatches: boolean } export type UIChatSearchBotHits = { hits: keybase1.FeaturedBot[] | null suggestedMatches: boolean } export type UIChatPayment = { username: string fullName: string xlmAmount: string error?: string displayAmount?: string } export type GiphySearchResult = { targetUrl: string previewUrl: string previewWidth: number previewHeight: number previewIsVideo: boolean } export enum UICoinFlipPhase { COMMITMENT = 'commitment', REVEALS = 'reveals', COMPLETE = 'complete', ERROR = 'error', } export type UICoinFlipErrorParticipant = { user: string device: string } export enum UICoinFlipErrorTyp { GENERIC = 'generic', ABSENTEE = 'absentee', TIMEOUT = 'timeout', ABORTED = 'aborted', DUPREG = 'dupreg', DUPCOMMITCOMPLETE = 'dupcommitcomplete', DUPREVEAL = 'dupreveal', COMMITMISMATCH = 'commitmismatch', } export enum UICoinFlipResultTyp { NUMBER = 'number', SHUFFLE = 'shuffle', DECK = 'deck', HANDS = 'hands', COIN = 'coin', } export type UICoinFlipHand = { target: string hand: number[] | null } export type UICoinFlipParticipant = { uid: string deviceId: string username: string deviceName: string commitment: string reveal?: string } export type UICommandMarkdown = { body: string title?: string } export type LocationWatchID = number export enum UIWatchPositionPerm { BASE = 'base', ALWAYS = 'always', } export enum UICommandStatusDisplayTyp { STATUS = 'status', WARNING = 'warning', ERROR = 'error', } export enum UICommandStatusActionTyp { APPSETTINGS = 'appsettings', } export enum UIBotCommandsUpdateStatusTyp { UPTODATE = 'uptodate', UPDATING = 'updating', FAILED = 'failed', BLANK = 'blank', } export type UIBotCommandsUpdateSettings = { settings: {[key: string]: keybase1.TeamBotSettings} } export type ConversationCommand = { description: string name: string usage: string hasHelpText: boolean username?: string } export enum ConversationCommandGroupsTyp { BUILTIN = 'builtin', CUSTOM = 'custom', NONE = 'none', } export enum ConversationBuiltinCommandTyp { NONE = 'none', ADHOC = 'adhoc', SMALLTEAM = 'smallteam', BIGTEAM = 'bigteam', BIGTEAMGENERAL = 'bigteamgeneral', } export type ThreadID = Buffer export type MessageID = number export type TLFConvOrdinal = number export type TopicID = Buffer export type ConversationID = Buffer export type TLFID = Buffer export type Hash = Buffer export type InboxVers = number export type LocalConversationVers = number export type ConversationVers = number export type OutboxID = Buffer export type TopicNameState = Buffer export type FlipGameID = Buffer export enum ConversationExistence { ACTIVE = 'active', ARCHIVED = 'archived', DELETED = 'deleted', ABANDONED = 'abandoned', } export enum ConversationMembersType { KBFS = 'kbfs', TEAM = 'team', IMPTEAMNATIVE = 'impteamnative', IMPTEAMUPGRADE = 'impteamupgrade', } export enum SyncInboxResType { CURRENT = 'current', INCREMENTAL = 'incremental', CLEAR = 'clear', } export enum MessageType { NONE = 'none', TEXT = 'text', ATTACHMENT = 'attachment', EDIT = 'edit', DELETE = 'delete', METADATA = 'metadata', TLFNAME = 'tlfname', HEADLINE = 'headline', ATTACHMENTUPLOADED = 'attachmentuploaded', JOIN = 'join', LEAVE = 'leave', SYSTEM = 'system', DELETEHISTORY = 'deletehistory', REACTION = 'reaction', SENDPAYMENT = 'sendpayment', REQUESTPAYMENT = 'requestpayment', UNFURL = 'unfurl', FLIP = 'flip', PIN = 'pin', } export enum TopicType { NONE = 'none', CHAT = 'chat', DEV = 'dev', KBFSFILEEDIT = 'kbfsfileedit', EMOJI = 'emoji', EMOJICROSS = 'emojicross', } export enum TeamType { NONE = 'none', SIMPLE = 'simple', COMPLEX = 'complex', } export enum NotificationKind { GENERIC = 'generic', ATMENTION = 'atmention', } export enum GlobalAppNotificationSetting { NEWMESSAGES = 'newmessages', PLAINTEXTMOBILE = 'plaintextmobile', PLAINTEXTDESKTOP = 'plaintextdesktop', DEFAULTSOUNDMOBILE = 'defaultsoundmobile', DISABLETYPING = 'disabletyping', } export type GlobalAppNotificationSettings = { settings: {[key: string]: boolean} } export enum ConversationStatus { UNFILED = 'unfiled', FAVORITE = 'favorite', IGNORED = 'ignored', BLOCKED = 'blocked', MUTED = 'muted', REPORTED = 'reported', } export type KBFSPath = { startIndex: number rawPath: string standardPath: string pathInfo: keybase1.KBFSPathInfo } export enum ConversationMemberStatus { ACTIVE = 'active', REMOVED = 'removed', LEFT = 'left', PREVIEW = 'preview', RESET = 'reset', NEVER_JOINED = 'never_joined', } export type Pagination = { next?: Buffer previous?: Buffer num: number last?: boolean forceFirstPage?: boolean } export type RateLimit = { name: string callsRemaining: number windowReset: number maxCalls: number } export enum InboxParticipantsMode { ALL = 'all', SKIP_TEAMS = 'skip_teams', } export type ConversationFinalizeInfo = { resetUser: string resetDate: string resetFull: string resetTimestamp: gregor1.Time } export type ConversationResolveInfo = { newTlfName: string } export type ConversationNotificationInfo = { channelWide: boolean settings: {[key: string]: {[key: string]: boolean}} } export type ConversationJourneycardInfo = { w: boolean } export type ConversationCreatorInfo = { ctime: gregor1.Time uid: gregor1.UID } export type ConversationCreatorInfoLocal = { ctime: gregor1.Time username: string } export type ConversationMinWriterRoleInfo = { uid: gregor1.UID role: keybase1.TeamRole } export type MsgEphemeralMetadata = { l: gregor1.DurationSec g: keybase1.EkGeneration u?: string } export type EncryptedData = { v: number e: Buffer n: Buffer } export type SignEncryptedData = { v: number e: Buffer n: Buffer } export type SealedData = { v: number e: Buffer n: Buffer } export type SignatureInfo = { v: number s: Buffer k: Buffer } export type MerkleRoot = { seqno: number hash: Buffer } export enum InboxResType { VERSIONHIT = 'versionhit', FULL = 'full', } export enum RetentionPolicyType { NONE = 'none', RETAIN = 'retain', EXPIRE = 'expire', INHERIT = 'inherit', EPHEMERAL = 'ephemeral', } export type RpRetain = {} export type RpExpire = { age: gregor1.DurationSec } export type RpInherit = {} export type RpEphemeral = { age: gregor1.DurationSec } export enum GetThreadReason { GENERAL = 'general', PUSH = 'push', FOREGROUND = 'foreground', BACKGROUNDCONVLOAD = 'backgroundconvload', FIXRETRY = 'fixretry', PREPARE = 'prepare', SEARCHER = 'searcher', INDEXED_SEARCH = 'indexed_search', KBFSFILEACTIVITY = 'kbfsfileactivity', COINFLIP = 'coinflip', BOTCOMMANDS = 'botcommands', EMOJISOURCE = 'emojisource', } export enum ReIndexingMode { NONE = 'none', PRESEARCH_SYNC = 'presearch_sync', POSTSEARCH_SYNC = 'postsearch_sync', } export type EmptyStruct = {} export type ChatSearchMatch = { startIndex: number endIndex: number match: string } export type ChatSearchInboxDone = { numHits: number numConvs: number percentIndexed: number delegated: boolean } export type ChatSearchIndexStatus = { percentIndexed: number } export type AssetMetadataImage = { width: number height: number audioAmps: number[] | null } export type AssetMetadataVideo = { width: number height: number durationMs: number isAudio: boolean } export enum AssetMetadataType { NONE = 'none', IMAGE = 'image', VIDEO = 'video', } export enum AssetTag { PRIMARY = 'primary', } export enum BotCommandsAdvertisementTyp { PUBLIC = 'public', TLFID_MEMBERS = 'tlfid_members', TLFID_CONVS = 'tlfid_convs', } export type TeamMember = { uid: gregor1.UID role: keybase1.TeamRole status: keybase1.TeamMemberStatus } export enum LastActiveStatus { NONE = 'none', ACTIVE = 'active', RECENTLY_ACTIVE = 'recently_active', } export type ChatMemberDetails = { uid: keybase1.UID username: string fullName: keybase1.FullName } export enum EmojiLoadSourceTyp { HTTPSRV = 'httpsrv', STR = 'str', } export type EmojiLoadSource = | {typ: EmojiLoadSourceTyp.HTTPSRV; HTTPSRV: string} | {typ: EmojiLoadSourceTyp.STR; STR: string} | {typ: Exclude<EmojiLoadSourceTyp, EmojiLoadSourceTyp.HTTPSRV | EmojiLoadSourceTyp.STR>} export enum EmojiRemoteSourceTyp { MESSAGE = 'message', STOCKALIAS = 'stockalias', } export type EmojiStockAlias = { text: string username: string time: gregor1.Time } export type EmojiCreationInfo = { username: string time: gregor1.Time } export type VersionKind = string export enum TextPaymentResultTyp { SENT = 'sent', ERROR = 'error', } export type TextPaymentResult = | {resultTyp: TextPaymentResultTyp.ERROR; ERROR: string} | {resultTyp: TextPaymentResultTyp.SENT; SENT: stellar1.PaymentID} | {resultTyp: Exclude<TextPaymentResultTyp, TextPaymentResultTyp.ERROR | TextPaymentResultTyp.SENT>} export type KnownUserMention = { text: string uid: gregor1.UID } export type KnownTeamMention = { name: string channel: string } export type MaybeMention = { name: string channel: string } export type Coordinate = { lat: number lon: number accuracy: number } export type LiveLocation = { endTime: gregor1.Time } export type MessageConversationMetadata = { conversationTitle: string } export enum MessageSystemType { ADDEDTOTEAM = 'addedtoteam', INVITEADDEDTOTEAM = 'inviteaddedtoteam', COMPLEXTEAM = 'complexteam', CREATETEAM = 'createteam', GITPUSH = 'gitpush', CHANGEAVATAR = 'changeavatar', CHANGERETENTION = 'changeretention', BULKADDTOCONV = 'bulkaddtoconv', SBSRESOLVE = 'sbsresolve', NEWCHANNEL = 'newchannel', } export type MessageSystemAddedToTeam = { team: string adder: string addee: string role: keybase1.TeamRole bulkAdds: string[] | null } export type MessageSystemInviteAddedToTeam = { team: string inviter: string invitee: string adder: string inviteType: keybase1.TeamInviteCategory role: keybase1.TeamRole } export type MessageSystemComplexTeam = { team: string } export type MessageSystemCreateTeam = { team: string creator: string } export type MessageSystemGitPush = { team: string pusher: string repoName: string repoId: keybase1.RepoID refs: keybase1.GitRefMetadata[] | null pushType: keybase1.GitPushType previousRepoName: string } export type MessageSystemChangeAvatar = { team: string user: string } export type MessageSystemBulkAddToConv = { usernames: string[] | null } export type MessageSystemSbsResolve = { assertionService: string assertionUsername: string prover: string } export type MessageJoin = { joiners: string[] | null leavers: string[] | null } export type MessageLeave = {} export type MessageSendPayment = { paymentId: stellar1.PaymentID } export type MessageRequestPayment = { requestId: stellar1.KeybaseRequestID note: string } export enum OutboxStateType { SENDING = 'sending', ERROR = 'error', } export enum OutboxErrorType { MISC = 'misc', OFFLINE = 'offline', IDENTIFY = 'identify', TOOLONG = 'toolong', DUPLICATE = 'duplicate', EXPIRED = 'expired', TOOMANYATTEMPTS = 'toomanyattempts', ALREADY_DELETED = 'already_deleted', UPLOADFAILED = 'uploadfailed', RESTRICTEDBOT = 'restrictedbot', MINWRITER = 'minwriter', } export enum HeaderPlaintextVersion { V1 = 'v1', V2 = 'v2', V3 = 'v3', V4 = 'v4', V5 = 'v5', V6 = 'v6', V7 = 'v7', V8 = 'v8', V9 = 'v9', V10 = 'v10', } export type HeaderPlaintextMetaInfo = { crit: boolean } export enum BodyPlaintextVersion { V1 = 'v1', V2 = 'v2', V3 = 'v3', V4 = 'v4', V5 = 'v5', V6 = 'v6', V7 = 'v7', V8 = 'v8', V9 = 'v9', V10 = 'v10', } export type BodyPlaintextMetaInfo = { crit: boolean } export enum MessageUnboxedErrorType { MISC = 'misc', BADVERSION_CRITICAL = 'badversion_critical', BADVERSION = 'badversion', IDENTIFY = 'identify', EPHEMERAL = 'ephemeral', PAIRWISE_MISSING = 'pairwise_missing', } export enum JourneycardType { WELCOME = 'welcome', POPULAR_CHANNELS = 'popular_channels', ADD_PEOPLE = 'add_people', CREATE_CHANNELS = 'create_channels', MSG_ATTENTION = 'msg_attention', UNUSED = 'unused', CHANNEL_INACTIVE = 'channel_inactive', MSG_NO_ANSWER = 'msg_no_answer', } export type UnreadFirstNumLimit = { numRead: number atLeast: number atMost: number } export type ConversationLocalParticipant = { username: string inConvName: boolean fullname?: string contactName?: string } export enum ConversationErrorType { PERMANENT = 'permanent', MISSINGINFO = 'missinginfo', SELFREKEYNEEDED = 'selfrekeyneeded', OTHERREKEYNEEDED = 'otherrekeyneeded', IDENTIFY = 'identify', TRANSIENT = 'transient', NONE = 'none', } export type ConversationErrorRekey = { tlfName: string tlfPublic: boolean rekeyers: string[] | null writerNames: string[] | null readerNames: string[] | null } export type ConversationMinWriterRoleInfoLocal = { changedBy: string cannotWrite: boolean role: keybase1.TeamRole } export enum MessageIDControlMode { OLDERMESSAGES = 'oldermessages', NEWERMESSAGES = 'newermessages', CENTERED = 'centered', UNREADLINE = 'unreadline', } export enum GetThreadNonblockCbMode { FULL = 'full', INCREMENTAL = 'incremental', } export enum GetThreadNonblockPgMode { DEFAULT = 'default', SERVER = 'server', } export enum InboxLayoutReselectMode { DEFAULT = 'default', FORCE = 'force', } export enum PreviewLocationTyp { URL = 'url', FILE = 'file', BYTES = 'bytes', } export type PreviewLocation = | {ltyp: PreviewLocationTyp.URL; URL: string} | {ltyp: PreviewLocationTyp.FILE; FILE: string} | {ltyp: PreviewLocationTyp.BYTES; BYTES: Buffer} | {ltyp: Exclude<PreviewLocationTyp, PreviewLocationTyp.URL | PreviewLocationTyp.FILE | PreviewLocationTyp.BYTES>} export enum UnfurlPromptAction { ALWAYS = 'always', NEVER = 'never', ACCEPT = 'accept', NOTNOW = 'notnow', ONETIME = 'onetime', } export type UnfurlPromptResult = | {actionType: UnfurlPromptAction.ALWAYS} | {actionType: UnfurlPromptAction.NEVER} | {actionType: UnfurlPromptAction.NOTNOW} | {actionType: UnfurlPromptAction.ACCEPT; ACCEPT: string} | {actionType: UnfurlPromptAction.ONETIME; ONETIME: string} | { actionType: Exclude< UnfurlPromptAction, | UnfurlPromptAction.ALWAYS | UnfurlPromptAction.NEVER | UnfurlPromptAction.NOTNOW | UnfurlPromptAction.ACCEPT | UnfurlPromptAction.ONETIME > } export enum GalleryItemTyp { MEDIA = 'media', LINK = 'link', DOC = 'doc', } export type UserBotExtendedDescription = { title: string desktopBody: string mobileBody: string } export enum SnippetDecoration { NONE = 'none', PENDING_MESSAGE = 'pending_message', FAILED_PENDING_MESSAGE = 'failed_pending_message', EXPLODING_MESSAGE = 'exploding_message', EXPLODED_MESSAGE = 'exploded_message', AUDIO_ATTACHMENT = 'audio_attachment', VIDEO_ATTACHMENT = 'video_attachment', PHOTO_ATTACHMENT = 'photo_attachment', FILE_ATTACHMENT = 'file_attachment', STELLAR_RECEIVED = 'stellar_received', STELLAR_SENT = 'stellar_sent', PINNED_MESSAGE = 'pinned_message', } export type WelcomeMessageDisplay = { set: boolean display: string raw: string } export type WelcomeMessage = { set: boolean raw: string } export type LastActiveTimeAll = { teams: {[key: string]: gregor1.Time} channels: {[key: string]: gregor1.Time} } export type EmojiError = { clidisplay: string uidisplay: string } export type EmojiFetchOpts = { getCreationInfo: boolean getAliases: boolean onlyInTeam: boolean } export enum ChatActivitySource { LOCAL = 'local', REMOTE = 'remote', } export enum ChatActivityType { RESERVED = 'reserved', INCOMING_MESSAGE = 'incoming_message', READ_MESSAGE = 'read_message', NEW_CONVERSATION = 'new_conversation', SET_STATUS = 'set_status', FAILED_MESSAGE = 'failed_message', MEMBERS_UPDATE = 'members_update', SET_APP_NOTIFICATION_SETTINGS = 'set_app_notification_settings', TEAMTYPE = 'teamtype', EXPUNGE = 'expunge', EPHEMERAL_PURGE = 'ephemeral_purge', REACTION_UPDATE = 'reaction_update', MESSAGES_UPDATED = 'messages_updated', } export type TyperInfo = { uid: keybase1.UID username: string deviceId: keybase1.DeviceID } export enum StaleUpdateType { CLEAR = 'clear', NEWACTIVITY = 'newactivity', } export enum MessageBoxedVersion { VNONE = 'vnone', V1 = 'v1', V2 = 'v2', V3 = 'v3', V4 = 'v4', } export enum ChannelMention { NONE = 'none', ALL = 'all', HERE = 'here', } export type S3Params = { bucket: string objectKey: string accessKey: string acl: string regionName: string regionEndpoint: string regionBucketEndpoint: string } export type ServerCacheVers = { inboxVers: number bodiesVers: number } export enum SyncAllProtVers { V0 = 'v0', V1 = 'v1', } export enum SyncAllNotificationType { STATE = 'state', INCREMENTAL = 'incremental', } export type SyncAllNotificationRes = | {typ: SyncAllNotificationType.STATE; STATE: gregor1.State} | {typ: SyncAllNotificationType.INCREMENTAL; INCREMENTAL: gregor1.SyncResult} | {typ: Exclude<SyncAllNotificationType, SyncAllNotificationType.STATE | SyncAllNotificationType.INCREMENTAL>} export enum ExternalAPIKeyTyp { GOOGLEMAPS = 'googlemaps', GIPHY = 'giphy', } export type ExternalAPIKey = | {typ: ExternalAPIKeyTyp.GOOGLEMAPS; GOOGLEMAPS: string} | {typ: ExternalAPIKeyTyp.GIPHY; GIPHY: string} | {typ: Exclude<ExternalAPIKeyTyp, ExternalAPIKeyTyp.GOOGLEMAPS | ExternalAPIKeyTyp.GIPHY>} export type BotInfoHashVers = number export type CommandConvVers = number export enum BotInfoResponseTyp { UPTODATE = 'uptodate', INFO = 'info', } export type BotInfoHash = Buffer export enum UnfurlType { GENERIC = 'generic', YOUTUBE = 'youtube', GIPHY = 'giphy', MAPS = 'maps', } export type UnfurlVideo = { url: string mimeType: string height: number width: number } export type UnfurlYoutubeRaw = {} export type UnfurlYoutube = {} export type UnfurlImageDisplay = { url: string height: number width: number isVideo: boolean } export type UnfurlYoutubeDisplay = {} export enum UnfurlMode { ALWAYS = 'always', NEVER = 'never', WHITELISTED = 'whitelisted', } export type MsgFlipContent = { text: string gameId: FlipGameIDStr flipConvId: ConvIDStr userMentions: KnownUserMention[] | null teamMentions: KnownTeamMention[] | null } export type EmojiContent = { alias: string isCrossTeam: boolean convId?: ConvIDStr messageId?: MessageID } /** * A chat conversation. This is essentially a chat channel plus some additional metadata. */ export type ConvSummary = { id: ConvIDStr channel: ChatChannel isDefaultConv: boolean unread: boolean activeAt: number activeAtMs: number memberStatus: string resetUsers?: string[] | null finalizeInfo?: ConversationFinalizeInfo supersedes?: string[] | null supersededBy?: string[] | null error?: string creatorInfo?: ConversationCreatorInfoLocal } export type SendRes = { message: string id?: MessageID outboxId?: OutboxID identifyFailures?: keybase1.TLFIdentifyFailure[] | null ratelimits?: RateLimitRes[] | null } export type NewConvRes = { id: ConvIDStr identifyFailures?: keybase1.TLFIdentifyFailure[] | null ratelimits?: RateLimitRes[] | null } export type EmptyRes = { ratelimits?: RateLimitRes[] | null } export type ResetConvMemberAPI = { conversationId: ConvIDStr username: string } export type GetDeviceInfoRes = { devices: DeviceInfo[] | null } export type UIInboxSmallTeamRow = { convId: ConvIDStr name: string time: gregor1.Time snippet?: string snippetDecoration: SnippetDecoration draft?: string isMuted: boolean isTeam: boolean } export type UIInboxBigTeamChannelRow = { convId: ConvIDStr teamname: string channelname: string draft?: string isMuted: boolean } export type UIInboxBigTeamLabelRow = { name: string id: TLFIDStr } export type UIInboxReselectInfo = { oldConvId: ConvIDStr newConvId?: ConvIDStr } export type UnverifiedInboxUIItemMetadata = { channelName: string headline: string headlineDecorated: string snippet: string snippetDecoration: SnippetDecoration writerNames: string[] | null resetParticipants: string[] | null } export type UIParticipant = { type: UIParticipantType assertion: string inConvName: boolean fullName?: string contactName?: string } export type UIChannelNameMention = { name: string convId: ConvIDStr } export type UIMessageJourneycard = { ordinal: number cardType: JourneycardType highlightMsgId: MessageID openTeam: boolean } export type UITeamMention = { inTeam: boolean open: boolean description?: string numMembers?: number publicAdmins: string[] | null convId?: ConvIDStr } export type UIChatSearchConvHit = { convId: ConvIDStr teamType: TeamType name: string mtime: gregor1.Time } export type UIChatPaymentSummary = { xlmTotal: string displayTotal: string payments: UIChatPayment[] | null } export type GiphySearchResults = { results: GiphySearchResult[] | null galleryUrl: string } export type UICoinFlipAbsenteeError = { absentees: UICoinFlipErrorParticipant[] | null } export type UICoinFlipResult = | {typ: UICoinFlipResultTyp.NUMBER; NUMBER: string} | {typ: UICoinFlipResultTyp.SHUFFLE; SHUFFLE: string[]} | {typ: UICoinFlipResultTyp.DECK; DECK: number[]} | {typ: UICoinFlipResultTyp.HANDS; HANDS: UICoinFlipHand[]} | {typ: UICoinFlipResultTyp.COIN; COIN: boolean} | { typ: Exclude< UICoinFlipResultTyp, | UICoinFlipResultTyp.NUMBER | UICoinFlipResultTyp.SHUFFLE | UICoinFlipResultTyp.DECK | UICoinFlipResultTyp.HANDS | UICoinFlipResultTyp.COIN > } export type UIBotCommandsUpdateStatus = | {typ: UIBotCommandsUpdateStatusTyp.UPTODATE; UPTODATE: UIBotCommandsUpdateSettings} | {typ: UIBotCommandsUpdateStatusTyp.UPDATING} | {typ: UIBotCommandsUpdateStatusTyp.FAILED} | {typ: UIBotCommandsUpdateStatusTyp.BLANK} | { typ: Exclude< UIBotCommandsUpdateStatusTyp, | UIBotCommandsUpdateStatusTyp.UPTODATE | UIBotCommandsUpdateStatusTyp.UPDATING | UIBotCommandsUpdateStatusTyp.FAILED | UIBotCommandsUpdateStatusTyp.BLANK > } export type ConversationCommandGroupsCustom = { commands: ConversationCommand[] | null } export type InboxVersInfo = { uid: gregor1.UID vers: InboxVers } export type ConversationMember = { uid: gregor1.UID convId: ConversationID topicType: TopicType } export type ConversationIDMessageIDPair = { convId: ConversationID msgId: MessageID } export type ChannelNameMention = { convId: ConversationID topicName: string } export type GetInboxQuery = { convId?: ConversationID topicType?: TopicType tlfId?: TLFID tlfVisibility?: keybase1.TLFVisibility before?: gregor1.Time after?: gregor1.Time oneChatTypePerTlf?: boolean topicName?: string status: ConversationStatus[] | null memberStatus: ConversationMemberStatus[] | null existences: ConversationExistence[] | null membersTypes: ConversationMembersType[] | null convIDs: ConversationID[] | null unreadOnly: boolean readOnly: boolean computeActiveList: boolean summarizeMaxMsgs: boolean participantsMode: InboxParticipantsMode skipBgLoads: boolean allowUnseenQuery: boolean } export type ConversationIDTriple = { tlfid: TLFID topicType: TopicType topicId: TopicID } export type Expunge = { upto: MessageID basis: MessageID } export type ConversationReaderInfo = { mtime: gregor1.Time readMsgid: MessageID maxMsgid: MessageID status: ConversationMemberStatus untrustedTeamRole: keybase1.TeamRole l: gregor1.Time jc?: ConversationJourneycardInfo } export type ConversationSettings = { mwr?: ConversationMinWriterRoleInfo } export type MessageSummary = { msgId: MessageID messageType: MessageType tlfName: string tlfPublic: boolean ctime: gregor1.Time } export type Reaction = { ctime: gregor1.Time reactionMsgId: MessageID } export type MessageServerHeader = { messageId: MessageID supersededBy: MessageID r: MessageID[] | null u: MessageID[] | null replies: MessageID[] | null ctime: gregor1.Time n: gregor1.Time rt?: gregor1.Time } export type MessagePreviousPointer = { id: MessageID hash: Hash } export type OutboxInfo = { prev: MessageID composeTime: gregor1.Time } export type EphemeralPurgeInfo = { c: ConversationID a: boolean n: gregor1.Time e: MessageID } export type RetentionPolicy = | {typ: RetentionPolicyType.RETAIN; RETAIN: RpRetain} | {typ: RetentionPolicyType.EXPIRE; EXPIRE: RpExpire} | {typ: RetentionPolicyType.INHERIT; INHERIT: RpInherit} | {typ: RetentionPolicyType.EPHEMERAL; EPHEMERAL: RpEphemeral} | { typ: Exclude< RetentionPolicyType, RetentionPolicyType.RETAIN | RetentionPolicyType.EXPIRE | RetentionPolicyType.INHERIT | RetentionPolicyType.EPHEMERAL > } export type SearchOpts = { isRegex: boolean sentBy: string sentTo: string matchMentions: boolean sentBefore: gregor1.Time sentAfter: gregor1.Time maxHits: number maxMessages: number beforeContext: number afterContext: number initialPagination?: Pagination reindexMode: ReIndexingMode maxConvsSearched: number maxConvsHit: number convId?: ConversationID maxNameConvs: number maxTeams: number maxBots: number skipBotCache: boolean } export type AssetMetadata = | {assetType: AssetMetadataType.IMAGE; IMAGE: AssetMetadataImage} | {assetType: AssetMetadataType.VIDEO; VIDEO: AssetMetadataVideo} | {assetType: Exclude<AssetMetadataType, AssetMetadataType.IMAGE | AssetMetadataType.VIDEO>} export type ChatMembersDetails = { owners: ChatMemberDetails[] | null admins: ChatMemberDetails[] | null writers: ChatMemberDetails[] | null readers: ChatMemberDetails[] | null bots: ChatMemberDetails[] | null restrictedBots: ChatMemberDetails[] | null } export type EmojiMessage = { convId: ConversationID msgId: MessageID isAlias: boolean } export type UnreadUpdate = { convId: ConversationID unreadMessages: number unreadNotifyingMessages: {[key: string]: number} diff: boolean } export type TLFFinalizeUpdate = { finalizeInfo: ConversationFinalizeInfo convIDs: ConversationID[] | null inboxVers: InboxVers } export type TLFResolveUpdate = { convId: ConversationID inboxVers: InboxVers } export type RemoteUserTypingUpdate = { uid: gregor1.UID deviceId: gregor1.DeviceID convId: ConversationID typing: boolean teamType: TeamType } export type TeamMemberRoleUpdate = { tlfId: TLFID role: keybase1.TeamRole } export type ConversationUpdate = { convId: ConversationID existence: ConversationExistence } export type KBFSImpteamUpgradeUpdate = { convId: ConversationID inboxVers: InboxVers topicType: TopicType } export type SubteamRenameUpdate = { convIDs: ConversationID[] | null inboxVers: InboxVers } export type TextPayment = { username: string paymentText: string result: TextPaymentResult } export type MessageDelete = { messageIDs: MessageID[] | null } export type MessageFlip = { text: string gameId: FlipGameID flipConvId: ConversationID userMentions: KnownUserMention[] | null teamMentions: KnownTeamMention[] | null } export type MessagePin = { msgId: MessageID } export type MessageSystemNewChannel = { creator: string nameAtCreation: string convId: ConversationID } export type MessageDeleteHistory = { upto: MessageID } export type SenderPrepareOptions = { skipTopicNameState: boolean replyTo?: MessageID } export type SenderSendOptions = { joinMentionsAs?: ConversationMemberStatus } export type OutboxStateError = { message: string typ: OutboxErrorType } export type HeaderPlaintextUnsupported = { mi: HeaderPlaintextMetaInfo } export type BodyPlaintextUnsupported = { mi: BodyPlaintextMetaInfo } export type MessageUnboxedError = { errType: MessageUnboxedErrorType errMsg: string internalErrMsg: string versionKind: VersionKind versionNumber: number isCritical: boolean senderUsername: string senderDeviceName: string senderDeviceType: keybase1.DeviceTypeV2 messageId: MessageID messageType: MessageType ctime: gregor1.Time isEphemeral: boolean explodedBy?: string etime: gregor1.Time botUsername: string } export type MessageUnboxedPlaceholder = { messageId: MessageID hidden: boolean } export type MessageUnboxedJourneycard = { prevId: MessageID ordinal: number cardType: JourneycardType highlightMsgId: MessageID openTeam: boolean } export type ConversationSettingsLocal = { minWriterRoleInfo?: ConversationMinWriterRoleInfoLocal } export type NonblockFetchRes = { offline: boolean rateLimits: RateLimit[] | null identifyFailures: keybase1.TLFIdentifyFailure[] | null } export type MessageIDControl = { pivot?: MessageID mode: MessageIDControlMode num: number } export type UnreadlineRes = { offline: boolean rateLimits: RateLimit[] | null identifyFailures: keybase1.TLFIdentifyFailure[] | null unreadlineId?: MessageID } export type NameQuery = { name: string tlfId?: TLFID membersType: ConversationMembersType } export type PostLocalRes = { rateLimits: RateLimit[] | null messageId: MessageID identifyFailures: keybase1.TLFIdentifyFailure[] | null } export type PostLocalNonblockRes = { rateLimits: RateLimit[] | null outboxId: OutboxID identifyFailures: keybase1.TLFIdentifyFailure[] | null } export type EditTarget = { messageId?: MessageID outboxId?: OutboxID } export type SetConversationStatusLocalRes = { rateLimits: RateLimit[] | null identifyFailures: keybase1.TLFIdentifyFailure[] | null } export type NewConversationLocalArgument = { tlfName: string topicType: TopicType tlfVisibility: keybase1.TLFVisibility topicName?: string membersType: ConversationMembersType } export type GetInboxSummaryForCLILocalQuery = { topicType: TopicType after: string before: string visibility: keybase1.TLFVisibility status: ConversationStatus[] | null convIDs: ConversationID[] | null unreadFirst: boolean unreadFirstLimit: UnreadFirstNumLimit activitySortedLimit: number } export type DownloadAttachmentLocalRes = { rateLimits: RateLimit[] | null identifyFailures: keybase1.TLFIdentifyFailure[] | null } export type DownloadFileAttachmentLocalRes = { filePath: string rateLimits: RateLimit[] | null identifyFailures: keybase1.TLFIdentifyFailure[] | null } export type MarkAsReadLocalRes = { offline: boolean rateLimits: RateLimit[] | null } export type JoinLeaveConversationLocalRes = { offline: boolean rateLimits: RateLimit[] | null } export type DeleteConversationLocalRes = { offline: boolean rateLimits: RateLimit[] | null } export type GetMutualTeamsLocalRes = { teamIDs: keybase1.TeamID[] | null offline: boolean rateLimits: RateLimit[] | null } export type SetAppNotificationSettingsLocalRes = { offline: boolean rateLimits: RateLimit[] | null } export type AppNotificationSettingLocal = { deviceType: keybase1.DeviceType kind: NotificationKind enabled: boolean } export type ResetConvMember = { username: string uid: gregor1.UID conv: ConversationID } export type SimpleSearchInboxConvNamesHit = { name: string convId: ConversationID isTeam: boolean parts: string[] | null tlfName: string } export type ProfileSearchConvStats = { err: string convName: string minConvId: MessageID maxConvId: MessageID numMissing: number numMessages: number indexSizeDisk: number indexSizeMem: number durationMsec: gregor1.DurationMsec percentIndexed: number } export type BuiltinCommandGroup = { typ: ConversationBuiltinCommandTyp commands: ConversationCommand[] | null } export type UserBotCommandOutput = { name: string description: string usage: string extendedDescription?: UserBotExtendedDescription username: string } export type UserBotCommandInput = { name: string description: string usage: string extendedDescription?: UserBotExtendedDescription } export type AdvertiseBotCommandsLocalRes = { rateLimits: RateLimit[] | null } export type ClearBotCommandsLocalRes = { rateLimits: RateLimit[] | null } export type PinMessageRes = { rateLimits: RateLimit[] | null } export type AddBotConvSearchHit = { name: string convId: ConversationID isTeam: boolean parts: string[] | null } export type LocalMtimeUpdate = { convId: ConversationID mtime: gregor1.Time } export type SetDefaultTeamChannelsLocalRes = { rateLimit?: RateLimit } export type LastActiveStatusAll = { teams: {[key: string]: LastActiveStatus} channels: {[key: string]: LastActiveStatus} } export type AddEmojiRes = { rateLimit?: RateLimit error?: EmojiError } export type AddEmojisRes = { rateLimit?: RateLimit successFilenames: string[] | null failedFilenames: {[key: string]: EmojiError} } export type AddEmojiAliasRes = { rateLimit?: RateLimit error?: EmojiError } export type RemoveEmojiRes = { rateLimit?: RateLimit } export type SetAppNotificationSettingsInfo = { convId: ConversationID settings: ConversationNotificationInfo } export type MemberInfo = { member: string status: ConversationMemberStatus } export type ConvTypingUpdate = { convId: ConversationID typers: TyperInfo[] | null } export type ConversationStaleUpdate = { convId: ConversationID updateType: StaleUpdateType } export type NewConversationRemoteRes = { convId: ConversationID createdComplexTeam: boolean rateLimit?: RateLimit } export type MarkAsReadRes = { rateLimit?: RateLimit } export type SetConversationStatusRes = { rateLimit?: RateLimit } export type GetUnreadlineRemoteRes = { unreadlineId?: MessageID rateLimit?: RateLimit } export type JoinLeaveConversationRemoteRes = { rateLimit?: RateLimit } export type DeleteConversationRemoteRes = { rateLimit?: RateLimit } export type GetMessageBeforeRes = { msgId: MessageID rateLimit?: RateLimit } export type SetAppNotificationSettingsRes = { rateLimit?: RateLimit } export type SetRetentionRes = { rateLimit?: RateLimit } export type SetConvMinWriterRoleRes = { rateLimit?: RateLimit } export type ServerNowRes = { rateLimit?: RateLimit now: gregor1.Time } export type RemoteBotCommandsAdvertisementPublic = { convId: ConversationID } export type RemoteBotCommandsAdvertisementTLFID = { convId: ConversationID tlfId: TLFID } export type BotCommandConv = { uid: gregor1.UID untrustedTeamRole: keybase1.TeamRole convId: ConversationID vers: CommandConvVers mtime: gregor1.Time } export type AdvertiseBotCommandsRes = { rateLimit?: RateLimit } export type ClearBotCommandsRes = { rateLimit?: RateLimit } export type GetDefaultTeamChannelsRes = { convs: ConversationID[] | null rateLimit?: RateLimit } export type SetDefaultTeamChannelsRes = { rateLimit?: RateLimit } export type GetRecentJoinsRes = { numJoins: number rateLimit?: RateLimit } export type RefreshParticipantsRemoteRes = { hashMatch: boolean uids: gregor1.UID[] | null hash: string rateLimit?: RateLimit } export type GetLastActiveAtRes = { lastActiveAt: gregor1.Time rateLimit?: RateLimit } export type ResetConversationMember = { convId: ConversationID uid: gregor1.UID } export type UnfurlGenericRaw = { title: string url: string siteName: string faviconUrl?: string imageUrl?: string video?: UnfurlVideo publishTime?: number description?: string } export type UnfurlGiphyRaw = { imageUrl?: string video?: UnfurlVideo faviconUrl?: string } export type UnfurlMapsRaw = { title: string url: string siteName: string imageUrl: string historyImageUrl?: string description: string coord: Coordinate time: gregor1.Time liveLocationEndTime?: gregor1.Time liveLocationDone: boolean } export type UnfurlGenericMapInfo = { coord: Coordinate time: gregor1.Time liveLocationEndTime?: gregor1.Time isLiveLocationDone: boolean } export type UnfurlGiphyDisplay = { favicon?: UnfurlImageDisplay image?: UnfurlImageDisplay video?: UnfurlImageDisplay } export type UnfurlSettings = { mode: UnfurlMode whitelist: {[key: string]: boolean} } export type UnfurlSettingsDisplay = { mode: UnfurlMode whitelist: string[] | null } export type MsgTextContent = { body: string payments: TextPayment[] | null replyTo?: MessageID replyToUid?: string userMentions: KnownUserMention[] | null teamMentions: KnownTeamMention[] | null liveLocation?: LiveLocation emojis: EmojiContent[] | null } export type ChatList = { conversations: ConvSummary[] | null offline: boolean identifyFailures?: keybase1.TLFIdentifyFailure[] | null ratelimits?: RateLimitRes[] | null } export type ListCommandsRes = { commands: UserBotCommandOutput[] | null ratelimits?: RateLimitRes[] | null } export type ConvNotification = { type: string conv?: ConvSummary error?: string } export type AdvertiseCommandAPIParam = { type: string commands: UserBotCommandInput[] | null teamName?: string } export type GetResetConvMembersRes = { members: ResetConvMemberAPI[] | null rateLimits: RateLimitRes[] | null } export type UIInboxBigTeamRow = | {state: UIInboxBigTeamRowTyp.LABEL; LABEL: UIInboxBigTeamLabelRow} | {state: UIInboxBigTeamRowTyp.CHANNEL; CHANNEL: UIInboxBigTeamChannelRow} | {state: Exclude<UIInboxBigTeamRowTyp, UIInboxBigTeamRowTyp.LABEL | UIInboxBigTeamRowTyp.CHANNEL>} export type UIReactionDesc = { decorated: string users: {[key: string]: Reaction} } export type UIMaybeMentionInfo = | {status: UIMaybeMentionStatus.UNKNOWN} | {status: UIMaybeMentionStatus.USER} | {status: UIMaybeMentionStatus.TEAM; TEAM: UITeamMention} | {status: UIMaybeMentionStatus.NOTHING} | { status: Exclude< UIMaybeMentionStatus, UIMaybeMentionStatus.UNKNOWN | UIMaybeMentionStatus.USER | UIMaybeMentionStatus.TEAM | UIMaybeMentionStatus.NOTHING > } export type UIChatSearchConvHits = { hits: UIChatSearchConvHit[] | null unreadMatches: boolean } export type UICoinFlipError = | {typ: UICoinFlipErrorTyp.GENERIC; GENERIC: string} | {typ: UICoinFlipErrorTyp.ABSENTEE; ABSENTEE: UICoinFlipAbsenteeError} | {typ: UICoinFlipErrorTyp.TIMEOUT} | {typ: UICoinFlipErrorTyp.ABORTED} | {typ: UICoinFlipErrorTyp.DUPREG; DUPREG: UICoinFlipErrorParticipant} | {typ: UICoinFlipErrorTyp.DUPCOMMITCOMPLETE; DUPCOMMITCOMPLETE: UICoinFlipErrorParticipant} | {typ: UICoinFlipErrorTyp.DUPREVEAL; DUPREVEAL: UICoinFlipErrorParticipant} | {typ: UICoinFlipErrorTyp.COMMITMISMATCH; COMMITMISMATCH: UICoinFlipErrorParticipant} | { typ: Exclude< UICoinFlipErrorTyp, | UICoinFlipErrorTyp.GENERIC | UICoinFlipErrorTyp.ABSENTEE | UICoinFlipErrorTyp.TIMEOUT | UICoinFlipErrorTyp.ABORTED | UICoinFlipErrorTyp.DUPREG | UICoinFlipErrorTyp.DUPCOMMITCOMPLETE | UICoinFlipErrorTyp.DUPREVEAL | UICoinFlipErrorTyp.COMMITMISMATCH > } export type ConversationCommandGroups = | {typ: ConversationCommandGroupsTyp.BUILTIN; BUILTIN: ConversationBuiltinCommandTyp} | {typ: ConversationCommandGroupsTyp.CUSTOM; CUSTOM: ConversationCommandGroupsCustom} | {typ: ConversationCommandGroupsTyp.NONE} | { typ: Exclude< ConversationCommandGroupsTyp, ConversationCommandGroupsTyp.BUILTIN | ConversationCommandGroupsTyp.CUSTOM | ConversationCommandGroupsTyp.NONE > } export type ConversationIDMessageIDPairs = { pairs: ConversationIDMessageIDPair[] | null } export type ReactionMap = { reactions: {[key: string]: {[key: string]: Reaction}} } export type MessageClientHeader = { conv: ConversationIDTriple tlfName: string tlfPublic: boolean messageType: MessageType supersedes: MessageID kbfsCryptKeysUsed?: boolean deletes: MessageID[] | null prev: MessagePreviousPointer[] | null deleteHistory?: MessageDeleteHistory sender: gregor1.UID senderDevice: gregor1.DeviceID merkleRoot?: MerkleRoot outboxId?: OutboxID outboxInfo?: OutboxInfo em?: MsgEphemeralMetadata pm: {[key: string]: Buffer} b?: gregor1.UID t?: stellar1.TransactionID } export type MessageClientHeaderVerified = { conv: ConversationIDTriple tlfName: string tlfPublic: boolean messageType: MessageType prev: MessagePreviousPointer[] | null sender: gregor1.UID senderDevice: gregor1.DeviceID kbfsCryptKeysUsed?: boolean merkleRoot?: MerkleRoot outboxId?: OutboxID outboxInfo?: OutboxInfo em?: MsgEphemeralMetadata rt: gregor1.Time pm: boolean b?: gregor1.UID } export type Asset = { filename: string region: string endpoint: string bucket: string path: string size: number mimeType: string encHash: Hash ptHash: Hash key: Buffer verifyKey: Buffer title: string nonce: Buffer metadata: AssetMetadata tag: AssetTag } export type EmojiRemoteSource = | {typ: EmojiRemoteSourceTyp.MESSAGE; MESSAGE: EmojiMessage} | {typ: EmojiRemoteSourceTyp.STOCKALIAS; STOCKALIAS: EmojiStockAlias} | {typ: Exclude<EmojiRemoteSourceTyp, EmojiRemoteSourceTyp.MESSAGE | EmojiRemoteSourceTyp.STOCKALIAS>} export type GenericPayload = { action: string inboxVers: InboxVers convId: ConversationID topicType: TopicType unreadUpdate?: UnreadUpdate } export type NewConversationPayload = { action: string convId: ConversationID inboxVers: InboxVers topicType: TopicType unreadUpdate?: UnreadUpdate } export type ReadMessagePayload = { action: string convId: ConversationID msgId: MessageID inboxVers: InboxVers topicType: TopicType unreadUpdate?: UnreadUpdate } export type SetStatusPayload = { action: string convId: ConversationID status: ConversationStatus inboxVers: InboxVers topicType: TopicType unreadUpdate?: UnreadUpdate } export type TeamTypePayload = { action: string convId: ConversationID teamType: TeamType inboxVers: InboxVers topicType: TopicType unreadUpdate?: UnreadUpdate } export type SetAppNotificationSettingsPayload = { action: string convId: ConversationID inboxVers: InboxVers settings: ConversationNotificationInfo topicType: TopicType unreadUpdate?: UnreadUpdate } export type ExpungePayload = { action: string convId: ConversationID inboxVers: InboxVers expunge: Expunge maxMsgs: MessageSummary[] | null topicType: TopicType unreadUpdate?: UnreadUpdate } export type UpdateConversationMembership = { inboxVers: InboxVers teamMemberRoleUpdate?: TeamMemberRoleUpdate joined: ConversationMember[] | null removed: ConversationMember[] | null reset: ConversationMember[] | null previewed: ConversationID[] | null unreadUpdate?: UnreadUpdate unreadUpdates: UnreadUpdate[] | null } export type UpdateConversations = { inboxVers: InboxVers convUpdates: ConversationUpdate[] | null } export type SetConvRetentionUpdate = { inboxVers: InboxVers convId: ConversationID policy: RetentionPolicy } export type SetTeamRetentionUpdate = { inboxVers: InboxVers teamId: keybase1.TeamID policy: RetentionPolicy } export type SetConvSettingsUpdate = { inboxVers: InboxVers convId: ConversationID convSettings?: ConversationSettings } export type MessageSystemChangeRetention = { isTeam: boolean isInherit: boolean membersType: ConversationMembersType policy: RetentionPolicy user: string } export type OutboxState = | {state: OutboxStateType.SENDING; SENDING: number} | {state: OutboxStateType.ERROR; ERROR: OutboxStateError} | {state: Exclude<OutboxStateType, OutboxStateType.SENDING | OutboxStateType.ERROR>} export type HeaderPlaintextV1 = { conv: ConversationIDTriple tlfName: string tlfPublic: boolean messageType: MessageType prev: MessagePreviousPointer[] | null sender: gregor1.UID senderDevice: gregor1.DeviceID kbfsCryptKeysUsed?: boolean bodyHash: Hash outboxInfo?: OutboxInfo outboxId?: OutboxID headerSignature?: SignatureInfo merkleRoot?: MerkleRoot em?: MsgEphemeralMetadata b?: gregor1.UID } export type GetThreadQuery = { markAsRead: boolean messageTypes: MessageType[] | null disableResolveSupersedes: boolean enableDeletePlaceholders: boolean disablePostProcessThread: boolean before?: gregor1.Time after?: gregor1.Time messageIdControl?: MessageIDControl } export type GetInboxLocalQuery = { name?: NameQuery topicName?: string convIDs: ConversationID[] | null topicType?: TopicType tlfVisibility?: keybase1.TLFVisibility before?: gregor1.Time after?: gregor1.Time oneChatTypePerTlf?: boolean status: ConversationStatus[] | null memberStatus: ConversationMemberStatus[] | null unreadOnly: boolean readOnly: boolean computeActiveList: boolean } export type MakePreviewRes = { mimeType: string previewMimeType?: string location?: PreviewLocation metadata?: AssetMetadata baseMetadata?: AssetMetadata } export type GetChannelMembershipsLocalRes = { channels: ChannelNameMention[] | null offline: boolean rateLimits: RateLimit[] | null } export type GetAllResetConvMembersRes = { members: ResetConvMember[] | null rateLimits: RateLimit[] | null } export type StaticConfig = { deletableByDeleteHistory: MessageType[] | null builtinCommands: BuiltinCommandGroup[] | null } export type AdvertiseCommandsParam = { typ: BotCommandsAdvertisementTyp commands: UserBotCommandInput[] | null teamName?: string } export type ListBotCommandsLocalRes = { commands: UserBotCommandOutput[] | null rateLimits: RateLimit[] | null } export type MembersUpdateInfo = { convId: ConversationID members: MemberInfo[] | null } export type ExpungeInfo = { convId: ConversationID expunge: Expunge } export type PostRemoteRes = { msgHeader: MessageServerHeader rateLimit?: RateLimit } export type UnreadUpdateFull = { ignore: boolean inboxVers: InboxVers inboxSyncStatus: SyncInboxResType updates: UnreadUpdate[] | null } export type SweepRes = { foundTask: boolean deletedMessages: boolean expunge: Expunge } export type RemoteBotCommandsAdvertisement = | {typ: BotCommandsAdvertisementTyp.PUBLIC; PUBLIC: RemoteBotCommandsAdvertisementPublic} | {typ: BotCommandsAdvertisementTyp.TLFID_MEMBERS; TLFID_MEMBERS: RemoteBotCommandsAdvertisementTLFID} | {typ: BotCommandsAdvertisementTyp.TLFID_CONVS; TLFID_CONVS: RemoteBotCommandsAdvertisementTLFID} | { typ: Exclude< BotCommandsAdvertisementTyp, BotCommandsAdvertisementTyp.PUBLIC | BotCommandsAdvertisementTyp.TLFID_MEMBERS | BotCommandsAdvertisementTyp.TLFID_CONVS > } export type BotInfo = { serverHashVers: BotInfoHashVers clientHashVers: BotInfoHashVers commandConvs: BotCommandConv[] | null } export type GetResetConversationsRes = { resetConvs: ResetConversationMember[] | null rateLimit?: RateLimit } export type UnfurlRaw = | {unfurlType: UnfurlType.GENERIC; GENERIC: UnfurlGenericRaw} | {unfurlType: UnfurlType.YOUTUBE; YOUTUBE: UnfurlYoutubeRaw} | {unfurlType: UnfurlType.GIPHY; GIPHY: UnfurlGiphyRaw} | {unfurlType: UnfurlType.MAPS; MAPS: UnfurlMapsRaw} | {unfurlType: Exclude<UnfurlType, UnfurlType.GENERIC | UnfurlType.YOUTUBE | UnfurlType.GIPHY | UnfurlType.MAPS>} export type UnfurlGenericDisplay = { title: string url: string siteName: string favicon?: UnfurlImageDisplay media?: UnfurlImageDisplay publishTime?: number description?: string mapInfo?: UnfurlGenericMapInfo } export type UIInboxLayout = { totalSmallTeams: number smallTeams: UIInboxSmallTeamRow[] | null bigTeams: UIInboxBigTeamRow[] | null reselectInfo?: UIInboxReselectInfo widgetList: UIInboxSmallTeamRow[] | null } export type UIReactionMap = { reactions: {[key: string]: UIReactionDesc} } export type UICoinFlipStatus = { gameId: FlipGameIDStr phase: UICoinFlipPhase progressText: string resultText: string commitmentVisualization: string revealVisualization: string participants: UICoinFlipParticipant[] | null errorInfo?: UICoinFlipError resultInfo?: UICoinFlipResult } export type HarvestedEmoji = { alias: string isBig: boolean isCrossTeam: boolean source: EmojiRemoteSource } export type Emoji = { alias: string isBig: boolean isReacji: boolean isCrossTeam: boolean isAlias: boolean source: EmojiLoadSource noAnimSource: EmojiLoadSource remoteSource: EmojiRemoteSource creationInfo?: EmojiCreationInfo teamname?: string } export type EmojiStorage = { mapping: {[key: string]: EmojiRemoteSource} } export type MessageSystem = | {systemType: MessageSystemType.ADDEDTOTEAM; ADDEDTOTEAM: MessageSystemAddedToTeam} | {systemType: MessageSystemType.INVITEADDEDTOTEAM; INVITEADDEDTOTEAM: MessageSystemInviteAddedToTeam} | {systemType: MessageSystemType.COMPLEXTEAM; COMPLEXTEAM: MessageSystemComplexTeam} | {systemType: MessageSystemType.CREATETEAM; CREATETEAM: MessageSystemCreateTeam} | {systemType: MessageSystemType.GITPUSH; GITPUSH: MessageSystemGitPush} | {systemType: MessageSystemType.CHANGEAVATAR; CHANGEAVATAR: MessageSystemChangeAvatar} | {systemType: MessageSystemType.CHANGERETENTION; CHANGERETENTION: MessageSystemChangeRetention} | {systemType: MessageSystemType.BULKADDTOCONV; BULKADDTOCONV: MessageSystemBulkAddToConv} | {systemType: MessageSystemType.SBSRESOLVE; SBSRESOLVE: MessageSystemSbsResolve} | {systemType: MessageSystemType.NEWCHANNEL; NEWCHANNEL: MessageSystemNewChannel} | { systemType: Exclude< MessageSystemType, | MessageSystemType.ADDEDTOTEAM | MessageSystemType.INVITEADDEDTOTEAM | MessageSystemType.COMPLEXTEAM | MessageSystemType.CREATETEAM | MessageSystemType.GITPUSH | MessageSystemType.CHANGEAVATAR | MessageSystemType.CHANGERETENTION | MessageSystemType.BULKADDTOCONV | MessageSystemType.SBSRESOLVE | MessageSystemType.NEWCHANNEL > } export type MessageAttachmentUploaded = { messageId: MessageID object: Asset previews: Asset[] | null metadata: Buffer } export type HeaderPlaintext = | {version: HeaderPlaintextVersion.V1; V1: HeaderPlaintextV1} | {version: HeaderPlaintextVersion.V2; V2: HeaderPlaintextUnsupported} | {version: HeaderPlaintextVersion.V3; V3: HeaderPlaintextUnsupported} | {version: HeaderPlaintextVersion.V4; V4: HeaderPlaintextUnsupported} | {version: HeaderPlaintextVersion.V5; V5: HeaderPlaintextUnsupported} | {version: HeaderPlaintextVersion.V6; V6: HeaderPlaintextUnsupported} | {version: HeaderPlaintextVersion.V7; V7: HeaderPlaintextUnsupported} | {version: HeaderPlaintextVersion.V8; V8: HeaderPlaintextUnsupported} | {version: HeaderPlaintextVersion.V9; V9: HeaderPlaintextUnsupported} | {version: HeaderPlaintextVersion.V10; V10: HeaderPlaintextUnsupported} | { version: Exclude< HeaderPlaintextVersion, | HeaderPlaintextVersion.V1 | HeaderPlaintextVersion.V2 | HeaderPlaintextVersion.V3 | HeaderPlaintextVersion.V4 | HeaderPlaintextVersion.V5 | HeaderPlaintextVersion.V6 | HeaderPlaintextVersion.V7 | HeaderPlaintextVersion.V8 | HeaderPlaintextVersion.V9 | HeaderPlaintextVersion.V10 > } export type PostFileAttachmentArg = { conversationId: ConversationID tlfName: string visibility: keybase1.TLFVisibility filename: string title: string metadata: Buffer identifyBehavior: keybase1.TLFIdentifyBehavior callerPreview?: MakePreviewRes outboxId?: OutboxID ephemeralLifetime?: gregor1.DurationSec } export type MessageBoxed = { version: MessageBoxedVersion serverHeader?: MessageServerHeader clientHeader: MessageClientHeader headerCiphertext: SealedData bodyCiphertext: EncryptedData verifyKey: Buffer keyGeneration: number } export type BotInfoResponse = | {typ: BotInfoResponseTyp.UPTODATE} | {typ: BotInfoResponseTyp.INFO; INFO: BotInfo} | {typ: Exclude<BotInfoResponseTyp, BotInfoResponseTyp.UPTODATE | BotInfoResponseTyp.INFO>} export type UnfurlGeneric = { title: string url: string siteName: string favicon?: Asset image?: Asset publishTime?: number description?: string mapInfo?: UnfurlGenericMapInfo } export type UnfurlGiphy = { favicon?: Asset image?: Asset video?: Asset } export type UnfurlDisplay = | {unfurlType: UnfurlType.GENERIC; GENERIC: UnfurlGenericDisplay} | {unfurlType: UnfurlType.YOUTUBE; YOUTUBE: UnfurlYoutubeDisplay} | {unfurlType: UnfurlType.GIPHY; GIPHY: UnfurlGiphyDisplay} | {unfurlType: Exclude<UnfurlType, UnfurlType.GENERIC | UnfurlType.YOUTUBE | UnfurlType.GIPHY>} export type UIMessageUnfurlInfo = { unfurlMessageId: MessageID url: string unfurl: UnfurlDisplay isCollapsed: boolean } export type UITextDecoration = | {typ: UITextDecorationTyp.PAYMENT; PAYMENT: TextPayment} | {typ: UITextDecorationTyp.ATMENTION; ATMENTION: string} | {typ: UITextDecorationTyp.CHANNELNAMEMENTION; CHANNELNAMEMENTION: UIChannelNameMention} | {typ: UITextDecorationTyp.MAYBEMENTION; MAYBEMENTION: MaybeMention} | {typ: UITextDecorationTyp.LINK; LINK: UILinkDecoration} | {typ: UITextDecorationTyp.MAILTO; MAILTO: UILinkDecoration} | {typ: UITextDecorationTyp.KBFSPATH; KBFSPATH: KBFSPath} | {typ: UITextDecorationTyp.EMOJI; EMOJI: Emoji} | { typ: Exclude< UITextDecorationTyp, | UITextDecorationTyp.PAYMENT | UITextDecorationTyp.ATMENTION | UITextDecorationTyp.CHANNELNAMEMENTION | UITextDecorationTyp.MAYBEMENTION | UITextDecorationTyp.LINK | UITextDecorationTyp.MAILTO | UITextDecorationTyp.KBFSPATH | UITextDecorationTyp.EMOJI > } export type EmojiGroup = { name: string emojis: Emoji[] | null } export type NewMessagePayload = { action: string convId: ConversationID message: MessageBoxed inboxVers: InboxVers topicType: TopicType unreadUpdate?: UnreadUpdate untrustedTeamRole: keybase1.TeamRole maxMsgs: MessageSummary[] | null } export type MessageText = { body: string payments: TextPayment[] | null replyTo?: MessageID replyToUid?: gregor1.UID userMentions: KnownUserMention[] | null teamMentions: KnownTeamMention[] | null liveLocation?: LiveLocation emojis: {[key: string]: HarvestedEmoji} } export type MessageEdit = { messageId: MessageID body: string userMentions: KnownUserMention[] | null teamMentions: KnownTeamMention[] | null emojis: {[key: string]: HarvestedEmoji} } export type MessageHeadline = { headline: string emojis: {[key: string]: HarvestedEmoji} } export type MessageAttachment = { object: Asset preview?: Asset previews: Asset[] | null metadata: Buffer uploaded: boolean userMentions: KnownUserMention[] | null teamMentions: KnownTeamMention[] | null emojis: {[key: string]: HarvestedEmoji} } export type MessageReaction = { m: MessageID b: string t?: gregor1.UID e: {[key: string]: HarvestedEmoji} } export type LoadFlipRes = { status: UICoinFlipStatus rateLimits: RateLimit[] | null identifyFailures: keybase1.TLFIdentifyFailure[] | null } export type ReactionUpdate = { reactions: UIReactionMap targetMsgId: MessageID } export type ThreadViewBoxed = { messages: MessageBoxed[] | null pagination?: Pagination } export type GetMessagesRemoteRes = { msgs: MessageBoxed[] | null membersType: ConversationMembersType visibility: keybase1.TLFVisibility rateLimit?: RateLimit } export type GetBotInfoRes = { response: BotInfoResponse rateLimit?: RateLimit } export type Unfurl = | {unfurlType: UnfurlType.GENERIC; GENERIC: UnfurlGeneric} | {unfurlType: UnfurlType.YOUTUBE; YOUTUBE: UnfurlYoutube} | {unfurlType: UnfurlType.GIPHY; GIPHY: UnfurlGiphy} | {unfurlType: Exclude<UnfurlType, UnfurlType.GENERIC | UnfurlType.YOUTUBE | UnfurlType.GIPHY>} export type UserEmojis = { emojis: EmojiGroup[] | null } export type ReactionUpdateNotif = { convId: ConversationID userReacjis: keybase1.UserReacjis reactionUpdates: ReactionUpdate[] | null } export type GetThreadRemoteRes = { thread: ThreadViewBoxed membersType: ConversationMembersType visibility: keybase1.TLFVisibility rateLimit?: RateLimit } export type UnfurlResult = { unfurl: Unfurl url: string } export type MessageUnfurl = { unfurl: UnfurlResult messageId: MessageID } export type UserEmojiRes = { emojis: UserEmojis rateLimit?: RateLimit } export type MsgContent = { type: string text?: MsgTextContent attachment?: MessageAttachment edit?: MessageEdit reaction?: MessageReaction delete?: MessageDelete metadata?: MessageConversationMetadata headline?: MessageHeadline attachmentUploaded?: MessageAttachmentUploaded system?: MessageSystem sendPayment?: MessageSendPayment requestPayment?: MessageRequestPayment unfurl?: MessageUnfurl flip?: MsgFlipContent } export type MessageBody = | {messageType: MessageType.TEXT; TEXT: MessageText} | {messageType: MessageType.ATTACHMENT; ATTACHMENT: MessageAttachment} | {messageType: MessageType.EDIT; EDIT: MessageEdit} | {messageType: MessageType.DELETE; DELETE: MessageDelete} | {messageType: MessageType.METADATA; METADATA: MessageConversationMetadata} | {messageType: MessageType.HEADLINE; HEADLINE: MessageHeadline} | {messageType: MessageType.ATTACHMENTUPLOADED; ATTACHMENTUPLOADED: MessageAttachmentUploaded} | {messageType: MessageType.JOIN; JOIN: MessageJoin} | {messageType: MessageType.LEAVE; LEAVE: MessageLeave} | {messageType: MessageType.SYSTEM; SYSTEM: MessageSystem} | {messageType: MessageType.DELETEHISTORY; DELETEHISTORY: MessageDeleteHistory} | {messageType: MessageType.REACTION; REACTION: MessageReaction} | {messageType: MessageType.SENDPAYMENT; SENDPAYMENT: MessageSendPayment} | {messageType: MessageType.REQUESTPAYMENT; REQUESTPAYMENT: MessageRequestPayment} | {messageType: MessageType.UNFURL; UNFURL: MessageUnfurl} | {messageType: MessageType.FLIP; FLIP: MessageFlip} | {messageType: MessageType.PIN; PIN: MessagePin} | { messageType: Exclude< MessageType, | MessageType.TEXT | MessageType.ATTACHMENT | MessageType.EDIT | MessageType.DELETE | MessageType.METADATA | MessageType.HEADLINE | MessageType.ATTACHMENTUPLOADED | MessageType.JOIN | MessageType.LEAVE | MessageType.SYSTEM | MessageType.DELETEHISTORY | MessageType.REACTION | MessageType.SENDPAYMENT | MessageType.REQUESTPAYMENT | MessageType.UNFURL | MessageType.FLIP | MessageType.PIN > } export type MsgSummary = { id: MessageID conversationId: ConvIDStr channel: ChatChannel sender: MsgSender sentAt: number sentAtMs: number content: MsgContent prev: MessagePreviousPointer[] | null unread: boolean revokedDevice?: boolean offline?: boolean kbfsEncrypted?: boolean isEphemeral?: boolean isEphemeralExpired?: boolean eTime?: gregor1.Time reactions?: UIReactionMap hasPairwiseMacs?: boolean atMentionUsernames?: string[] | null channelMention?: string channelNameMentions?: UIChannelNameMention[] | null botInfo?: MsgBotInfo } export type BodyPlaintextV1 = { messageBody: MessageBody } export type BodyPlaintextV2 = { messageBody: MessageBody mi: BodyPlaintextMetaInfo } export type MessagePlaintext = { clientHeader: MessageClientHeader messageBody: MessageBody supersedesOutboxId?: OutboxID emojis: HarvestedEmoji[] | null } export type Message = { msg?: MsgSummary error?: string } export type MsgNotification = { type: string source: string msg?: MsgSummary error?: string pagination?: UIPagination } export type BodyPlaintext = | {version: BodyPlaintextVersion.V1; V1: BodyPlaintextV1} | {version: BodyPlaintextVersion.V2; V2: BodyPlaintextV2} | {version: BodyPlaintextVersion.V3; V3: BodyPlaintextUnsupported} | {version: BodyPlaintextVersion.V4; V4: BodyPlaintextUnsupported} | {version: BodyPlaintextVersion.V5; V5: BodyPlaintextUnsupported} | {version: BodyPlaintextVersion.V6; V6: BodyPlaintextUnsupported} | {version: BodyPlaintextVersion.V7; V7: BodyPlaintextUnsupported} | {version: BodyPlaintextVersion.V8; V8: BodyPlaintextUnsupported} | {version: BodyPlaintextVersion.V9; V9: BodyPlaintextUnsupported} | {version: BodyPlaintextVersion.V10; V10: BodyPlaintextUnsupported} | { version: Exclude< BodyPlaintextVersion, | BodyPlaintextVersion.V1 | BodyPlaintextVersion.V2 | BodyPlaintextVersion.V3 | BodyPlaintextVersion.V4 | BodyPlaintextVersion.V5 | BodyPlaintextVersion.V6 | BodyPlaintextVersion.V7 | BodyPlaintextVersion.V8 | BodyPlaintextVersion.V9 | BodyPlaintextVersion.V10 > } export type Thread = { messages: Message[] | null pagination?: Pagination offline?: boolean identifyFailures?: keybase1.TLFIdentifyFailure[] | null ratelimits?: RateLimitRes[] | null }
the_stack
import { Rule, RuleTester } from 'eslint' import { rule, name, Options } from 'rules/interface' import { SortingOrder } from 'common/options' import { typescript } from '../helpers/configs' import { InvalidTestCase, processInvalidTestCase, processValidTestCase, ValidTestCase, } from '../helpers/util' const valid: readonly ValidTestCase<Options>[] = [ /** * default, asc, caseSensitive */ { code: 'interface U {_:T; a:T; b:T;}', optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false, requiredFirst: false }], ], }, { code: 'interface U {a:T; b:T; c:T;}', optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false, requiredFirst: false }], ], }, { code: 'interface U {a:T; b:T; b_:T;}', optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false, requiredFirst: false }], ], }, { code: 'interface U {C:T; b_:T; c:T;}', optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false, requiredFirst: false }], ], }, { code: 'interface U {$:T; A:T; _:T; a:T;}', optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false, requiredFirst: false }], ], }, { code: "interface U {1:T; '11':T; 2:T; A:T;}", optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false, requiredFirst: false }], ], }, { code: "interface U {'#':T; 'Z':T; À:T; è:T;}", optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false, requiredFirst: false }], ], }, /** * computed */ { code: 'interface U {a:T; ["ab"]:T; b:T; c:T;}', optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false, requiredFirst: false }], ], }, /** * nested */ { code: 'interface U {a:T; b:{x:T; y:T;}; c:T;}', optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false, requiredFirst: false }], ], }, { code: 'interface U {a:T; b:{x:T; y:T; z:{i:T; j:T;};}; c:T;}', optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false, requiredFirst: false }], ], }, { code: 'type U = {a:T; b:{x:T; y:T;}; c:T;}', optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false, requiredFirst: false }], ], }, { code: 'type U = {a:T; b:{x:T; y:T; z:{i:T; j:T;};}; c:T;}', optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false, requiredFirst: false }], ], }, /** * asc, insensitive */ { code: 'interface U {_:T; a:T; b:T;}', optionsSet: [[SortingOrder.Ascending, { caseSensitive: false }]], }, { code: 'interface U {a:T; b:T; c:T;}', optionsSet: [[SortingOrder.Ascending, { caseSensitive: false }]], }, { code: 'interface U {a:T; b:T; b_:T;}', optionsSet: [[SortingOrder.Ascending, { caseSensitive: false }]], }, { code: 'interface U {b_:T; C:T; c:T;}', optionsSet: [[SortingOrder.Ascending, { caseSensitive: false }]], }, { code: 'interface U {b_:T; c:T; C:T;}', optionsSet: [[SortingOrder.Ascending, { caseSensitive: false }]], }, { code: 'interface U {$:T; _:T; A:T; a:T;}', optionsSet: [[SortingOrder.Ascending, { caseSensitive: false }]], }, { code: "interface U {1:T; '11':T; 2:T; A:T;}", optionsSet: [[SortingOrder.Ascending, { caseSensitive: false }]], }, { code: "interface U {'#':T; 'Z':T; À:T; è:T;}", optionsSet: [[SortingOrder.Ascending, { natural: true }]], }, /** * asc, natural, insensitive */ { code: 'interface U {_:T; a:T; b:T;}', optionsSet: [[SortingOrder.Ascending, { natural: true, caseSensitive: false }]], }, { code: 'interface U {a:T; b:T; c:T;}', optionsSet: [[SortingOrder.Ascending, { natural: true, caseSensitive: false }]], }, { code: 'interface U {a:T; b:T; b_:T;}', optionsSet: [[SortingOrder.Ascending, { natural: true, caseSensitive: false }]], }, { code: 'interface U {b_:T; C:T; c:T;}', optionsSet: [[SortingOrder.Ascending, { natural: true, caseSensitive: false }]], }, { code: 'interface U {b_:T; c:T; C:T;}', optionsSet: [[SortingOrder.Ascending, { natural: true, caseSensitive: false }]], }, { code: 'interface U {$:T; _:T; A:T; a:T;}', optionsSet: [[SortingOrder.Ascending, { natural: true, caseSensitive: false }]], }, { code: "interface U {1:T; 2:T; '11':T; A:T;}", optionsSet: [[SortingOrder.Ascending, { natural: true, caseSensitive: false }]], }, { code: "interface U {'#':T; 'Z':T; À:T; è:T;}", optionsSet: [[SortingOrder.Ascending, { natural: true, caseSensitive: false }]], }, /** * asc, natural, insensitive, required */ { code: 'interface U {_:T; b:T; a?:T;}', optionsSet: [ [SortingOrder.Ascending, { natural: true, caseSensitive: false, requiredFirst: true }], ], }, { code: 'interface U {a:T; c:T; b?:T;}', optionsSet: [ [SortingOrder.Ascending, { natural: true, caseSensitive: false, requiredFirst: true }], ], }, { code: 'interface U {b:T; b_:T; a?:T;}', optionsSet: [ [SortingOrder.Ascending, { natural: true, caseSensitive: false, requiredFirst: true }], ], }, { code: 'interface U {C:T; c:T; b_?:T;}', optionsSet: [ [SortingOrder.Ascending, { natural: true, caseSensitive: false, requiredFirst: true }], ], }, { code: 'interface U {c:T; C:T; b_?:T;}', optionsSet: [ [SortingOrder.Ascending, { natural: true, caseSensitive: false, requiredFirst: true }], ], }, { code: 'interface U {$:T; _:T; A?:T; a?:T;}', optionsSet: [ [SortingOrder.Ascending, { natural: true, caseSensitive: false, requiredFirst: true }], ], }, { code: "interface U {1:T; '11':T; A:T; 2?:T;}", optionsSet: [ [SortingOrder.Ascending, { natural: true, caseSensitive: false, requiredFirst: true }], ], }, { code: "interface U {'Z':T; À:T; è:T; '#'?:T;}", optionsSet: [ [SortingOrder.Ascending, { natural: true, caseSensitive: false, requiredFirst: true }], ], }, /** * asc, required */ { code: 'interface U {_:T; b:T; a?:T;}', optionsSet: [[SortingOrder.Ascending, { requiredFirst: true }]], }, { code: 'interface U {a:T; c:T; b?:T;}', optionsSet: [[SortingOrder.Ascending, { requiredFirst: true }]], }, { code: 'interface U {b:T; b_:T; a?:T;}', optionsSet: [[SortingOrder.Ascending, { requiredFirst: true }]], }, { code: 'interface U {C:T; c:T; b_?:T;}', optionsSet: [[SortingOrder.Ascending, { requiredFirst: true }]], }, { code: 'interface U {1:T; 11:T; 9:T; 111?:T;}', optionsSet: [[SortingOrder.Ascending, { requiredFirst: true }]], }, { code: 'interface U {$:T; _:T; A?:T; a?:T;}', optionsSet: [[SortingOrder.Ascending, { requiredFirst: true }]], }, { code: "interface U {10:T; '11':T; 1?:T; 12?:T; 2?:T;}", optionsSet: [[SortingOrder.Ascending, { requiredFirst: true }]], }, { code: "interface U {'Z':T; À:T; è:T; '#'?:T;}", optionsSet: [[SortingOrder.Ascending, { requiredFirst: true }]], }, /** * asc, natural, insensitive, not-required */ { code: 'interface U {_:T; a?:T; b:T;}', optionsSet: [ [SortingOrder.Ascending, { natural: true, caseSensitive: false, requiredFirst: false }], ], }, { code: 'interface U {a:T; b?:T; c:T;}', optionsSet: [ [SortingOrder.Ascending, { natural: true, caseSensitive: false, requiredFirst: false }], ], }, { code: 'interface U {a?:T; b:T; b_:T;}', optionsSet: [ [SortingOrder.Ascending, { natural: true, caseSensitive: false, requiredFirst: false }], ], }, { code: 'interface U {b_?:T; C:T; c:T;}', optionsSet: [ [SortingOrder.Ascending, { natural: true, caseSensitive: false, requiredFirst: false }], ], }, { code: 'interface U {b_?:T; c:T; C:T;}', optionsSet: [ [SortingOrder.Ascending, { natural: true, caseSensitive: false, requiredFirst: false }], ], }, { code: 'interface U {$:T; _:T; A?:T; a?:T;}', optionsSet: [ [SortingOrder.Ascending, { natural: true, caseSensitive: false, requiredFirst: false }], ], }, { code: "interface U {1:T; 2?:T; '11':T; A:T;}", optionsSet: [ [SortingOrder.Ascending, { natural: true, caseSensitive: false, requiredFirst: false }], ], }, { code: "interface U {'#'?:T; 'Z':T; À:T; è:T;}", optionsSet: [ [SortingOrder.Ascending, { natural: true, caseSensitive: false, requiredFirst: false }], ], }, /** * desc */ { code: 'interface U {b:T; a:T; _:T;}', optionsSet: [ [SortingOrder.Descending], [SortingOrder.Descending, { caseSensitive: true }], [SortingOrder.Descending, { natural: false }], [SortingOrder.Descending, { caseSensitive: true, natural: false }], ], }, { code: 'interface U {c:T; b:T; a:T;}', optionsSet: [ [SortingOrder.Descending], [SortingOrder.Descending, { caseSensitive: true }], [SortingOrder.Descending, { natural: false }], [SortingOrder.Descending, { caseSensitive: true, natural: false }], ], }, { code: 'interface U {b_:T; b:T; a:T;}', optionsSet: [ [SortingOrder.Descending], [SortingOrder.Descending, { caseSensitive: true }], [SortingOrder.Descending, { natural: false }], [SortingOrder.Descending, { caseSensitive: true, natural: false }], ], }, { code: 'interface U {c:T; b_:T; C:T;}', optionsSet: [ [SortingOrder.Descending], [SortingOrder.Descending, { caseSensitive: true }], [SortingOrder.Descending, { natural: false }], [SortingOrder.Descending, { caseSensitive: true, natural: false }], ], }, { code: 'interface U {a:T; _:T; A:T; $:T;}', optionsSet: [ [SortingOrder.Descending], [SortingOrder.Descending, { caseSensitive: true }], [SortingOrder.Descending, { natural: false }], [SortingOrder.Descending, { caseSensitive: true, natural: false }], ], }, { code: "interface U {A:T; 2:T; '11':T; 1:T;}", optionsSet: [ [SortingOrder.Descending], [SortingOrder.Descending, { caseSensitive: true }], [SortingOrder.Descending, { natural: false }], [SortingOrder.Descending, { caseSensitive: true, natural: false }], ], }, { code: "interface U {è:T; À:T; 'Z':T; '#':T;}", optionsSet: [ [SortingOrder.Descending], [SortingOrder.Descending, { caseSensitive: true }], [SortingOrder.Descending, { natural: false }], [SortingOrder.Descending, { caseSensitive: true, natural: false }], ], }, /** * desc, insensitive */ { code: 'interface U {b:T; a:T; _:T;}', optionsSet: [ [SortingOrder.Descending, { caseSensitive: false }], [SortingOrder.Descending, { caseSensitive: false, natural: false }], ], }, { code: 'interface U {c:T; b:T; a:T;}', optionsSet: [ [SortingOrder.Descending, { caseSensitive: false }], [SortingOrder.Descending, { caseSensitive: false, natural: false }], ], }, { code: 'interface U {b_:T; b:T; a:T;}', optionsSet: [ [SortingOrder.Descending, { caseSensitive: false }], [SortingOrder.Descending, { caseSensitive: false, natural: false }], ], }, { code: 'interface U {c:T; C:T; b_:T;}', optionsSet: [ [SortingOrder.Descending, { caseSensitive: false }], [SortingOrder.Descending, { caseSensitive: false, natural: false }], ], }, { code: 'interface U {C:T; c:T; b_:T;}', optionsSet: [ [SortingOrder.Descending, { caseSensitive: false }], [SortingOrder.Descending, { caseSensitive: false, natural: false }], ], }, { code: 'interface U {a:T; A:T; _:T; $:T;}', optionsSet: [ [SortingOrder.Descending, { caseSensitive: false }], [SortingOrder.Descending, { caseSensitive: false, natural: false }], ], }, { code: "interface U {A:T; 2:T; '11':T; 1:T;}", optionsSet: [ [SortingOrder.Descending, { caseSensitive: false }], [SortingOrder.Descending, { caseSensitive: false, natural: false }], ], }, { code: "interface U {è:T; À:T; 'Z':T; '#':T;}", optionsSet: [ [SortingOrder.Descending, { caseSensitive: false }], [SortingOrder.Descending, { caseSensitive: false, natural: false }], ], }, /** * desc, natural */ { code: 'interface U {b:T; a:T; _:T;}', optionsSet: [ [SortingOrder.Descending, { natural: true }], [SortingOrder.Descending, { natural: true, caseSensitive: true }], ], }, { code: 'interface U {c:T; b:T; a:T;}', optionsSet: [ [SortingOrder.Descending, { natural: true }], [SortingOrder.Descending, { natural: true, caseSensitive: true }], ], }, { code: 'interface U {b_:T; b:T; a:T;}', optionsSet: [ [SortingOrder.Descending, { natural: true }], [SortingOrder.Descending, { natural: true, caseSensitive: true }], ], }, { code: 'interface U {c:T; b_:T; C:T;}', optionsSet: [ [SortingOrder.Descending, { natural: true }], [SortingOrder.Descending, { natural: true, caseSensitive: true }], ], }, { code: 'interface U {a:T; A:T; _:T; $:T;}', optionsSet: [ [SortingOrder.Descending, { natural: true }], [SortingOrder.Descending, { natural: true, caseSensitive: true }], ], }, { code: "interface U {A:T; '11':T; 2:T; 1:T;}", optionsSet: [ [SortingOrder.Descending, { natural: true }], [SortingOrder.Descending, { natural: true, caseSensitive: true }], ], }, { code: "interface U {è:T; À:T; 'Z':T; '#':T;}", optionsSet: [ [SortingOrder.Descending, { natural: true }], [SortingOrder.Descending, { natural: true, caseSensitive: true }], ], }, /** * desc, natural, insensitive */ { code: 'interface U {b:T; a:T; _:T;}', optionsSet: [[SortingOrder.Descending, { natural: true, caseSensitive: false }]], }, { code: 'interface U {c:T; b:T; a:T;}', optionsSet: [[SortingOrder.Descending, { natural: true, caseSensitive: false }]], }, { code: 'interface U {b_:T; b:T; a:T;}', optionsSet: [[SortingOrder.Descending, { natural: true, caseSensitive: false }]], }, { code: 'interface U {c:T; C:T; b_:T;}', optionsSet: [[SortingOrder.Descending, { natural: true, caseSensitive: false }]], }, { code: 'interface U {C:T; c:T; b_:T;}', optionsSet: [[SortingOrder.Descending, { natural: true, caseSensitive: false }]], }, { code: 'interface U {a:T; A:T; _:T; $:T;}', optionsSet: [[SortingOrder.Descending, { natural: true, caseSensitive: false }]], }, { code: "interface U {A:T; '11':T; 2:T; 1:T;}", optionsSet: [[SortingOrder.Descending, { natural: true, caseSensitive: false }]], }, { code: "interface U {è:T; À:T; 'Z':T; '#':T;}", optionsSet: [[SortingOrder.Descending, { natural: true, caseSensitive: false }]], }, /** * desc, natural, insensitive, required */ { code: 'interface U {b:T; _:T; a?:T;}', optionsSet: [ [SortingOrder.Descending, { natural: true, caseSensitive: false, requiredFirst: true }], ], }, { code: 'interface U {c:T; a:T; b?:T;}', optionsSet: [ [SortingOrder.Descending, { natural: true, caseSensitive: false, requiredFirst: true }], ], }, { code: 'interface U {b_:T; b:T; a?:T;}', optionsSet: [ [SortingOrder.Descending, { natural: true, caseSensitive: false, requiredFirst: true }], ], }, { code: 'interface U {c:T; C:T; b_?:T;}', optionsSet: [ [SortingOrder.Descending, { natural: true, caseSensitive: false, requiredFirst: true }], ], }, { code: 'interface U {C:T; c:T; b_?:T;}', optionsSet: [ [SortingOrder.Descending, { natural: true, caseSensitive: false, requiredFirst: true }], ], }, { code: 'interface U {_:T; $:T; a?:T; A?:T;}', optionsSet: [ [SortingOrder.Descending, { natural: true, caseSensitive: false, requiredFirst: true }], ], }, { code: "interface U { A:T; '11':T; 1:T; 2?:T;}", optionsSet: [ [SortingOrder.Descending, { natural: true, caseSensitive: false, requiredFirst: true }], ], }, { code: "interface U {è:T; 'Z':T; À?:T; '#'?:T;}", optionsSet: [ [SortingOrder.Descending, { natural: true, caseSensitive: false, requiredFirst: true }], ], }, /** * desc, required */ { code: 'interface U {b:T; _:T; a?:T;}', optionsSet: [[SortingOrder.Descending, { requiredFirst: true }]], }, { code: 'interface U {c:T; a:T; b?:T;}', optionsSet: [[SortingOrder.Descending, { requiredFirst: true }]], }, { code: 'interface U {b_:T; b:T; a?:T;}', optionsSet: [[SortingOrder.Descending, { requiredFirst: true }]], }, { code: 'interface U {c:T; C:T; b_?:T;}', optionsSet: [[SortingOrder.Descending, { requiredFirst: true }]], }, { code: 'interface U {9:T; 11:T; 1:T; 111?:T;}', optionsSet: [[SortingOrder.Descending, { requiredFirst: true }]], }, { code: 'interface U {_:T; $:T; a?:T; A?:T;}', optionsSet: [[SortingOrder.Descending, { requiredFirst: true }]], }, { code: "interface U {'11':T; 10:T; 2?:T; 12?:T; 1?:T;}", optionsSet: [[SortingOrder.Descending, { requiredFirst: true }]], }, { code: "interface U {è:T; À:T; 'Z':T; '#'?:T;}", optionsSet: [[SortingOrder.Descending, { requiredFirst: true }]], }, /** * desc, natural, insensitive, not-required */ { code: 'interface U {b:T; a?:T; _:T;}', optionsSet: [ [SortingOrder.Descending, { natural: true, caseSensitive: false, requiredFirst: false }], ], }, { code: 'interface U {c:T; b?:T; a:T;}', optionsSet: [ [SortingOrder.Descending, { natural: true, caseSensitive: false, requiredFirst: false }], ], }, { code: 'interface U {b_:T; b:T; a?:T;}', optionsSet: [ [SortingOrder.Descending, { natural: true, caseSensitive: false, requiredFirst: false }], ], }, { code: 'interface U {c:T; C:T; b_?:T;}', optionsSet: [ [SortingOrder.Descending, { natural: true, caseSensitive: false, requiredFirst: false }], ], }, { code: 'interface U {C:T; c:T; b_?:T;}', optionsSet: [ [SortingOrder.Descending, { natural: true, caseSensitive: false, requiredFirst: false }], ], }, { code: 'interface U {a?:T; A?:T; _:T; $:T;}', optionsSet: [ [SortingOrder.Descending, { natural: true, caseSensitive: false, requiredFirst: false }], ], }, { code: "interface U {A:T; '11':T; 2?:T; 1:T;}", optionsSet: [ [SortingOrder.Descending, { natural: true, caseSensitive: false, requiredFirst: false }], ], }, { code: "interface U {è:T; À:T; 'Z':T; '#'?:T;}", optionsSet: [ [SortingOrder.Descending, { natural: true, caseSensitive: false, requiredFirst: false }], ], }, /** * index signatures */ { code: `interface U<T> { [nkey: number]: T; [skey: string]: T; $: T; A: T; _: T; a: T; }`, optionsSet: [[SortingOrder.Ascending]], }, { code: `interface U<T> { a: T; _: T; A: T; $: T; [skey: string]: T; [nkey: number]: T; }`, optionsSet: [[SortingOrder.Descending]], }, ] const invalid: readonly InvalidTestCase<Options>[] = [ /** * default (asc) */ { code: 'interface U {a:T; _:T; b:T;}', output: 'interface U {_:T; a:T; b:T;}', errors: ["Expected interface keys to be in ascending order. '_' should be before 'a'."], optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false, requiredFirst: false }], ], }, { code: 'interface U {a:T; c:T; b:T;}', output: 'interface U {a:T; b:T; c:T;}', errors: ["Expected interface keys to be in ascending order. 'b' should be before 'c'."], optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false, requiredFirst: false }], ], }, { code: 'interface U {b_:T; a:T; b:T;}', output: 'interface U {a:T; b_:T; b:T;}', errors: ["Expected interface keys to be in ascending order. 'a' should be before 'b_'."], optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false, requiredFirst: false }], ], }, { code: 'interface U {b_:T; c:T; C:T;}', output: 'interface U {C:T; c:T; b_:T;}', errors: ["Expected interface keys to be in ascending order. 'C' should be before 'c'."], optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false, requiredFirst: false }], ], }, { code: 'interface U {$:T; _:T; A:T; a:T;}', output: 'interface U {$:T; A:T; _:T; a:T;}', errors: ["Expected interface keys to be in ascending order. 'A' should be before '_'."], optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false, requiredFirst: false }], ], }, { code: "interface U {1:T; 2:T; A:T; '11':T;}", output: "interface U {1:T; '11':T; A:T; 2:T;}", errors: ["Expected interface keys to be in ascending order. '11' should be before 'A'."], optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false, requiredFirst: false }], ], }, { code: "interface U {'#':T; À:T; 'Z':T; è:T;}", output: "interface U {'#':T; 'Z':T; À:T; è:T;}", errors: ["Expected interface keys to be in ascending order. 'Z' should be before 'À'."], optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false, requiredFirst: false }], ], }, /** * methods */ { code: "interface U {1:T; 2:T; A():T; '11':T;}", output: "interface U {1:T; '11':T; A():T; 2:T;}", errors: ["Expected interface keys to be in ascending order. '11' should be before 'A'."], optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false, requiredFirst: false }], ], }, { code: "interface U {'#'():T; À():T; 'Z':T; è:T;}", output: "interface U {'#'():T; 'Z':T; À():T; è:T;}", errors: ["Expected interface keys to be in ascending order. 'Z' should be before 'À'."], optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false, requiredFirst: false }], ], }, /** * not ignore simple computed properties. */ { code: 'interface U {a:T; b:T; ["a"]:T; c:T;}', output: 'interface U {a:T; ["a"]:T; b:T; c:T;}', errors: ["Expected interface keys to be in ascending order. 'a' should be before 'b'."], optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false, requiredFirst: false }], ], }, /** * nested */ { code: 'interface U {a:T; c:{y:T; x:T;}, b:T;}', output: 'interface U {a:T; b:T; c:{y:T; x:T;}}', errors: [ "Expected interface keys to be in ascending order. 'x' should be before 'y'.", "Expected interface keys to be in ascending order. 'b' should be before 'c'.", ], optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false, requiredFirst: false }], ], }, { code: 'type U = {a:T; c:{y:T; x:T;}, b:T;}', output: 'type U = {a:T; b:T; c:{y:T; x:T;}}', errors: [ "Expected interface keys to be in ascending order. 'x' should be before 'y'.", "Expected interface keys to be in ascending order. 'b' should be before 'c'.", ], optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false, requiredFirst: false }], ], }, /** * asc */ { code: 'interface U {a:T; _:T; b:T;}', output: 'interface U {_:T; a:T; b:T;}', errors: ["Expected interface keys to be in ascending order. '_' should be before 'a'."], optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false, requiredFirst: false }], ], }, { code: 'interface U {a:T; c:T; b:T;}', output: 'interface U {a:T; b:T; c:T;}', errors: ["Expected interface keys to be in ascending order. 'b' should be before 'c'."], optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false, requiredFirst: false }], ], }, { code: 'interface U {b_:T; a:T; b:T;}', output: 'interface U {a:T; b_:T; b:T;}', errors: ["Expected interface keys to be in ascending order. 'a' should be before 'b_'."], optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false, requiredFirst: false }], ], }, { code: 'interface U {b_:T; c:T; C:T;}', output: 'interface U {C:T; c:T; b_:T;}', errors: ["Expected interface keys to be in ascending order. 'C' should be before 'c'."], optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false, requiredFirst: false }], ], }, { code: 'interface U {$:T; _:T; A:T; a:T;}', output: 'interface U {$:T; A:T; _:T; a:T;}', errors: ["Expected interface keys to be in ascending order. 'A' should be before '_'."], optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false, requiredFirst: false }], ], }, { code: "interface U {1:T; 2:T; A:T; '11':T;}", output: "interface U {1:T; '11':T; A:T; 2:T;}", errors: ["Expected interface keys to be in ascending order. '11' should be before 'A'."], optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false, requiredFirst: false }], ], }, { code: "interface U {'#':T; À:T; 'Z':T; è:T;}", output: "interface U {'#':T; 'Z':T; À:T; è:T;}", errors: ["Expected interface keys to be in ascending order. 'Z' should be before 'À'."], optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], ], }, /** * asc, insensitive */ { code: 'interface U {a:T; _:T; b:T;}', output: 'interface U {_:T; a:T; b:T;}', errors: [ "Expected interface keys to be in insensitive ascending order. '_' should be before 'a'.", ], optionsSet: [[SortingOrder.Ascending, { caseSensitive: false }]], }, { code: 'interface U {a:T; c:T; b:T;}', output: 'interface U {a:T; b:T; c:T;}', errors: [ "Expected interface keys to be in insensitive ascending order. 'b' should be before 'c'.", ], optionsSet: [[SortingOrder.Ascending, { caseSensitive: false }]], }, { code: 'interface U {b_:T; a:T; b:T;}', output: 'interface U {a:T; b_:T; b:T;}', errors: [ "Expected interface keys to be in insensitive ascending order. 'a' should be before 'b_'.", ], optionsSet: [[SortingOrder.Ascending, { caseSensitive: false }]], }, { code: 'interface U {$:T; A:T; _:T; a:T;}', output: 'interface U {$:T; _:T; A:T; a:T;}', errors: [ "Expected interface keys to be in insensitive ascending order. '_' should be before 'A'.", ], optionsSet: [[SortingOrder.Ascending, { caseSensitive: false }]], }, { code: "interface U {1:T; 2:T; A:T; '11':T;}", output: "interface U {1:T; '11':T; A:T; 2:T;}", errors: [ "Expected interface keys to be in insensitive ascending order. '11' should be before 'A'.", ], optionsSet: [[SortingOrder.Ascending, { caseSensitive: false }]], }, { code: "interface U {'#':T; À:T; 'Z':T; è:T;}", output: "interface U {'#':T; 'Z':T; À:T; è:T;}", errors: [ "Expected interface keys to be in insensitive ascending order. 'Z' should be before 'À'.", ], optionsSet: [[SortingOrder.Ascending, { caseSensitive: false }]], }, /** * asc, natural */ { code: 'interface U {a:T; _:T; b:T;}', output: 'interface U {_:T; a:T; b:T;}', errors: ["Expected interface keys to be in natural ascending order. '_' should be before 'a'."], optionsSet: [[SortingOrder.Ascending, { natural: true }]], }, { code: 'interface U {a:T; c:T; b:T;}', output: 'interface U {a:T; b:T; c:T;}', errors: ["Expected interface keys to be in natural ascending order. 'b' should be before 'c'."], optionsSet: [[SortingOrder.Ascending, { natural: true }]], }, { code: 'interface U {b_:T; a:T; b:T;}', output: 'interface U {a:T; b_:T; b:T;}', errors: [ "Expected interface keys to be in natural ascending order. 'a' should be before 'b_'.", ], optionsSet: [[SortingOrder.Ascending, { natural: true }]], }, { code: 'interface U {b_:T; c:T; C:T;}', output: 'interface U {C:T; c:T; b_:T;}', errors: ["Expected interface keys to be in natural ascending order. 'C' should be before 'c'."], optionsSet: [[SortingOrder.Ascending, { natural: true }]], }, { code: 'interface U {$:T; A:T; _:T; a:T;}', output: 'interface U {$:T; _:T; A:T; a:T;}', errors: ["Expected interface keys to be in natural ascending order. '_' should be before 'A'."], optionsSet: [[SortingOrder.Ascending, { natural: true }]], }, { code: "interface U {1:T; 2:T; A:T; '11':T;}", output: "interface U {1:T; 2:T; '11':T; A:T;}", errors: [ "Expected interface keys to be in natural ascending order. '11' should be before 'A'.", ], optionsSet: [[SortingOrder.Ascending, { natural: true }]], }, { code: "interface U {'#':T; À:T; 'Z':T; è:T;}", output: "interface U {'#':T; 'Z':T; À:T; è:T;}", errors: ["Expected interface keys to be in natural ascending order. 'Z' should be before 'À'."], optionsSet: [[SortingOrder.Ascending, { natural: true }]], }, /** * asc, natural, insensitive */ { code: 'interface U {a:T; _:T; b:T;}', output: 'interface U {_:T; a:T; b:T;}', errors: [ "Expected interface keys to be in natural insensitive ascending order. '_' should be before 'a'.", ], optionsSet: [[SortingOrder.Ascending, { natural: true, caseSensitive: false }]], }, { code: 'interface U {a:T; c:T; b:T;}', output: 'interface U {a:T; b:T; c:T;}', errors: [ "Expected interface keys to be in natural insensitive ascending order. 'b' should be before 'c'.", ], optionsSet: [[SortingOrder.Ascending, { natural: true, caseSensitive: false }]], }, { code: 'interface U {b_:T; a:T; b:T;}', output: 'interface U {a:T; b_:T; b:T;}', errors: [ "Expected interface keys to be in natural insensitive ascending order. 'a' should be before 'b_'.", ], optionsSet: [[SortingOrder.Ascending, { natural: true, caseSensitive: false }]], }, { code: 'interface U {$:T; A:T; _:T; a:T;}', output: 'interface U {$:T; _:T; A:T; a:T;}', errors: [ "Expected interface keys to be in natural insensitive ascending order. '_' should be before 'A'.", ], optionsSet: [[SortingOrder.Ascending, { natural: true, caseSensitive: false }]], }, { code: "interface U {1:T; '11':T; 2:T; A:T;}", output: "interface U {1:T; 2:T; '11':T; A:T;}", errors: [ "Expected interface keys to be in natural insensitive ascending order. '2' should be before '11'.", ], optionsSet: [[SortingOrder.Ascending, { natural: true, caseSensitive: false }]], }, { code: "interface U {'#':T; À:T; 'Z':T; è:T;}", output: "interface U {'#':T; 'Z':T; À:T; è:T;}", errors: [ "Expected interface keys to be in natural insensitive ascending order. 'Z' should be before 'À'.", ], optionsSet: [[SortingOrder.Ascending, { natural: true, caseSensitive: false }]], }, /** * asc, natural, insensitive, required */ { code: 'interface U {_:T; a?:T; b:T;}', output: 'interface U {_:T; b:T; a?:T;}', errors: [ "Expected interface keys to be in required first natural insensitive ascending order. 'b' should be before 'a'.", ], optionsSet: [ [SortingOrder.Ascending, { natural: true, caseSensitive: false, requiredFirst: true }], ], }, { code: 'interface U {a:T; b?:T; c:T;}', output: 'interface U {a:T; c:T; b?:T;}', errors: [ "Expected interface keys to be in required first natural insensitive ascending order. 'c' should be before 'b'.", ], optionsSet: [ [SortingOrder.Ascending, { natural: true, caseSensitive: false, requiredFirst: true }], ], }, { code: 'interface U {b:T; a?:T; b_:T;}', output: 'interface U {b:T; b_:T; a?:T;}', errors: [ "Expected interface keys to be in required first natural insensitive ascending order. 'b_' should be before 'a'.", ], optionsSet: [ [SortingOrder.Ascending, { natural: true, caseSensitive: false, requiredFirst: true }], ], }, { code: 'interface U {C:T; b_?:T; c:T;}', output: 'interface U {C:T; c:T; b_?:T;}', errors: [ "Expected interface keys to be in required first natural insensitive ascending order. 'c' should be before 'b_'.", ], optionsSet: [ [SortingOrder.Ascending, { natural: true, caseSensitive: false, requiredFirst: true }], ], }, { code: 'interface U {C:T; b_?:T; c:T;}', output: 'interface U {C:T; c:T; b_?:T;}', errors: [ "Expected interface keys to be in required first natural insensitive ascending order. 'c' should be before 'b_'.", ], optionsSet: [ [SortingOrder.Ascending, { natural: true, caseSensitive: false, requiredFirst: true }], ], }, { code: 'interface U {$:T; A?:T; _:T; a?:T;}', output: 'interface U {$:T; _:T; A?:T; a?:T;}', errors: [ "Expected interface keys to be in required first natural insensitive ascending order. '_' should be before 'A'.", ], optionsSet: [ [SortingOrder.Ascending, { natural: true, caseSensitive: false, requiredFirst: true }], ], }, { code: "interface U {1:T; '11':T; 2?:T; A:T;}", output: "interface U {1:T; '11':T; A:T; 2?:T;}", errors: [ "Expected interface keys to be in required first natural insensitive ascending order. 'A' should be before '2'.", ], optionsSet: [ [SortingOrder.Ascending, { natural: true, caseSensitive: false, requiredFirst: true }], ], }, { code: "interface U {'Z':T; À:T; '#'?:T; è:T;}", output: "interface U {'Z':T; À:T; è:T; '#'?:T;}", errors: [ "Expected interface keys to be in required first natural insensitive ascending order. 'è' should be before '#'.", ], optionsSet: [ [SortingOrder.Ascending, { natural: true, caseSensitive: false, requiredFirst: true }], ], }, /** * asc, natural, insensitive, not-required */ { code: 'interface U {_:T; b:T; a?:T;}', output: 'interface U {_:T; a?:T; b:T;}', errors: [ "Expected interface keys to be in natural insensitive ascending order. 'a' should be before 'b'.", ], optionsSet: [ [SortingOrder.Ascending, { natural: true, caseSensitive: false, requiredFirst: false }], ], }, { code: 'interface U {b?:T; a:T; c:T;}', output: 'interface U {a:T; b?:T; c:T;}', errors: [ "Expected interface keys to be in natural insensitive ascending order. 'a' should be before 'b'.", ], optionsSet: [ [SortingOrder.Ascending, { natural: true, caseSensitive: false, requiredFirst: false }], ], }, { code: 'interface U {b:T; a?:T; b_:T;}', output: 'interface U {a?:T; b:T; b_:T;}', errors: [ "Expected interface keys to be in natural insensitive ascending order. 'a' should be before 'b'.", ], optionsSet: [ [SortingOrder.Ascending, { natural: true, caseSensitive: false, requiredFirst: false }], ], }, { code: 'interface U {C:T; c:T; b_?:T;}', output: 'interface U {b_?:T; c:T; C:T;}', errors: [ "Expected interface keys to be in natural insensitive ascending order. 'b_' should be before 'c'.", ], optionsSet: [ [SortingOrder.Ascending, { natural: true, caseSensitive: false, requiredFirst: false }], ], }, { code: 'interface U {C:T; b_?:T; c:T;}', output: 'interface U {b_?:T; C:T; c:T;}', errors: [ "Expected interface keys to be in natural insensitive ascending order. 'b_' should be before 'C'.", ], optionsSet: [ [SortingOrder.Ascending, { natural: true, caseSensitive: false, requiredFirst: false }], ], }, { code: 'interface U {$:T; A?:T; _:T; a?:T;}', output: 'interface U {$:T; _:T; A?:T; a?:T;}', errors: [ "Expected interface keys to be in natural insensitive ascending order. '_' should be before 'A'.", ], optionsSet: [ [SortingOrder.Ascending, { natural: true, caseSensitive: false, requiredFirst: false }], ], }, { code: "interface U {1:T; '11':T; 2?:T; A:T;}", output: "interface U {1:T; 2?:T; '11':T; A:T;}", errors: [ "Expected interface keys to be in natural insensitive ascending order. '2' should be before '11'.", ], optionsSet: [ [SortingOrder.Ascending, { natural: true, caseSensitive: false, requiredFirst: false }], ], }, { code: "interface U {'Z':T; À:T; '#'?:T; è:T;}", output: "interface U {'#'?:T; À:T; 'Z':T; è:T;}", errors: [ "Expected interface keys to be in natural insensitive ascending order. '#' should be before 'À'.", ], optionsSet: [ [SortingOrder.Ascending, { natural: true, caseSensitive: false, requiredFirst: false }], ], }, /** * desc */ { code: 'interface U {a:T; _:T; b:T;}', output: 'interface U {b:T; _:T; a:T;}', errors: ["Expected interface keys to be in descending order. 'b' should be before '_'."], optionsSet: [[SortingOrder.Descending]], }, { code: 'interface U {a:T; c:T; b:T;}', output: 'interface U {c:T; a:T; b:T;}', errors: ["Expected interface keys to be in descending order. 'c' should be before 'a'."], optionsSet: [[SortingOrder.Descending]], }, { code: 'interface U {b_:T; a:T; b:T;}', output: 'interface U {b_:T; b:T; a:T;}', errors: ["Expected interface keys to be in descending order. 'b' should be before 'a'."], optionsSet: [[SortingOrder.Descending]], }, { code: 'interface U {b_:T; c:T; C:T;}', output: 'interface U {c:T; b_:T; C:T;}', errors: ["Expected interface keys to be in descending order. 'c' should be before 'b_'."], optionsSet: [[SortingOrder.Descending]], }, { code: 'interface U {$:T; _:T; A:T; a:T;}', output: 'interface U {a:T; _:T; A:T; $:T;}', errors: [ "Expected interface keys to be in descending order. '_' should be before '$'.", "Expected interface keys to be in descending order. 'a' should be before 'A'.", ], optionsSet: [[SortingOrder.Descending]], }, { code: "interface U {1:T; 2:T; A:T; '11':T;}", output: "interface U {A:T; 2:T; 1:T; '11':T;}", errors: [ "Expected interface keys to be in descending order. '2' should be before '1'.", "Expected interface keys to be in descending order. 'A' should be before '2'.", ], optionsSet: [[SortingOrder.Descending]], }, { code: "interface U {'#':T; À:T; 'Z':T; è:T;}", output: "interface U {è:T; À:T; 'Z':T; '#':T;}", errors: [ "Expected interface keys to be in descending order. 'À' should be before '#'.", "Expected interface keys to be in descending order. 'è' should be before 'Z'.", ], optionsSet: [[SortingOrder.Descending]], }, /** * desc, insensitive */ { code: 'interface U {a:T; _:T; b:T;}', output: 'interface U {b:T; _:T; a:T;}', errors: [ "Expected interface keys to be in insensitive descending order. 'b' should be before '_'.", ], optionsSet: [[SortingOrder.Descending, { caseSensitive: false }]], }, { code: 'interface U {a:T; c:T; b:T;}', output: 'interface U {c:T; a:T; b:T;}', errors: [ "Expected interface keys to be in insensitive descending order. 'c' should be before 'a'.", ], optionsSet: [[SortingOrder.Descending, { caseSensitive: false }]], }, { code: 'interface U {b_:T; a:T; b:T;}', output: 'interface U {b_:T; b:T; a:T;}', errors: [ "Expected interface keys to be in insensitive descending order. 'b' should be before 'a'.", ], optionsSet: [[SortingOrder.Descending, { caseSensitive: false }]], }, { code: 'interface U {b_:T; c:T; C:T;}', output: 'interface U {c:T; b_:T; C:T;}', errors: [ "Expected interface keys to be in insensitive descending order. 'c' should be before 'b_'.", ], optionsSet: [[SortingOrder.Descending, { caseSensitive: false }]], }, { code: 'interface U {$:T; _:T; A:T; a:T;}', output: 'interface U {A:T; _:T; $:T; a:T;}', errors: [ "Expected interface keys to be in insensitive descending order. '_' should be before '$'.", "Expected interface keys to be in insensitive descending order. 'A' should be before '_'.", ], optionsSet: [[SortingOrder.Descending, { caseSensitive: false }]], }, { code: "interface U {1:T; 2:T; A:T; '11':T;}", output: "interface U {A:T; 2:T; 1:T; '11':T;}", errors: [ "Expected interface keys to be in insensitive descending order. '2' should be before '1'.", "Expected interface keys to be in insensitive descending order. 'A' should be before '2'.", ], optionsSet: [[SortingOrder.Descending, { caseSensitive: false }]], }, { code: "interface U {'#':T; À:T; 'Z':T; è:T;}", output: "interface U {è:T; À:T; 'Z':T; '#':T;}", errors: [ "Expected interface keys to be in insensitive descending order. 'À' should be before '#'.", "Expected interface keys to be in insensitive descending order. 'è' should be before 'Z'.", ], optionsSet: [[SortingOrder.Descending, { caseSensitive: false }]], }, /** * desc, natural */ { code: 'interface U {a:T; _:T; b:T;}', output: 'interface U {b:T; _:T; a:T;}', errors: [ "Expected interface keys to be in natural descending order. 'b' should be before '_'.", ], optionsSet: [[SortingOrder.Descending, { natural: true }]], }, { code: 'interface U {a:T; c:T; b:T;}', output: 'interface U {c:T; a:T; b:T;}', errors: [ "Expected interface keys to be in natural descending order. 'c' should be before 'a'.", ], optionsSet: [[SortingOrder.Descending, { natural: true }]], }, { code: 'interface U {b_:T; a:T; b:T;}', output: 'interface U {b_:T; b:T; a:T;}', errors: [ "Expected interface keys to be in natural descending order. 'b' should be before 'a'.", ], optionsSet: [[SortingOrder.Descending, { natural: true }]], }, { code: 'interface U {b_:T; c:T; C:T;}', output: 'interface U {c:T; b_:T; C:T;}', errors: [ "Expected interface keys to be in natural descending order. 'c' should be before 'b_'.", ], optionsSet: [[SortingOrder.Descending, { natural: true }]], }, { code: 'interface U {$:T; _:T; A:T; a:T;}', output: 'interface U {a:T; _:T; A:T; $:T;}', errors: [ "Expected interface keys to be in natural descending order. '_' should be before '$'.", "Expected interface keys to be in natural descending order. 'A' should be before '_'.", "Expected interface keys to be in natural descending order. 'a' should be before 'A'.", ], optionsSet: [[SortingOrder.Descending, { natural: true }]], }, { code: "interface U {1:T; 2:T; A:T; '11':T;}", output: "interface U {A:T; 2:T; 1:T; '11':T;}", errors: [ "Expected interface keys to be in natural descending order. '2' should be before '1'.", "Expected interface keys to be in natural descending order. 'A' should be before '2'.", ], optionsSet: [[SortingOrder.Descending, { natural: true }]], }, { code: "interface U {'#':T; À:T; 'Z':T; è:T;}", output: "interface U {è:T; À:T; 'Z':T; '#':T;}", errors: [ "Expected interface keys to be in natural descending order. 'À' should be before '#'.", "Expected interface keys to be in natural descending order. 'è' should be before 'Z'.", ], optionsSet: [[SortingOrder.Descending, { natural: true }]], }, /** * desc, natural, insensitive */ { code: 'interface U {a:T; _:T; b:T;}', output: 'interface U {b:T; _:T; a:T;}', errors: [ "Expected interface keys to be in natural insensitive descending order. 'b' should be before '_'.", ], optionsSet: [[SortingOrder.Descending, { natural: true, caseSensitive: false }]], }, { code: 'interface U {a:T; c:T; b:T;}', output: 'interface U {c:T; a:T; b:T;}', errors: [ "Expected interface keys to be in natural insensitive descending order. 'c' should be before 'a'.", ], optionsSet: [[SortingOrder.Descending, { natural: true, caseSensitive: false }]], }, { code: 'interface U {b_:T; a:T; b:T;}', output: 'interface U {b_:T; b:T; a:T;}', errors: [ "Expected interface keys to be in natural insensitive descending order. 'b' should be before 'a'.", ], optionsSet: [[SortingOrder.Descending, { natural: true, caseSensitive: false }]], }, { code: 'interface U {b_:T; c:T; C:T;}', output: 'interface U {c:T; b_:T; C:T;}', errors: [ "Expected interface keys to be in natural insensitive descending order. 'c' should be before 'b_'.", ], optionsSet: [[SortingOrder.Descending, { natural: true, caseSensitive: false }]], }, { code: 'interface U {$:T; _:T; A:T; a:T;}', output: 'interface U {A:T; _:T; $:T; a:T;}', errors: [ "Expected interface keys to be in natural insensitive descending order. '_' should be before '$'.", "Expected interface keys to be in natural insensitive descending order. 'A' should be before '_'.", ], optionsSet: [[SortingOrder.Descending, { natural: true, caseSensitive: false }]], }, { code: "interface U {1:T; 2:T; '11':T; A:T;}", output: "interface U {A:T; 2:T; '11':T; 1:T;}", errors: [ "Expected interface keys to be in natural insensitive descending order. '2' should be before '1'.", "Expected interface keys to be in natural insensitive descending order. '11' should be before '2'.", "Expected interface keys to be in natural insensitive descending order. 'A' should be before '11'.", ], optionsSet: [[SortingOrder.Descending, { natural: true, caseSensitive: false }]], }, { code: "interface U {'#':T; À:T; 'Z':T; è:T;}", output: "interface U {è:T; À:T; 'Z':T; '#':T;}", errors: [ "Expected interface keys to be in natural insensitive descending order. 'À' should be before '#'.", "Expected interface keys to be in natural insensitive descending order. 'è' should be before 'Z'.", ], optionsSet: [[SortingOrder.Descending, { natural: true, caseSensitive: false }]], }, /** * desc, natural, insensitive, required */ { code: 'interface U {_:T; a?:T; b:T;}', output: 'interface U {b:T; a?:T; _:T;}', errors: [ "Expected interface keys to be in required first natural insensitive descending order. 'b' should be before 'a'.", ], optionsSet: [ [SortingOrder.Descending, { natural: true, caseSensitive: false, requiredFirst: true }], ], }, { code: 'interface U {b:T; a?:T; _:T;}', output: 'interface U {b:T; _:T; a?:T;}', errors: [ "Expected interface keys to be in required first natural insensitive descending order. '_' should be before 'a'.", ], optionsSet: [ [SortingOrder.Descending, { natural: true, caseSensitive: false, requiredFirst: true }], ], }, { code: 'interface U {b:T; b_:T; a?:T;}', output: 'interface U {b_:T; b:T; a?:T;}', errors: [ "Expected interface keys to be in required first natural insensitive descending order. 'b_' should be before 'b'.", ], optionsSet: [ [SortingOrder.Descending, { natural: true, caseSensitive: false, requiredFirst: true }], ], }, { code: 'interface U {c:T; b_?:T; C:T;}', output: 'interface U {c:T; C:T; b_?:T;}', errors: [ "Expected interface keys to be in required first natural insensitive descending order. 'C' should be before 'b_'.", ], optionsSet: [ [SortingOrder.Descending, { natural: true, caseSensitive: false, requiredFirst: true }], ], }, { code: 'interface U {b_?:T; C:T; c:T;}', output: 'interface U {C:T; b_?:T; c:T;}', errors: [ "Expected interface keys to be in required first natural insensitive descending order. 'C' should be before 'b_'.", ], optionsSet: [ [SortingOrder.Descending, { natural: true, caseSensitive: false, requiredFirst: true }], ], }, { code: 'interface U {_:T; a?:T; $:T; A?:T;}', output: 'interface U {_:T; $:T; a?:T; A?:T;}', errors: [ "Expected interface keys to be in required first natural insensitive descending order. '$' should be before 'a'.", ], optionsSet: [ [SortingOrder.Descending, { natural: true, caseSensitive: false, requiredFirst: true }], ], }, { code: "interface U {2?:T; A:T; 1:T; '11':T;}", output: "interface U {A:T; 2?:T; 1:T; '11':T;}", errors: [ "Expected interface keys to be in required first natural insensitive descending order. 'A' should be before '2'.", "Expected interface keys to be in required first natural insensitive descending order. '11' should be before '1'.", ], optionsSet: [ [SortingOrder.Descending, { natural: true, caseSensitive: false, requiredFirst: true }], ], }, { code: "interface U {è:T; 'Z':T; '#'?:T; À?:T;}", output: "interface U {è:T; 'Z':T; À?:T; '#'?:T;}", errors: [ "Expected interface keys to be in required first natural insensitive descending order. 'À' should be before '#'.", ], optionsSet: [ [SortingOrder.Descending, { natural: true, caseSensitive: false, requiredFirst: true }], ], }, { code: "interface U {À?:T; 'Z':T; '#'?:T; è:T;}", output: "interface U {è:T; 'Z':T; '#'?:T; À?:T;}", errors: [ "Expected interface keys to be in required first natural insensitive descending order. 'Z' should be before 'À'.", "Expected interface keys to be in required first natural insensitive descending order. 'è' should be before '#'.", ], optionsSet: [ [SortingOrder.Descending, { natural: true, caseSensitive: false, requiredFirst: true }], ], }, /** * desc, natural, insensitive, not-required */ { code: 'interface U {_:T; a?:T; b:T;}', output: 'interface U {b:T; a?:T; _:T;}', errors: [ "Expected interface keys to be in natural insensitive descending order. 'a' should be before '_'.", "Expected interface keys to be in natural insensitive descending order. 'b' should be before 'a'.", ], optionsSet: [ [SortingOrder.Descending, { natural: true, caseSensitive: false, requiredFirst: false }], ], }, { code: 'interface U {a?:T; b:T; _:T;}', output: 'interface U {b:T; a?:T; _:T;}', errors: [ "Expected interface keys to be in natural insensitive descending order. 'b' should be before 'a'.", ], optionsSet: [ [SortingOrder.Descending, { natural: true, caseSensitive: false, requiredFirst: false }], ], }, { code: 'interface U {b:T; b_:T; a?:T;}', output: 'interface U {b_:T; b:T; a?:T;}', errors: [ "Expected interface keys to be in natural insensitive descending order. 'b_' should be before 'b'.", ], optionsSet: [ [SortingOrder.Descending, { natural: true, caseSensitive: false, requiredFirst: false }], ], }, { code: 'interface U {c:T; b_?:T; C:T;}', output: 'interface U {c:T; C:T; b_?:T;}', errors: [ "Expected interface keys to be in natural insensitive descending order. 'C' should be before 'b_'.", ], optionsSet: [ [SortingOrder.Descending, { natural: true, caseSensitive: false, requiredFirst: false }], ], }, { code: 'interface U {b_?:T; C:T; c:T;}', output: 'interface U {C:T; b_?:T; c:T;}', errors: [ "Expected interface keys to be in natural insensitive descending order. 'C' should be before 'b_'.", ], optionsSet: [ [SortingOrder.Descending, { natural: true, caseSensitive: false, requiredFirst: false }], ], }, { code: 'interface U {_:T; a?:T; $:T; A?:T;}', output: 'interface U {a?:T; _:T; $:T; A?:T;}', errors: [ "Expected interface keys to be in natural insensitive descending order. 'a' should be before '_'.", "Expected interface keys to be in natural insensitive descending order. 'A' should be before '$'.", ], optionsSet: [ [SortingOrder.Descending, { natural: true, caseSensitive: false, requiredFirst: false }], ], }, { code: "interface U {2?:T; A:T; 1:T; '11':T;}", output: "interface U {A:T; 2?:T; 1:T; '11':T;}", errors: [ "Expected interface keys to be in natural insensitive descending order. 'A' should be before '2'.", "Expected interface keys to be in natural insensitive descending order. '11' should be before '1'.", ], optionsSet: [ [SortingOrder.Descending, { natural: true, caseSensitive: false, requiredFirst: false }], ], }, { code: "interface U {è:T; 'Z':T; '#'?:T; À?:T;}", output: "interface U {è:T; À?:T; '#'?:T; 'Z':T;}", errors: [ "Expected interface keys to be in natural insensitive descending order. 'À' should be before '#'.", ], optionsSet: [ [SortingOrder.Descending, { natural: true, caseSensitive: false, requiredFirst: false }], ], }, { code: "interface U {À?:T; 'Z':T; '#'?:T; è:T;}", output: "interface U {è:T; 'Z':T; '#'?:T; À?:T;}", errors: [ "Expected interface keys to be in natural insensitive descending order. 'è' should be before '#'.", ], optionsSet: [ [SortingOrder.Descending, { natural: true, caseSensitive: false, requiredFirst: false }], ], }, /** * index signatures */ { code: 'interface U<T> { A: T; [skey: string]: T; _: T; }', output: 'interface U<T> { [skey: string]: T; A: T; _: T; }', errors: [ "Expected interface keys to be in ascending order. '[index: skey]' should be before 'A'.", ], optionsSet: [[SortingOrder.Ascending]], }, { code: 'interface U<T> { _: T; [skey: string]: T; A: T; }', output: 'interface U<T> { _: T; A: T; [skey: string]: T; }', errors: [ "Expected interface keys to be in descending order. 'A' should be before '[index: skey]'.", ], optionsSet: [[SortingOrder.Descending]], }, ] describe('TypeScript', () => { const ruleTester = new RuleTester(typescript) ruleTester.run(name, rule as unknown as Rule.RuleModule, { valid: processValidTestCase(valid), invalid: processInvalidTestCase(invalid), }) })
the_stack
declare namespace imbacss { /** * Specifies the width of the content area, padding area or border area (depending on 'box-sizing') of certain boxes. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/width) * * @alias w */ interface width extends _ { set(val: this | Ψlength | Ψpercentage): void; /** The width depends on the values of other properties. */ auto: '' /** Use the fit-content inline size or fit-content block size, as appropriate to the writing mode. */ fitΞcontent: '' /** Use the max-content inline size or max-content block size, as appropriate to the writing mode. */ maxΞcontent: '' /** Use the min-content inline size or min-content block size, as appropriate to the writing mode. */ minΞcontent: '' } /** @proxy width */ interface w extends width { } /** * Specifies the height of the content area, padding area or border area (depending on 'box-sizing') of certain boxes. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/height) * * @alias h */ interface height extends _ { set(val: this | Ψlength | Ψpercentage): void; /** The height depends on the values of other properties. */ auto: '' /** Use the fit-content inline size or fit-content block size, as appropriate to the writing mode. */ fitΞcontent: '' /** Use the max-content inline size or max-content block size, as appropriate to the writing mode. */ maxΞcontent: '' /** Use the min-content inline size or min-content block size, as appropriate to the writing mode. */ minΞcontent: '' } /** @proxy height */ interface h extends height { } /** * In combination with 'float' and 'position', determines the type of box or boxes that are generated for an element. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/display) * * @alias d */ interface display extends _ { set(val: this): void; /** The element generates a block-level box */ block: '' /** The element itself does not generate any boxes, but its children and pseudo-elements still generate boxes as normal. */ contents: '' /** The element generates a principal flex container box and establishes a flex formatting context. */ flex: '' /** Flex with flex-direction set to row */ hflex: '' /** Flex with flex-direction set to column */ vflex: '' /** The element generates a block container box, and lays out its contents using flow layout. */ flowΞroot: '' /** The element generates a principal grid container box, and establishes a grid formatting context. */ grid: '' /** Grid with grid-auto-flow set to column */ hgrid: '' /** Grid with grid-auto-flow set to row */ vgrid: '' /** The element generates an inline-level box. */ inline: '' /** A block box, which itself is flowed as a single inline box, similar to a replaced element. The inside of an inline-block is formatted as a block box, and the box itself is formatted as an inline box. */ inlineΞblock: '' /** Inline-level flex container. */ inlineΞflex: '' /** Inline-level table wrapper box containing table box. */ inlineΞtable: '' /** One or more block boxes and one marker box. */ listΞitem: '' /** The element lays out its contents using flow layout (block-and-inline layout). Standardized as 'flex'. */ ΞmozΞbox: '' ΞmozΞdeck: '' ΞmozΞgrid: '' ΞmozΞgridΞgroup: '' ΞmozΞgridΞline: '' ΞmozΞgroupbox: '' /** Inline-level flex container. Standardized as 'inline-flex' */ ΞmozΞinlineΞbox: '' ΞmozΞinlineΞgrid: '' ΞmozΞinlineΞstack: '' ΞmozΞmarker: '' ΞmozΞpopup: '' ΞmozΞstack: '' /** The element lays out its contents using flow layout (block-and-inline layout). Standardized as 'flex'. */ ΞmsΞflexbox: '' /** The element generates a principal grid container box, and establishes a grid formatting context. */ ΞmsΞgrid: '' /** Inline-level flex container. Standardized as 'inline-flex' */ ΞmsΞinlineΞflexbox: '' /** Inline-level grid container. */ ΞmsΞinlineΞgrid: '' /** The element and its descendants generates no boxes. */ none: '' /** The element generates a principal ruby container box, and establishes a ruby formatting context. */ ruby: '' rubyΞbase: '' rubyΞbaseΞcontainer: '' rubyΞtext: '' rubyΞtextΞcontainer: '' /** The element generates a run-in box. Run-in elements act like inlines or blocks, depending on the surrounding elements. */ runΞin: '' /** The element generates a principal table wrapper box containing an additionally-generated table box, and establishes a table formatting context. */ table: '' tableΞcaption: '' tableΞcell: '' tableΞcolumn: '' tableΞcolumnΞgroup: '' tableΞfooterΞgroup: '' tableΞheaderΞgroup: '' tableΞrow: '' tableΞrowΞgroup: '' /** The element lays out its contents using flow layout (block-and-inline layout). Standardized as 'flex'. */ ΞwebkitΞbox: '' /** The element lays out its contents using flow layout (block-and-inline layout). */ ΞwebkitΞflex: '' /** Inline-level flex container. Standardized as 'inline-flex' */ ΞwebkitΞinlineΞbox: '' /** Inline-level flex container. */ ΞwebkitΞinlineΞflex: '' } /** @proxy display */ interface d extends display { } /** * Shorthand property to set values the thickness of the padding area. If left is omitted, it is the same as right. If bottom is omitted it is the same as top, if right is omitted it is the same as top. The value may not be negative. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/padding) * * @alias p */ interface padding extends _ { set(val: Ψlength | Ψpercentage, arg1: any, arg2: any, arg3: any): void; } /** @proxy padding */ interface p extends padding { } /** * The position CSS property sets how an element is positioned in a document. The top, right, bottom, and left properties determine the final location of positioned elements. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/position) * * @alias pos */ interface position extends _ { set(val: this): void; /** The box's position (and possibly size) is specified with the 'top', 'right', 'bottom', and 'left' properties. These properties specify offsets with respect to the box's 'containing block'. */ absolute: '' /** The box's position is calculated according to the 'absolute' model, but in addition, the box is fixed with respect to some reference. As with the 'absolute' model, the box's margins do not collapse with any other margins. */ fixed: '' /** The box's position is calculated according to the 'absolute' model. */ ΞmsΞpage: '' /** The box's position is calculated according to the normal flow (this is called the position in normal flow). Then the box is offset relative to its normal position. */ relative: '' /** The box is a normal box, laid out according to the normal flow. The 'top', 'right', 'bottom', and 'left' properties do not apply. */ static: '' /** The box's position is calculated according to the normal flow. Then the box is offset relative to its flow root and containing block and in all cases, including table elements, does not affect the position of any following boxes. */ sticky: '' /** The box's position is calculated according to the normal flow. Then the box is offset relative to its flow root and containing block and in all cases, including table elements, does not affect the position of any following boxes. */ ΞwebkitΞsticky: '' } /** @proxy position */ interface pos extends position { } /** * Shorthand property for setting border width, style, and color. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border) * * @alias bd */ interface border extends _ { set(val: Ψlength | ΨlineΞwidth | ΨlineΞstyle | Ψcolor): void; } /** @proxy border */ interface bd extends border { } /** * Shorthand property to set values the thickness of the margin area. If left is omitted, it is the same as right. If bottom is omitted it is the same as top, if right is omitted it is the same as top. Negative values for margin properties are allowed, but there may be implementation-specific limits. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/margin) * * @alias m */ interface margin extends _ { set(val: this | Ψlength | Ψpercentage, arg1: any, arg2: any, arg3: any): void; auto: '' } /** @proxy margin */ interface m extends margin { } /** * Set asset as inline background svg * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/svg) * */ interface svg extends _ { set(val: any): void; } /** * Specifies how far an absolutely positioned box's top margin edge is offset below the top edge of the box's 'containing block'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/top) * * @alias t */ interface top extends _ { set(val: this | Ψlength | Ψpercentage): void; /** For non-replaced elements, the effect of this value depends on which of related properties have the value 'auto' as well */ auto: '' } /** @proxy top */ interface t extends top { } /** * Specifies how far an absolutely positioned box's left margin edge is offset to the right of the left edge of the box's 'containing block'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/left) * * @alias l */ interface left extends _ { set(val: this | Ψlength | Ψpercentage): void; /** For non-replaced elements, the effect of this value depends on which of related properties have the value 'auto' as well */ auto: '' } /** @proxy left */ interface l extends left { } /** * Shorthand property to set values the thickness of the margin area. If left is omitted, it is the same as right. If bottom is omitted it is the same as top, if right is omitted it is the same as top. Negative values for margin properties are allowed, but there may be implementation-specific limits.. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/margin-top) * * @alias mt */ interface marginΞtop extends _ { set(val: this | Ψlength | Ψpercentage): void; auto: '' } /** @proxy marginΞtop */ interface mt extends marginΞtop { } /** * Sets the color of an element's text * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/color) * * @alias c */ interface color extends _ { set(val: Ψcolor): void; } /** @proxy color */ interface c extends color { } /** * Indicates the desired height of glyphs from the font. For scalable fonts, the font-size is a scale factor applied to the EM unit of the font. (Note that certain glyphs may bleed outside their EM box.) For non-scalable fonts, the font-size is converted into absolute units and matched against the declared font-size of the font, using the same absolute coordinate space for both of the matched values. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/font-size) * * @alias fs */ interface fontΞsize extends _ { set(val: Ψfs | this | Ψlength | Ψpercentage): void; large: '' larger: '' medium: '' small: '' smaller: '' xΞlarge: '' xΞsmall: '' xxΞlarge: '' xxΞsmall: '' } /** @proxy fontΞsize */ interface fs extends fontΞsize { } /** * Sets the background color of an element. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/background-color) * * @alias bgc */ interface backgroundΞcolor extends _ { set(val: Ψcolor): void; } /** @proxy backgroundΞcolor */ interface bgc extends backgroundΞcolor { } /** * Describes how inline contents of a block are horizontally aligned if the contents do not completely fill the line box. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align) * * @alias ta */ interface textΞalign extends _ { set(val: this | Ψstring): void; /** The inline contents are centered within the line box. */ center: '' /** The inline contents are aligned to the end edge of the line box. */ end: '' /** The text is justified according to the method specified by the 'text-justify' property. */ justify: '' /** The inline contents are aligned to the left edge of the line box. In vertical text, 'left' aligns to the edge of the line box that would be the start edge for left-to-right text. */ left: '' /** The inline contents are aligned to the right edge of the line box. In vertical text, 'right' aligns to the edge of the line box that would be the end edge for left-to-right text. */ right: '' /** The inline contents are aligned to the start edge of the line box. */ start: '' } /** @proxy textΞalign */ interface ta extends textΞalign { } /** * Opacity of an element's text, where 1 is opaque and 0 is entirely transparent. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/opacity) * * @alias o */ interface opacity extends _ { set(val: Ψnumber): void; } /** @proxy opacity */ interface o extends opacity { } /** * Shorthand property for setting most background properties at the same place in the style sheet. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/background) * * @alias bg */ interface background extends _ { set(val: this | Ψimage | Ψcolor | Ψposition | Ψlength | Ψrepeat | Ψpercentage | Ψbox, arg1: any, arg2: any, arg3: any): void; /** The background is fixed with regard to the viewport. In paged media where there is no viewport, a 'fixed' background is fixed with respect to the page box and therefore replicated on every page. */ fixed: '' /** The background is fixed with regard to the element's contents: if the element has a scrolling mechanism, the background scrolls with the element's contents. */ local: '' /** A value of 'none' counts as an image layer but draws nothing. */ none: '' /** The background is fixed with regard to the element itself and does not scroll with its contents. (It is effectively attached to the element's border.) */ scroll: '' } /** @proxy background */ interface bg extends background { } /** * Specifies weight of glyphs in the font, their degree of blackness or stroke thickness. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight) * * @alias fw */ interface fontΞweight extends _ { set(val: this): void; /** Thin */ 100: '' /** Extra Light (Ultra Light) */ 200: '' /** Light */ 300: '' /** Normal */ 400: '' /** Medium */ 500: '' /** Semi Bold (Demi Bold) */ 600: '' /** Bold */ 700: '' /** Extra Bold (Ultra Bold) */ 800: '' /** Black (Heavy) */ 900: '' /** Same as 700 */ bold: '' /** Specifies the weight of the face bolder than the inherited value. */ bolder: '' /** Specifies the weight of the face lighter than the inherited value. */ lighter: '' /** Same as 400 */ normal: '' } /** @proxy fontΞweight */ interface fw extends fontΞweight { } /** * Shorthand for setting 'overflow-x' and 'overflow-y'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/overflow) * * @alias of */ interface overflow extends _ { set(val: this, arg1: any): void; /** The behavior of the 'auto' value is UA-dependent, but should cause a scrolling mechanism to be provided for overflowing boxes. */ auto: '' /** Content is clipped and no scrolling mechanism should be provided to view the content outside the clipping region. */ hidden: '' /** Same as the standardized 'clip', except doesn’t establish a block formatting context. */ ΞmozΞhiddenΞunscrollable: '' /** Content is clipped and if the user agent uses a scrolling mechanism that is visible on the screen (such as a scroll bar or a panner), that mechanism should be displayed for a box whether or not any of its content is clipped. */ scroll: '' /** Content is not clipped, i.e., it may be rendered outside the content box. */ visible: '' } /** @proxy overflow */ interface of extends overflow { } /** * Specifies a prioritized list of font family names or generic family names. A user agent iterates through the list of family names until it matches an available font that contains a glyph for the character to be rendered. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/font-family) * * @alias ff */ interface fontΞfamily extends _ { set(val: this | Ψfont, arg1: any, arg2: any, arg3: any): void; cursive: '' fantasy: '' monospace: '' sansΞserif: '' serif: '' } /** @proxy fontΞfamily */ interface ff extends fontΞfamily { } /** * Specifies how a box should be floated. It may be set for any element, but only applies to elements that generate boxes that are not absolutely positioned. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/float) * */ interface float extends _ { set(val: this): void; /** A keyword indicating that the element must float on the end side of its containing block. That is the right side with ltr scripts, and the left side with rtl scripts. */ inlineΞend: '' /** A keyword indicating that the element must float on the start side of its containing block. That is the left side with ltr scripts, and the right side with rtl scripts. */ inlineΞstart: '' /** The element generates a block box that is floated to the left. Content flows on the right side of the box, starting at the top (subject to the 'clear' property). */ left: '' /** The box is not floated. */ none: '' /** Similar to 'left', except the box is floated to the right, and content flows on the left side of the box, starting at the top. */ right: '' } /** * Determines the block-progression dimension of the text content area of an inline box. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height) * * @alias lh */ interface lineΞheight extends _ { set(val: this | Ψnumber | Ψlength | Ψpercentage): void; /** Tells user agents to set the computed value to a 'reasonable' value based on the font size of the element. */ normal: '' } /** @proxy lineΞheight */ interface lh extends lineΞheight { } /** * Specifies the behavior of the 'width' and 'height' properties. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing) * */ interface boxΞsizing extends _ { set(val: this): void; /** The specified width and height (and respective min/max properties) on this element determine the border box of the element. */ borderΞbox: '' /** Behavior of width and height as specified by CSS2.1. The specified width and height (and respective min/max properties) apply to the width and height respectively of the content box of the element. */ contentΞbox: '' } /** * Decorations applied to font used for an element's text. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/text-decoration) * * @alias td */ interface textΞdecoration extends _ { set(val: this | Ψcolor): void; /** Produces a dashed line style. */ dashed: '' /** Produces a dotted line. */ dotted: '' /** Produces a double line. */ double: '' /** Each line of text has a line through the middle. */ lineΞthrough: '' /** Produces no line. */ none: '' /** Each line of text has a line above it. */ overline: '' /** Produces a solid line. */ solid: '' /** Each line of text is underlined. */ underline: '' /** Produces a wavy line. */ wavy: '' } /** @proxy textΞdecoration */ interface td extends textΞdecoration { } /** * For a positioned box, the 'z-index' property specifies the stack level of the box in the current stacking context and whether the box establishes a local stacking context. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/z-index) * * @alias zi */ interface zΞindex extends _ { set(val: this | Ψinteger): void; /** The stack level of the generated box in the current stacking context is 0. The box does not establish a new stacking context unless it is the root element. */ auto: '' } /** @proxy zΞindex */ interface zi extends zΞindex { } /** * Affects the vertical positioning of the inline boxes generated by an inline-level element inside a line box. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align) * * @alias va */ interface verticalΞalign extends _ { set(val: this | Ψpercentage | Ψlength): void; /** Align the dominant baseline of the parent box with the equivalent, or heuristically reconstructed, baseline of the element inline box. */ auto: '' /** Align the 'alphabetic' baseline of the element with the 'alphabetic' baseline of the parent element. */ baseline: '' /** Align the after edge of the extended inline box with the after-edge of the line box. */ bottom: '' /** Align the 'middle' baseline of the inline element with the middle baseline of the parent. */ middle: '' /** Lower the baseline of the box to the proper position for subscripts of the parent's box. (This value has no effect on the font size of the element's text.) */ sub: '' /** Raise the baseline of the box to the proper position for superscripts of the parent's box. (This value has no effect on the font size of the element's text.) */ super: '' /** Align the bottom of the box with the after-edge of the parent element's font. */ textΞbottom: '' /** Align the top of the box with the before-edge of the parent element's font. */ textΞtop: '' /** Align the before edge of the extended inline box with the before-edge of the line box. */ top: '' ΞwebkitΞbaselineΞmiddle: '' } /** @proxy verticalΞalign */ interface va extends verticalΞalign { } /** * Allows control over cursor appearance in an element * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/cursor) * */ interface cursor extends _ { set(val: this | Ψurl | Ψnumber): void; /** Indicates an alias of/shortcut to something is to be created. Often rendered as an arrow with a small curved arrow next to it. */ alias: '' /** Indicates that the something can be scrolled in any direction. Often rendered as arrows pointing up, down, left, and right with a dot in the middle. */ allΞscroll: '' /** The UA determines the cursor to display based on the current context. */ auto: '' /** Indicates that a cell or set of cells may be selected. Often rendered as a thick plus-sign with a dot in the middle. */ cell: '' /** Indicates that the item/column can be resized horizontally. Often rendered as arrows pointing left and right with a vertical bar separating them. */ colΞresize: '' /** A context menu is available for the object under the cursor. Often rendered as an arrow with a small menu-like graphic next to it. */ contextΞmenu: '' /** Indicates something is to be copied. Often rendered as an arrow with a small plus sign next to it. */ copy: '' /** A simple crosshair (e.g., short line segments resembling a '+' sign). Often used to indicate a two dimensional bitmap selection mode. */ crosshair: '' /** The platform-dependent default cursor. Often rendered as an arrow. */ default: '' /** Indicates that east edge is to be moved. */ eΞresize: '' /** Indicates a bidirectional east-west resize cursor. */ ewΞresize: '' /** Indicates that something can be grabbed. */ grab: '' /** Indicates that something is being grabbed. */ grabbing: '' /** Help is available for the object under the cursor. Often rendered as a question mark or a balloon. */ help: '' /** Indicates something is to be moved. */ move: '' /** Indicates that something can be grabbed. */ ΞmozΞgrab: '' /** Indicates that something is being grabbed. */ ΞmozΞgrabbing: '' /** Indicates that something can be zoomed (magnified) in. */ ΞmozΞzoomΞin: '' /** Indicates that something can be zoomed (magnified) out. */ ΞmozΞzoomΞout: '' /** Indicates that movement starts from north-east corner. */ neΞresize: '' /** Indicates a bidirectional north-east/south-west cursor. */ neswΞresize: '' /** Indicates that the dragged item cannot be dropped at the current cursor location. Often rendered as a hand or pointer with a small circle with a line through it. */ noΞdrop: '' /** No cursor is rendered for the element. */ none: '' /** Indicates that the requested action will not be carried out. Often rendered as a circle with a line through it. */ notΞallowed: '' /** Indicates that north edge is to be moved. */ nΞresize: '' /** Indicates a bidirectional north-south cursor. */ nsΞresize: '' /** Indicates that movement starts from north-west corner. */ nwΞresize: '' /** Indicates a bidirectional north-west/south-east cursor. */ nwseΞresize: '' /** The cursor is a pointer that indicates a link. */ pointer: '' /** A progress indicator. The program is performing some processing, but is different from 'wait' in that the user may still interact with the program. Often rendered as a spinning beach ball, or an arrow with a watch or hourglass. */ progress: '' /** Indicates that the item/row can be resized vertically. Often rendered as arrows pointing up and down with a horizontal bar separating them. */ rowΞresize: '' /** Indicates that movement starts from south-east corner. */ seΞresize: '' /** Indicates that south edge is to be moved. */ sΞresize: '' /** Indicates that movement starts from south-west corner. */ swΞresize: '' /** Indicates text that may be selected. Often rendered as a vertical I-beam. */ text: '' /** Indicates vertical-text that may be selected. Often rendered as a horizontal I-beam. */ verticalΞtext: '' /** Indicates that the program is busy and the user should wait. Often rendered as a watch or hourglass. */ wait: '' /** Indicates that something can be grabbed. */ ΞwebkitΞgrab: '' /** Indicates that something is being grabbed. */ ΞwebkitΞgrabbing: '' /** Indicates that something can be zoomed (magnified) in. */ ΞwebkitΞzoomΞin: '' /** Indicates that something can be zoomed (magnified) out. */ ΞwebkitΞzoomΞout: '' /** Indicates that west edge is to be moved. */ wΞresize: '' /** Indicates that something can be zoomed (magnified) in. */ zoomΞin: '' /** Indicates that something can be zoomed (magnified) out. */ zoomΞout: '' } /** * Shorthand property to set values the thickness of the margin area. If left is omitted, it is the same as right. If bottom is omitted it is the same as top, if right is omitted it is the same as top. Negative values for margin properties are allowed, but there may be implementation-specific limits.. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/margin-left) * * @alias ml */ interface marginΞleft extends _ { set(val: this | Ψlength | Ψpercentage): void; auto: '' } /** @proxy marginΞleft */ interface ml extends marginΞleft { } /** * Defines the radii of the outer border edge. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-radius) * * @alias rd */ interface borderΞradius extends _ { set(val: Ψradius | Ψlength | Ψpercentage, arg1: any, arg2: any, arg3: any): void; } /** @proxy borderΞradius */ interface rd extends borderΞradius { } /** * Shorthand property to set values the thickness of the margin area. If left is omitted, it is the same as right. If bottom is omitted it is the same as top, if right is omitted it is the same as top. Negative values for margin properties are allowed, but there may be implementation-specific limits.. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/margin-bottom) * * @alias mb */ interface marginΞbottom extends _ { set(val: this | Ψlength | Ψpercentage): void; auto: '' } /** @proxy marginΞbottom */ interface mb extends marginΞbottom { } /** * Shorthand property to set values the thickness of the margin area. If left is omitted, it is the same as right. If bottom is omitted it is the same as top, if right is omitted it is the same as top. Negative values for margin properties are allowed, but there may be implementation-specific limits.. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/margin-right) * * @alias mr */ interface marginΞright extends _ { set(val: this | Ψlength | Ψpercentage): void; auto: '' } /** @proxy marginΞright */ interface mr extends marginΞright { } /** * Specifies how far an absolutely positioned box's right margin edge is offset to the left of the right edge of the box's 'containing block'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/right) * * @alias r */ interface right extends _ { set(val: this | Ψlength | Ψpercentage): void; /** For non-replaced elements, the effect of this value depends on which of related properties have the value 'auto' as well */ auto: '' } /** @proxy right */ interface r extends right { } /** * Shorthand property to set values the thickness of the padding area. If left is omitted, it is the same as right. If bottom is omitted it is the same as top, if right is omitted it is the same as top. The value may not be negative. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/padding-left) * * @alias pl */ interface paddingΞleft extends _ { set(val: Ψlength | Ψpercentage): void; } /** @proxy paddingΞleft */ interface pl extends paddingΞleft { } /** * Shorthand property to set values the thickness of the padding area. If left is omitted, it is the same as right. If bottom is omitted it is the same as top, if right is omitted it is the same as top. The value may not be negative. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/padding-top) * * @alias pt */ interface paddingΞtop extends _ { set(val: Ψlength | Ψpercentage): void; } /** @proxy paddingΞtop */ interface pt extends paddingΞtop { } /** * Allows authors to constrain content width to a certain range. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/max-width) * */ interface maxΞwidth extends _ { set(val: this | Ψlength | Ψpercentage): void; /** No limit on the width of the box. */ none: '' /** Use the fit-content inline size or fit-content block size, as appropriate to the writing mode. */ fitΞcontent: '' /** Use the max-content inline size or max-content block size, as appropriate to the writing mode. */ maxΞcontent: '' /** Use the min-content inline size or min-content block size, as appropriate to the writing mode. */ minΞcontent: '' } /** * Specifies how far an absolutely positioned box's bottom margin edge is offset above the bottom edge of the box's 'containing block'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/bottom) * * @alias b */ interface bottom extends _ { set(val: this | Ψlength | Ψpercentage): void; /** For non-replaced elements, the effect of this value depends on which of related properties have the value 'auto' as well */ auto: '' } /** @proxy bottom */ interface b extends bottom { } /** * Determines which page-based occurrence of a given element is applied to a counter or string value. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/content) * */ interface content extends _ { set(val: this | Ψstring | Ψurl): void; /** The attr(n) function returns as a string the value of attribute n for the subject of the selector. */ attr(): '' /** Counters are denoted by identifiers (see the 'counter-increment' and 'counter-reset' properties). */ counter(name): '' /** The (pseudo-)element is replaced in its entirety by the resource referenced by its 'icon' property, and treated as a replaced element. */ icon: '' /** On elements, this inhibits the children of the element from being rendered as children of this element, as if the element was empty. On pseudo-elements it causes the pseudo-element to have no content. */ none: '' /** See http://www.w3.org/TR/css3-content/#content for computation rules. */ normal: '' url(): '' } /** * Attaches one or more drop-shadows to the box. The property is a comma-separated list of shadows, each specified by 2-4 length values, an optional color, and an optional 'inset' keyword. Omitted lengths are 0; omitted colors are a user agent chosen color. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/box-shadow) * * @alias shadow */ interface boxΞshadow extends _ { set(val: Ψshadow | this | Ψlength | Ψcolor): void; /** Changes the drop shadow from an outer shadow (one that shadows the box onto the canvas, as if it were lifted above the canvas) to an inner shadow (one that shadows the canvas onto the box, as if the box were cut out of the canvas and shifted behind it). */ inset: '' /** No shadow. */ none: '' } /** @proxy boxΞshadow */ interface shadow extends boxΞshadow { } /** * Sets the background image(s) of an element. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/background-image) * * @alias bgi */ interface backgroundΞimage extends _ { set(val: this | Ψimage, arg1: any, arg2: any, arg3: any): void; /** Counts as an image layer but draws nothing. */ none: '' } /** @proxy backgroundΞimage */ interface bgi extends backgroundΞimage { } /** * Shorthand property to set values the thickness of the padding area. If left is omitted, it is the same as right. If bottom is omitted it is the same as top, if right is omitted it is the same as top. The value may not be negative. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/padding-right) * * @alias pr */ interface paddingΞright extends _ { set(val: Ψlength | Ψpercentage): void; } /** @proxy paddingΞright */ interface pr extends paddingΞright { } /** * Shorthand property for the 'white-space-collapsing' and 'text-wrap' properties. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/white-space) * * @alias ws */ interface whiteΞspace extends _ { set(val: this): void; /** Sets 'white-space-collapsing' to 'collapse' and 'text-wrap' to 'normal'. */ normal: '' /** Sets 'white-space-collapsing' to 'collapse' and 'text-wrap' to 'none'. */ nowrap: '' /** Sets 'white-space-collapsing' to 'preserve' and 'text-wrap' to 'none'. */ pre: '' /** Sets 'white-space-collapsing' to 'preserve-breaks' and 'text-wrap' to 'normal'. */ preΞline: '' /** Sets 'white-space-collapsing' to 'preserve' and 'text-wrap' to 'normal'. */ preΞwrap: '' } /** @proxy whiteΞspace */ interface ws extends whiteΞspace { } /** * Shorthand property to set values the thickness of the padding area. If left is omitted, it is the same as right. If bottom is omitted it is the same as top, if right is omitted it is the same as top. The value may not be negative. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/padding-bottom) * * @alias pb */ interface paddingΞbottom extends _ { set(val: Ψlength | Ψpercentage): void; } /** @proxy paddingΞbottom */ interface pb extends paddingΞbottom { } /** * Allows authors to constrain content height to a certain range. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/min-height) * */ interface minΞheight extends _ { set(val: this | Ψlength | Ψpercentage): void; auto: '' /** Use the fit-content inline size or fit-content block size, as appropriate to the writing mode. */ fitΞcontent: '' /** Use the max-content inline size or max-content block size, as appropriate to the writing mode. */ maxΞcontent: '' /** Use the min-content inline size or min-content block size, as appropriate to the writing mode. */ minΞcontent: '' } /** * A two-dimensional transformation is applied to an element through the 'transform' property. This property contains a list of transform functions similar to those allowed by SVG. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/transform) * */ interface transform extends _ { set(val: this): void; /** Specifies a 2D transformation in the form of a transformation matrix of six values. matrix(a,b,c,d,e,f) is equivalent to applying the transformation matrix [a b c d e f] */ matrix(): '' /** Specifies a 3D transformation as a 4x4 homogeneous matrix of 16 values in column-major order. */ matrix3d(): '' none: '' /** Specifies a perspective projection matrix. */ perspective(): '' /** Specifies a 2D rotation by the angle specified in the parameter about the origin of the element, as defined by the transform-origin property. */ rotate(): '' /** Specifies a clockwise 3D rotation by the angle specified in last parameter about the [x,y,z] direction vector described by the first 3 parameters. */ rotate3d(): '' /** Specifies a 2D scale operation by the [sx,sy] scaling vector described by the 2 parameters. If the second parameter is not provided, it is takes a value equal to the first. */ scale(): '' /** Specifies a 3D scale operation by the [sx,sy,sz] scaling vector described by the 3 parameters. */ scale3d(): '' /** Specifies a scale operation using the [sx,1] scaling vector, where sx is given as the parameter. */ scaleX(): '' /** Specifies a scale operation using the [sy,1] scaling vector, where sy is given as the parameter. */ scaleY(): '' /** Specifies a scale operation using the [1,1,sz] scaling vector, where sz is given as the parameter. */ scaleZ(): '' /** Specifies a skew transformation along the X and Y axes. The first angle parameter specifies the skew on the X axis. The second angle parameter specifies the skew on the Y axis. If the second parameter is not given then a value of 0 is used for the Y angle (ie: no skew on the Y axis). */ skew(): '' /** Specifies a skew transformation along the X axis by the given angle. */ skewX(): '' /** Specifies a skew transformation along the Y axis by the given angle. */ skewY(): '' /** Specifies a 2D translation by the vector [tx, ty], where tx is the first translation-value parameter and ty is the optional second translation-value parameter. */ translate(): '' /** Specifies a 3D translation by the vector [tx,ty,tz], with tx, ty and tz being the first, second and third translation-value parameters respectively. */ translate3d(): '' /** Specifies a translation by the given amount in the X direction. */ translateX(): '' /** Specifies a translation by the given amount in the Y direction. */ translateY(): '' /** Specifies a translation by the given amount in the Z direction. Note that percentage values are not allowed in the translateZ translation-value, and if present are evaluated as 0. */ translateZ(): '' } /** * Shorthand property for setting border width, style and color. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-bottom) * * @alias bdb */ interface borderΞbottom extends _ { set(val: Ψlength | ΨlineΞwidth | ΨlineΞstyle | Ψcolor): void; } /** @proxy borderΞbottom */ interface bdb extends borderΞbottom { } /** * Specifies whether the boxes generated by an element are rendered. Invisible boxes still affect layout (set the ‘display’ property to ‘none’ to suppress box generation altogether). * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/visibility) * */ interface visibility extends _ { set(val: this): void; /** Table-specific. If used on elements other than rows, row groups, columns, or column groups, 'collapse' has the same meaning as 'hidden'. */ collapse: '' /** The generated box is invisible (fully transparent, nothing is drawn), but still affects layout. */ hidden: '' /** The generated box is visible. */ visible: '' } /** * Specifies the initial position of the background image(s) (after any resizing) within their corresponding background positioning area. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/background-position) * * @alias bgp */ interface backgroundΞposition extends _ { set(val: Ψposition | Ψlength | Ψpercentage, arg1: any, arg2: any, arg3: any): void; } /** @proxy backgroundΞposition */ interface bgp extends backgroundΞposition { } /** * Shorthand property for setting border width, style and color * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-top) * * @alias bdt */ interface borderΞtop extends _ { set(val: Ψlength | ΨlineΞwidth | ΨlineΞstyle | Ψcolor): void; } /** @proxy borderΞtop */ interface bdt extends borderΞtop { } /** * Allows authors to constrain content width to a certain range. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/min-width) * */ interface minΞwidth extends _ { set(val: this | Ψlength | Ψpercentage): void; auto: '' /** Use the fit-content inline size or fit-content block size, as appropriate to the writing mode. */ fitΞcontent: '' /** Use the max-content inline size or max-content block size, as appropriate to the writing mode. */ maxΞcontent: '' /** Use the min-content inline size or min-content block size, as appropriate to the writing mode. */ minΞcontent: '' } /** * Shorthand property for 'outline-style', 'outline-width', and 'outline-color'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/outline) * */ interface outline extends _ { set(val: this | Ψlength | ΨlineΞwidth | ΨlineΞstyle | Ψcolor): void; /** Permits the user agent to render a custom outline style, typically the default platform style. */ auto: '' /** Performs a color inversion on the pixels on the screen. */ invert: '' } /** * The color of the border around all four edges of an element. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-color) * * @alias bc */ interface borderΞcolor extends _ { set(val: Ψcolor, arg1: any, arg2: any, arg3: any): void; } /** @proxy borderΞcolor */ interface bc extends borderΞcolor { } /** * Specifies how background images are tiled after they have been sized and positioned. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/background-repeat) * * @alias bgr */ interface backgroundΞrepeat extends _ { set(val: Ψrepeat, arg1: any, arg2: any, arg3: any): void; } /** @proxy backgroundΞrepeat */ interface bgr extends backgroundΞrepeat { } /** * Controls capitalization effects of an element’s text. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/text-transform) * * @alias tt */ interface textΞtransform extends _ { set(val: this): void; /** Puts the first typographic letter unit of each word in titlecase. */ capitalize: '' /** Puts all letters in lowercase. */ lowercase: '' /** No effects. */ none: '' /** Puts all letters in uppercase. */ uppercase: '' } /** @proxy textΞtransform */ interface tt extends textΞtransform { } /** * Specifies the size of the background images. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/background-size) * * @alias bgs */ interface backgroundΞsize extends _ { set(val: this | Ψlength | Ψpercentage, arg1: any, arg2: any, arg3: any): void; /** Resolved by using the image’s intrinsic ratio and the size of the other dimension, or failing that, using the image’s intrinsic size, or failing that, treating it as 100%. */ auto: '' /** Scale the image, while preserving its intrinsic aspect ratio (if any), to the largest size such that both its width and its height can fit inside the background positioning area. */ contain: '' /** Scale the image, while preserving its intrinsic aspect ratio (if any), to the smallest size such that both its width and its height can completely cover the background positioning area. */ cover: '' } /** @proxy backgroundΞsize */ interface bgs extends backgroundΞsize { } /** * Indicates which sides of an element's box(es) may not be adjacent to an earlier floating box. The 'clear' property does not consider floats inside the element itself or in other block formatting contexts. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/clear) * */ interface clear extends _ { set(val: this): void; /** The clearance of the generated box is set to the amount necessary to place the top border edge below the bottom outer edge of any right-floating and left-floating boxes that resulted from elements earlier in the source document. */ both: '' /** The clearance of the generated box is set to the amount necessary to place the top border edge below the bottom outer edge of any left-floating boxes that resulted from elements earlier in the source document. */ left: '' /** No constraint on the box's position with respect to floats. */ none: '' /** The clearance of the generated box is set to the amount necessary to place the top border edge below the bottom outer edge of any right-floating boxes that resulted from elements earlier in the source document. */ right: '' } /** * Allows authors to constrain content height to a certain range. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/max-height) * */ interface maxΞheight extends _ { set(val: this | Ψlength | Ψpercentage): void; /** No limit on the height of the box. */ none: '' /** Use the fit-content inline size or fit-content block size, as appropriate to the writing mode. */ fitΞcontent: '' /** Use the max-content inline size or max-content block size, as appropriate to the writing mode. */ maxΞcontent: '' /** Use the min-content inline size or min-content block size, as appropriate to the writing mode. */ minΞcontent: '' } /** * Shorthand for setting 'list-style-type', 'list-style-position' and 'list-style-image' * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/list-style) * */ interface listΞstyle extends _ { set(val: this | Ψimage | Ψurl): void; armenian: '' /** A hollow circle. */ circle: '' decimal: '' decimalΞleadingΞzero: '' /** A filled circle. */ disc: '' georgian: '' /** The marker box is outside the principal block box, as described in the section on the ::marker pseudo-element below. */ inside: '' lowerΞalpha: '' lowerΞgreek: '' lowerΞlatin: '' lowerΞroman: '' none: '' /** The ::marker pseudo-element is an inline element placed immediately before all ::before pseudo-elements in the principal block box, after which the element's content flows. */ outside: '' /** A filled square. */ square: '' /** Allows a counter style to be defined inline. */ symbols(): '' upperΞalpha: '' upperΞlatin: '' upperΞroman: '' url(): '' } /** * Allows italic or oblique faces to be selected. Italic forms are generally cursive in nature while oblique faces are typically sloped versions of the regular face. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/font-style) * */ interface fontΞstyle extends _ { set(val: this): void; /** Selects a font that is labeled as an 'italic' face, or an 'oblique' face if one is not */ italic: '' /** Selects a face that is classified as 'normal'. */ normal: '' /** Selects a font that is labeled as an 'oblique' face, or an 'italic' face if one is not. */ oblique: '' } /** * Shorthand property for setting 'font-style', 'font-variant', 'font-weight', 'font-size', 'line-height', and 'font-family', at the same place in the style sheet. The syntax of this property is based on a traditional typographical shorthand notation to set multiple properties related to fonts. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/font) * */ interface font extends _ { set(val: this | Ψfont): void; /** Thin */ 100: '' /** Extra Light (Ultra Light) */ 200: '' /** Light */ 300: '' /** Normal */ 400: '' /** Medium */ 500: '' /** Semi Bold (Demi Bold) */ 600: '' /** Bold */ 700: '' /** Extra Bold (Ultra Bold) */ 800: '' /** Black (Heavy) */ 900: '' /** Same as 700 */ bold: '' /** Specifies the weight of the face bolder than the inherited value. */ bolder: '' /** The font used for captioned controls (e.g., buttons, drop-downs, etc.). */ caption: '' /** The font used to label icons. */ icon: '' /** Selects a font that is labeled 'italic', or, if that is not available, one labeled 'oblique'. */ italic: '' large: '' larger: '' /** Specifies the weight of the face lighter than the inherited value. */ lighter: '' medium: '' /** The font used in menus (e.g., dropdown menus and menu lists). */ menu: '' /** The font used in dialog boxes. */ messageΞbox: '' /** Specifies a face that is not labeled as a small-caps font. */ normal: '' /** Selects a font that is labeled 'oblique'. */ oblique: '' small: '' /** Specifies a font that is labeled as a small-caps font. If a genuine small-caps font is not available, user agents should simulate a small-caps font. */ smallΞcaps: '' /** The font used for labeling small controls. */ smallΞcaption: '' smaller: '' /** The font used in window status bars. */ statusΞbar: '' xΞlarge: '' xΞsmall: '' xxΞlarge: '' xxΞsmall: '' } /** * Shorthand property for setting border width, style and color * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-left) * * @alias bdl */ interface borderΞleft extends _ { set(val: Ψlength | ΨlineΞwidth | ΨlineΞstyle | Ψcolor): void; } /** @proxy borderΞleft */ interface bdl extends borderΞleft { } /** * Shorthand property for setting border width, style and color * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-right) * * @alias bdr */ interface borderΞright extends _ { set(val: Ψlength | ΨlineΞwidth | ΨlineΞstyle | Ψcolor): void; } /** @proxy borderΞright */ interface bdr extends borderΞright { } /** * Text can overflow for example when it is prevented from wrapping. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/text-overflow) * */ interface textΞoverflow extends _ { set(val: this | Ψstring, arg1: any): void; /** Clip inline content that overflows. Characters may be only partially rendered. */ clip: '' /** Render an ellipsis character (U+2026) to represent clipped inline content. */ ellipsis: '' } /** * Shorthand that sets the four 'border-*-width' properties. If it has four values, they set top, right, bottom and left in that order. If left is missing, it is the same as right; if bottom is missing, it is the same as top; if right is missing, it is the same as top. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-width) * * @alias bw */ interface borderΞwidth extends _ { set(val: Ψlength | ΨlineΞwidth, arg1: any, arg2: any, arg3: any): void; } /** @proxy borderΞwidth */ interface bw extends borderΞwidth { } /** * Aligns flex items along the main axis of the current line of the flex container. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content) * * @alias jc */ interface justifyΞcontent extends _ { set(val: this): void; /** Flex items are packed toward the center of the line. */ center: '' /** The items are packed flush to each other toward the start edge of the alignment container in the main axis. */ start: '' /** The items are packed flush to each other toward the end edge of the alignment container in the main axis. */ end: '' /** The items are packed flush to each other toward the left edge of the alignment container in the main axis. */ left: '' /** The items are packed flush to each other toward the right edge of the alignment container in the main axis. */ right: '' /** If the size of the item overflows the alignment container, the item is instead aligned as if the alignment mode were start. */ safe: '' /** Regardless of the relative sizes of the item and alignment container, the given alignment value is honored. */ unsafe: '' /** If the combined size of the alignment subjects is less than the size of the alignment container, any auto-sized alignment subjects have their size increased equally (not proportionally), while still respecting the constraints imposed by max-height/max-width (or equivalent functionality), so that the combined size exactly fills the alignment container. */ stretch: '' /** The items are evenly distributed within the alignment container along the main axis. */ spaceΞevenly: '' /** Flex items are packed toward the end of the line. */ flexΞend: '' /** Flex items are packed toward the start of the line. */ flexΞstart: '' /** Flex items are evenly distributed in the line, with half-size spaces on either end. */ spaceΞaround: '' /** Flex items are evenly distributed in the line. */ spaceΞbetween: '' /** Specifies participation in first-baseline alignment. */ baseline: '' /** Specifies participation in first-baseline alignment. */ 'first baseline': '' /** Specifies participation in last-baseline alignment. */ 'last baseline': '' } /** @proxy justifyΞcontent */ interface jc extends justifyΞcontent { } /** * Aligns flex items along the cross axis of the current line of the flex container. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/align-items) * * @alias ai */ interface alignΞitems extends _ { set(val: this): void; /** If the flex item’s inline axis is the same as the cross axis, this value is identical to 'flex-start'. Otherwise, it participates in baseline alignment. */ baseline: '' /** The flex item’s margin box is centered in the cross axis within the line. */ center: '' /** The cross-end margin edge of the flex item is placed flush with the cross-end edge of the line. */ flexΞend: '' /** The cross-start margin edge of the flex item is placed flush with the cross-start edge of the line. */ flexΞstart: '' /** If the cross size property of the flex item computes to auto, and neither of the cross-axis margins are auto, the flex item is stretched. */ stretch: '' } /** @proxy alignΞitems */ interface ai extends alignΞitems { } /** * Specifies the handling of overflow in the vertical direction. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/overflow-y) * * @alias ofy */ interface overflowΞy extends _ { set(val: this): void; /** The behavior of the 'auto' value is UA-dependent, but should cause a scrolling mechanism to be provided for overflowing boxes. */ auto: '' /** Content is clipped and no scrolling mechanism should be provided to view the content outside the clipping region. */ hidden: '' /** Content is clipped and if the user agent uses a scrolling mechanism that is visible on the screen (such as a scroll bar or a panner), that mechanism should be displayed for a box whether or not any of its content is clipped. */ scroll: '' /** Content is not clipped, i.e., it may be rendered outside the content box. */ visible: '' } /** @proxy overflowΞy */ interface ofy extends overflowΞy { } /** * Specifies under what circumstances a given element can be the target element for a pointer event. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events) * * @alias pe */ interface pointerΞevents extends _ { set(val: this): void; /** The given element can be the target element for pointer events whenever the pointer is over either the interior or the perimeter of the element. */ all: '' /** The given element can be the target element for pointer events whenever the pointer is over the interior of the element. */ fill: '' /** The given element does not receive pointer events. */ none: '' /** The given element can be the target element for pointer events when the pointer is over a "painted" area. */ painted: '' /** The given element can be the target element for pointer events whenever the pointer is over the perimeter of the element. */ stroke: '' /** The given element can be the target element for pointer events when the ‘visibility’ property is set to visible and the pointer is over either the interior or the perimete of the element. */ visible: '' /** The given element can be the target element for pointer events when the ‘visibility’ property is set to visible and when the pointer is over the interior of the element. */ visibleFill: '' /** The given element can be the target element for pointer events when the ‘visibility’ property is set to visible and when the pointer is over a ‘painted’ area. */ visiblePainted: '' /** The given element can be the target element for pointer events when the ‘visibility’ property is set to visible and when the pointer is over the perimeter of the element. */ visibleStroke: '' } /** @proxy pointerΞevents */ interface pe extends pointerΞevents { } /** * The style of the border around edges of an element. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-style) * * @alias bs */ interface borderΞstyle extends _ { set(val: ΨlineΞstyle): void; } /** @proxy borderΞstyle */ interface bs extends borderΞstyle { } /** * Specifies the minimum, maximum, and optimal spacing between grapheme clusters. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/letter-spacing) * * @alias ls */ interface letterΞspacing extends _ { set(val: this | Ψlength): void; /** The spacing is the normal spacing for the current font. It is typically zero-length. */ normal: '' } /** @proxy letterΞspacing */ interface ls extends letterΞspacing { } /** * Shorthand property combines six of the animation properties into a single property. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/animation) * */ interface animation extends _ { set(val: this | Ψtime | ΨeasingΞfunction | Ψidentifier | Ψnumber, arg1: any, arg2: any, arg3: any): void; /** The animation cycle iterations that are odd counts are played in the normal direction, and the animation cycle iterations that are even counts are played in a reverse direction. */ alternate: '' /** The animation cycle iterations that are odd counts are played in the reverse direction, and the animation cycle iterations that are even counts are played in a normal direction. */ alternateΞreverse: '' /** The beginning property value (as defined in the first @keyframes at-rule) is applied before the animation is displayed, during the period defined by 'animation-delay'. */ backwards: '' /** Both forwards and backwards fill modes are applied. */ both: '' /** The final property value (as defined in the last @keyframes at-rule) is maintained after the animation completes. */ forwards: '' /** Causes the animation to repeat forever. */ infinite: '' /** No animation is performed */ none: '' /** Normal playback. */ normal: '' /** All iterations of the animation are played in the reverse direction from the way they were specified. */ reverse: '' } /** * Specifies the handling of overflow in the horizontal direction. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/overflow-x) * * @alias ofx */ interface overflowΞx extends _ { set(val: this): void; /** The behavior of the 'auto' value is UA-dependent, but should cause a scrolling mechanism to be provided for overflowing boxes. */ auto: '' /** Content is clipped and no scrolling mechanism should be provided to view the content outside the clipping region. */ hidden: '' /** Content is clipped and if the user agent uses a scrolling mechanism that is visible on the screen (such as a scroll bar or a panner), that mechanism should be displayed for a box whether or not any of its content is clipped. */ scroll: '' /** Content is not clipped, i.e., it may be rendered outside the content box. */ visible: '' } /** @proxy overflowΞx */ interface ofx extends overflowΞx { } /** * Specifies how flex items are placed in the flex container, by setting the direction of the flex container’s main axis. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/flex-direction) * * @alias fld */ interface flexΞdirection extends _ { set(val: this): void; /** The flex container’s main axis has the same orientation as the block axis of the current writing mode. */ column: '' /** Same as 'column', except the main-start and main-end directions are swapped. */ columnΞreverse: '' /** The flex container’s main axis has the same orientation as the inline axis of the current writing mode. */ row: '' /** Same as 'row', except the main-start and main-end directions are swapped. */ rowΞreverse: '' } /** @proxy flexΞdirection */ interface fld extends flexΞdirection { } /** * Specifies whether the UA may break within a word to prevent overflow when an otherwise-unbreakable string is too long to fit. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/word-wrap) * */ interface wordΞwrap extends _ { set(val: this): void; /** An otherwise unbreakable sequence of characters may be broken at an arbitrary point if there are no otherwise-acceptable break points in the line. */ breakΞword: '' /** Lines may break only at allowed break points. */ normal: '' } /** * Specifies the components of a flexible length: the flex grow factor and flex shrink factor, and the flex basis. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/flex) * * @alias fl */ interface flex extends _ { set(val: this | Ψlength | Ψnumber | Ψpercentage): void; /** Retrieves the value of the main size property as the used 'flex-basis'. */ auto: '' /** Indicates automatic sizing, based on the flex item’s content. */ content: '' /** Expands to '0 0 auto'. */ none: '' } /** @proxy flex */ interface fl extends flex { } /** * Selects a table's border model. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-collapse) * */ interface borderΞcollapse extends _ { set(val: this): void; /** Selects the collapsing borders model. */ collapse: '' /** Selects the separated borders border model. */ separate: '' } /** * Non-standard. Specifies the magnification scale of the object. See 'transform: scale()' for a standards-based alternative. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/zoom) * */ interface zoom extends _ { set(val: this | Ψinteger | Ψnumber | Ψpercentage): void; normal: '' } /** * Used to construct the default contents of a list item’s marker * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/list-style-type) * */ interface listΞstyleΞtype extends _ { set(val: this | Ψstring): void; /** Traditional uppercase Armenian numbering. */ armenian: '' /** A hollow circle. */ circle: '' /** Western decimal numbers. */ decimal: '' /** Decimal numbers padded by initial zeros. */ decimalΞleadingΞzero: '' /** A filled circle. */ disc: '' /** Traditional Georgian numbering. */ georgian: '' /** Lowercase ASCII letters. */ lowerΞalpha: '' /** Lowercase classical Greek. */ lowerΞgreek: '' /** Lowercase ASCII letters. */ lowerΞlatin: '' /** Lowercase ASCII Roman numerals. */ lowerΞroman: '' /** No marker */ none: '' /** A filled square. */ square: '' /** Allows a counter style to be defined inline. */ symbols(): '' /** Uppercase ASCII letters. */ upperΞalpha: '' /** Uppercase ASCII letters. */ upperΞlatin: '' /** Uppercase ASCII Roman numerals. */ upperΞroman: '' } /** * Defines the radii of the bottom left outer border edge. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-bottom-left-radius) * * @alias rdbl */ interface borderΞbottomΞleftΞradius extends _ { set(val: Ψradius | Ψlength | Ψpercentage, arg1: any): void; } /** @proxy borderΞbottomΞleftΞradius */ interface rdbl extends borderΞbottomΞleftΞradius { } /** * Paints the interior of the given graphical element. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/fill) * */ interface fill extends _ { set(val: this | Ψcolor | Ψurl): void; /** A URL reference to a paint server element, which is an element that defines a paint server: ‘hatch’, ‘linearGradient’, ‘mesh’, ‘pattern’, ‘radialGradient’ and ‘solidcolor’. */ url(): '' /** No paint is applied in this layer. */ none: '' } /** * Establishes the origin of transformation for an element. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/transform-origin) * * @alias origin */ interface transformΞorigin extends _ { set(val: Ψposition | Ψlength | Ψpercentage): void; } /** @proxy transformΞorigin */ interface origin extends transformΞorigin { } /** * Controls whether the flex container is single-line or multi-line, and the direction of the cross-axis, which determines the direction new lines are stacked in. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/flex-wrap) * * @alias flw */ interface flexΞwrap extends _ { set(val: this): void; /** The flex container is single-line. */ nowrap: '' /** The flexbox is multi-line. */ wrap: '' /** Same as 'wrap', except the cross-start and cross-end directions are swapped. */ wrapΞreverse: '' } /** @proxy flexΞwrap */ interface flw extends flexΞwrap { } /** * Enables shadow effects to be applied to the text of the element. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow) * * @alias ts */ interface textΞshadow extends _ { set(val: this | Ψlength | Ψcolor): void; /** No shadow. */ none: '' } /** @proxy textΞshadow */ interface ts extends textΞshadow { } /** * Defines the radii of the top left outer border edge. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-top-left-radius) * * @alias rdtl */ interface borderΞtopΞleftΞradius extends _ { set(val: Ψradius | Ψlength | Ψpercentage, arg1: any): void; } /** @proxy borderΞtopΞleftΞradius */ interface rdtl extends borderΞtopΞleftΞradius { } /** * Controls the appearance of selection. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/user-select) * * @alias us */ interface userΞselect extends _ { set(val: this): void; /** The content of the element must be selected atomically */ all: '' auto: '' /** UAs must not allow a selection which is started in this element to be extended outside of this element. */ contain: '' /** The UA must not allow selections to be started in this element. */ none: '' /** The element imposes no constraint on the selection. */ text: '' } /** @proxy userΞselect */ interface us extends userΞselect { } /** * Deprecated. Use the 'clip-path' property when support allows. Defines the visible portion of an element’s box. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/clip) * */ interface clip extends _ { set(val: this): void; /** The element does not clip. */ auto: '' /** Specifies offsets from the edges of the border box. */ rect(): '' } /** * Defines the radii of the bottom right outer border edge. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-bottom-right-radius) * * @alias rdbr */ interface borderΞbottomΞrightΞradius extends _ { set(val: Ψradius | Ψlength | Ψpercentage, arg1: any): void; } /** @proxy borderΞbottomΞrightΞradius */ interface rdbr extends borderΞbottomΞrightΞradius { } /** * Specifies line break opportunities for non-CJK scripts. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/word-break) * */ interface wordΞbreak extends _ { set(val: this): void; /** Lines may break between any two grapheme clusters for non-CJK scripts. */ breakΞall: '' /** Block characters can no longer create implied break points. */ keepΞall: '' /** Breaks non-CJK scripts according to their own rules. */ normal: '' } /** * Defines the radii of the top right outer border edge. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-top-right-radius) * * @alias rdtr */ interface borderΞtopΞrightΞradius extends _ { set(val: Ψradius | Ψlength | Ψpercentage, arg1: any): void; } /** @proxy borderΞtopΞrightΞradius */ interface rdtr extends borderΞtopΞrightΞradius { } /** * Sets the flex grow factor. Negative numbers are invalid. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/flex-grow) * * @alias flg */ interface flexΞgrow extends _ { set(val: Ψnumber): void; } /** @proxy flexΞgrow */ interface flg extends flexΞgrow { } /** * Sets the color of the top border. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-top-color) * * @alias bct */ interface borderΞtopΞcolor extends _ { set(val: Ψcolor): void; } /** @proxy borderΞtopΞcolor */ interface bct extends borderΞtopΞcolor { } /** * Sets the color of the bottom border. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-bottom-color) * * @alias bcb */ interface borderΞbottomΞcolor extends _ { set(val: Ψcolor): void; } /** @proxy borderΞbottomΞcolor */ interface bcb extends borderΞbottomΞcolor { } /** * Sets the flex shrink factor. Negative numbers are invalid. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/flex-shrink) * * @alias fls */ interface flexΞshrink extends _ { set(val: Ψnumber): void; } /** @proxy flexΞshrink */ interface fls extends flexΞshrink { } /** * The creator of SVG content might want to provide a hint to the implementation about what tradeoffs to make as it renders text. The ‘text-rendering’ property provides these hints. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/text-rendering) * */ interface textΞrendering extends _ { set(val: this): void; auto: '' /** Indicates that the user agent shall emphasize geometric precision over legibility and rendering speed. */ geometricPrecision: '' /** Indicates that the user agent shall emphasize legibility over rendering speed and geometric precision. */ optimizeLegibility: '' /** Indicates that the user agent shall emphasize rendering speed over legibility and geometric precision. */ optimizeSpeed: '' } /** * Allows the default alignment along the cross axis to be overridden for individual flex items. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/align-self) * * @alias as */ interface alignΞself extends _ { set(val: this): void; /** Computes to the value of 'align-items' on the element’s parent, or 'stretch' if the element has no parent. On absolutely positioned elements, it computes to itself. */ auto: '' /** If the flex item’s inline axis is the same as the cross axis, this value is identical to 'flex-start'. Otherwise, it participates in baseline alignment. */ baseline: '' /** The flex item’s margin box is centered in the cross axis within the line. */ center: '' /** The cross-end margin edge of the flex item is placed flush with the cross-end edge of the line. */ flexΞend: '' /** The cross-start margin edge of the flex item is placed flush with the cross-start edge of the line. */ flexΞstart: '' /** If the cross size property of the flex item computes to auto, and neither of the cross-axis margins are auto, the flex item is stretched. */ stretch: '' } /** @proxy alignΞself */ interface as extends alignΞself { } /** * Specifies the indentation applied to lines of inline content in a block. The indentation only affects the first line of inline content in the block unless the 'hanging' keyword is specified, in which case it affects all lines except the first. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/text-indent) * */ interface textΞindent extends _ { set(val: Ψpercentage | Ψlength): void; } /** * Describes how the animation will progress over one cycle of its duration. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/animation-timing-function) * */ interface animationΞtimingΞfunction extends _ { set(val: ΨeasingΞfunction, arg1: any, arg2: any, arg3: any): void; } /** * The lengths specify the distance that separates adjoining cell borders. If one length is specified, it gives both the horizontal and vertical spacing. If two are specified, the first gives the horizontal spacing and the second the vertical spacing. Lengths may not be negative. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-spacing) * */ interface borderΞspacing extends _ { set(val: Ψlength): void; } /** * Specifies the inline base direction or directionality of any bidi paragraph, embedding, isolate, or override established by the box. Note: for HTML content use the 'dir' attribute and 'bdo' element rather than this property. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/direction) * */ interface direction extends _ { set(val: this): void; /** Left-to-right direction. */ ltr: '' /** Right-to-left direction. */ rtl: '' } /** * Determines the background painting area. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/background-clip) * * @alias bgclip */ interface backgroundΞclip extends _ { set(val: Ψbox, arg1: any, arg2: any, arg3: any): void; } /** @proxy backgroundΞclip */ interface bgclip extends backgroundΞclip { } /** * Sets the color of the left border. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-left-color) * * @alias bcl */ interface borderΞleftΞcolor extends _ { set(val: Ψcolor): void; } /** @proxy borderΞleftΞcolor */ interface bcl extends borderΞleftΞcolor { } /** * `@font-face` descriptor. Specifies the resource containing font data. It is required, whether the font is downloadable or locally installed. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/src) * */ interface src extends _ { set(val: this | Ψurl | Ψidentifier, arg1: any, arg2: any, arg3: any): void; /** Reference font by URL */ url(): '' /** Optional hint describing the format of the font resource. */ format(): '' /** Format-specific string that identifies a locally available copy of a given font. */ local(): '' } /** * Determines whether touch input may trigger default behavior supplied by user agent. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/touch-action) * */ interface touchΞaction extends _ { set(val: this): void; /** The user agent may determine any permitted touch behaviors for touches that begin on the element. */ auto: '' crossΞslideΞx: '' crossΞslideΞy: '' doubleΞtapΞzoom: '' /** The user agent may consider touches that begin on the element only for the purposes of scrolling and continuous zooming. */ manipulation: '' /** Touches that begin on the element must not trigger default touch behaviors. */ none: '' /** The user agent may consider touches that begin on the element only for the purposes of horizontally scrolling the element’s nearest ancestor with horizontally scrollable content. */ panΞx: '' /** The user agent may consider touches that begin on the element only for the purposes of vertically scrolling the element’s nearest ancestor with vertically scrollable content. */ panΞy: '' pinchΞzoom: '' } /** * Sets the color of the right border. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-right-color) * * @alias bcr */ interface borderΞrightΞcolor extends _ { set(val: Ψcolor): void; } /** @proxy borderΞrightΞcolor */ interface bcr extends borderΞrightΞcolor { } /** * Specifies the name of the CSS property to which the transition is applied. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/transition-property) * */ interface transitionΞproperty extends _ { set(val: this | Ψproperty): void; /** Every property that is able to undergo a transition will do so. */ all: '' /** No property will transition. */ none: '' } /** * Defines a list of animations that apply. Each name is used to select the keyframe at-rule that provides the property values for the animation. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/animation-name) * */ interface animationΞname extends _ { set(val: this | Ψidentifier, arg1: any, arg2: any, arg3: any): void; /** No animation is performed */ none: '' } /** * Processes an element’s rendering before it is displayed in the document, by applying one or more filter effects. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/filter) * */ interface filter extends _ { set(val: this | Ψurl): void; /** No filter effects are applied. */ none: '' /** Applies a Gaussian blur to the input image. */ blur(): '' /** Applies a linear multiplier to input image, making it appear more or less bright. */ brightness(): '' /** Adjusts the contrast of the input. */ contrast(): '' /** Applies a drop shadow effect to the input image. */ dropΞshadow(): '' /** Converts the input image to grayscale. */ grayscale(): '' /** Applies a hue rotation on the input image. */ hueΞrotate(): '' /** Inverts the samples in the input image. */ invert(): '' /** Applies transparency to the samples in the input image. */ opacity(): '' /** Saturates the input image. */ saturate(): '' /** Converts the input image to sepia. */ sepia(): '' /** A filter reference to a <filter> element. */ url(): '' } /** * Defines the length of time that an animation takes to complete one cycle. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/animation-duration) * */ interface animationΞduration extends _ { set(val: Ψtime, arg1: any, arg2: any, arg3: any): void; } /** * Specifies whether the UA may break within a word to prevent overflow when an otherwise-unbreakable string is too long to fit within the line box. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/overflow-wrap) * */ interface overflowΞwrap extends _ { set(val: this): void; /** An otherwise unbreakable sequence of characters may be broken at an arbitrary point if there are no otherwise-acceptable break points in the line. */ breakΞword: '' /** Lines may break only at allowed break points. */ normal: '' } /** * Defines when the transition will start. It allows a transition to begin execution some period of time from when it is applied. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/transition-delay) * */ interface transitionΞdelay extends _ { set(val: Ψtime, arg1: any, arg2: any, arg3: any): void; } /** * Paints along the outline of the given graphical element. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/stroke) * */ interface stroke extends _ { set(val: this | Ψcolor | Ψurl): void; /** A URL reference to a paint server element, which is an element that defines a paint server: ‘hatch’, ‘linearGradient’, ‘mesh’, ‘pattern’, ‘radialGradient’ and ‘solidcolor’. */ url(): '' /** No paint is applied in this layer. */ none: '' } /** * Specifies variant representations of the font * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/font-variant) * */ interface fontΞvariant extends _ { set(val: this): void; /** Specifies a face that is not labeled as a small-caps font. */ normal: '' /** Specifies a font that is labeled as a small-caps font. If a genuine small-caps font is not available, user agents should simulate a small-caps font. */ smallΞcaps: '' } /** * Sets the thickness of the bottom border. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-bottom-width) * * @alias bwb */ interface borderΞbottomΞwidth extends _ { set(val: Ψlength | ΨlineΞwidth): void; } /** @proxy borderΞbottomΞwidth */ interface bwb extends borderΞbottomΞwidth { } /** * Defines when the animation will start. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/animation-delay) * */ interface animationΞdelay extends _ { set(val: Ψtime, arg1: any, arg2: any, arg3: any): void; } /** * Sets the thickness of the top border. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-top-width) * * @alias bwt */ interface borderΞtopΞwidth extends _ { set(val: Ψlength | ΨlineΞwidth): void; } /** @proxy borderΞtopΞwidth */ interface bwt extends borderΞtopΞwidth { } /** * Specifies how long the transition from the old value to the new value should take. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/transition-duration) * */ interface transitionΞduration extends _ { set(val: Ψtime, arg1: any, arg2: any, arg3: any): void; } /** * Sets the flex basis. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/flex-basis) * * @alias flb */ interface flexΞbasis extends _ { set(val: this | Ψlength | Ψnumber | Ψpercentage): void; /** Retrieves the value of the main size property as the used 'flex-basis'. */ auto: '' /** Indicates automatic sizing, based on the flex item’s content. */ content: '' } /** @proxy flexΞbasis */ interface flb extends flexΞbasis { } /** * Provides a rendering hint to the user agent, stating what kinds of changes the author expects to perform on the element. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/will-change) * */ interface willΞchange extends _ { set(val: this | Ψidentifier): void; /** Expresses no particular intent. */ auto: '' /** Indicates that the author expects to animate or change something about the element’s contents in the near future. */ contents: '' /** Indicates that the author expects to animate or change the scroll position of the element in the near future. */ scrollΞposition: '' } /** * Defines what values are applied by the animation outside the time it is executing. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/animation-fill-mode) * */ interface animationΞfillΞmode extends _ { set(val: this, arg1: any, arg2: any, arg3: any): void; /** The beginning property value (as defined in the first @keyframes at-rule) is applied before the animation is displayed, during the period defined by 'animation-delay'. */ backwards: '' /** Both forwards and backwards fill modes are applied. */ both: '' /** The final property value (as defined in the last @keyframes at-rule) is maintained after the animation completes. */ forwards: '' /** There is no change to the property value between the time the animation is applied and the time the animation begins playing or after the animation completes. */ none: '' } /** * Width of the outline. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/outline-width) * */ interface outlineΞwidth extends _ { set(val: Ψlength | ΨlineΞwidth): void; } /** * Controls the algorithm used to lay out the table cells, rows, and columns. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/table-layout) * */ interface tableΞlayout extends _ { set(val: this): void; /** Use any automatic table layout algorithm. */ auto: '' /** Use the fixed table layout algorithm. */ fixed: '' } /** * Specifies how the contents of a replaced element should be scaled relative to the box established by its used height and width. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) * */ interface objectΞfit extends _ { set(val: this): void; /** The replaced content is sized to maintain its aspect ratio while fitting within the element’s content box: its concrete object size is resolved as a contain constraint against the element's used width and height. */ contain: '' /** The replaced content is sized to maintain its aspect ratio while filling the element's entire content box: its concrete object size is resolved as a cover constraint against the element’s used width and height. */ cover: '' /** The replaced content is sized to fill the element’s content box: the object's concrete object size is the element's used width and height. */ fill: '' /** The replaced content is not resized to fit inside the element's content box */ none: '' /** Size the content as if ‘none’ or ‘contain’ were specified, whichever would result in a smaller concrete object size. */ scaleΞdown: '' } /** * Controls the order in which children of a flex container appear within the flex container, by assigning them to ordinal groups. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/order) * */ interface order extends _ { set(val: Ψinteger): void; } /** * Describes how the intermediate values used during a transition will be calculated. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/transition-timing-function) * */ interface transitionΞtimingΞfunction extends _ { set(val: ΨeasingΞfunction, arg1: any, arg2: any, arg3: any): void; } /** * Specifies whether or not an element is resizable by the user, and if so, along which axis/axes. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/resize) * */ interface resize extends _ { set(val: this): void; /** The UA presents a bidirectional resizing mechanism to allow the user to adjust both the height and the width of the element. */ both: '' /** The UA presents a unidirectional horizontal resizing mechanism to allow the user to adjust only the width of the element. */ horizontal: '' /** The UA does not present a resizing mechanism on the element, and the user is given no direct manipulation mechanism to resize the element. */ none: '' /** The UA presents a unidirectional vertical resizing mechanism to allow the user to adjust only the height of the element. */ vertical: '' } /** * Style of the outline. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/outline-style) * */ interface outlineΞstyle extends _ { set(val: this | ΨlineΞstyle): void; /** Permits the user agent to render a custom outline style, typically the default platform style. */ auto: '' } /** * Sets the thickness of the right border. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-right-width) * * @alias bwr */ interface borderΞrightΞwidth extends _ { set(val: Ψlength | ΨlineΞwidth): void; } /** @proxy borderΞrightΞwidth */ interface bwr extends borderΞrightΞwidth { } /** * Specifies the width of the stroke on the current object. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/stroke-width) * */ interface strokeΞwidth extends _ { set(val: Ψpercentage | Ψlength): void; } /** * Defines the number of times an animation cycle is played. The default value is one, meaning the animation will play from beginning to end once. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/animation-iteration-count) * */ interface animationΞiterationΞcount extends _ { set(val: this | Ψnumber, arg1: any, arg2: any, arg3: any): void; /** Causes the animation to repeat forever. */ infinite: '' } /** * Aligns a flex container’s lines within the flex container when there is extra space in the cross-axis, similar to how 'justify-content' aligns individual items within the main-axis. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/align-content) * * @alias ac */ interface alignΞcontent extends _ { set(val: this): void; /** Lines are packed toward the center of the flex container. */ center: '' /** Lines are packed toward the end of the flex container. */ flexΞend: '' /** Lines are packed toward the start of the flex container. */ flexΞstart: '' /** Lines are evenly distributed in the flex container, with half-size spaces on either end. */ spaceΞaround: '' /** Lines are evenly distributed in the flex container. */ spaceΞbetween: '' /** Lines stretch to take up the remaining space. */ stretch: '' } /** @proxy alignΞcontent */ interface ac extends alignΞcontent { } /** * Offset the outline and draw it beyond the border edge. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/outline-offset) * */ interface outlineΞoffset extends _ { set(val: Ψlength): void; } /** * Determines whether or not the 'back' side of a transformed element is visible when facing the viewer. With an identity transform, the front side of an element faces the viewer. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/backface-visibility) * */ interface backfaceΞvisibility extends _ { set(val: this): void; /** Back side is hidden. */ hidden: '' /** Back side is visible. */ visible: '' } /** * Sets the thickness of the left border. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-left-width) * * @alias bwl */ interface borderΞleftΞwidth extends _ { set(val: Ψlength | ΨlineΞwidth): void; } /** @proxy borderΞleftΞwidth */ interface bwl extends borderΞleftΞwidth { } /** * Specifies how flexbox items are placed in the flexbox. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/flex-flow) * * @alias flf */ interface flexΞflow extends _ { set(val: this): void; /** The flex container’s main axis has the same orientation as the block axis of the current writing mode. */ column: '' /** Same as 'column', except the main-start and main-end directions are swapped. */ columnΞreverse: '' /** The flex container is single-line. */ nowrap: '' /** The flex container’s main axis has the same orientation as the inline axis of the current writing mode. */ row: '' /** Same as 'row', except the main-start and main-end directions are swapped. */ rowΞreverse: '' /** The flexbox is multi-line. */ wrap: '' /** Same as 'wrap', except the cross-start and cross-end directions are swapped. */ wrapΞreverse: '' } /** @proxy flexΞflow */ interface flf extends flexΞflow { } /** * Changes the appearance of buttons and other controls to resemble native controls. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/appearance) * */ interface appearance extends _ { set(val: any): void; } /** * The level of embedding with respect to the bidirectional algorithm. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/unicode-bidi) * */ interface unicodeΞbidi extends _ { set(val: this): void; /** Inside the element, reordering is strictly in sequence according to the 'direction' property; the implicit part of the bidirectional algorithm is ignored. */ bidiΞoverride: '' /** If the element is inline-level, this value opens an additional level of embedding with respect to the bidirectional algorithm. The direction of this embedding level is given by the 'direction' property. */ embed: '' /** The contents of the element are considered to be inside a separate, independent paragraph. */ isolate: '' /** This combines the isolation behavior of 'isolate' with the directional override behavior of 'bidi-override' */ isolateΞoverride: '' /** The element does not open an additional level of embedding with respect to the bidirectional algorithm. For inline-level elements, implicit reordering works across element boundaries. */ normal: '' /** For the purposes of the Unicode bidirectional algorithm, the base directionality of each bidi paragraph for which the element forms the containing block is determined not by the element's computed 'direction'. */ plaintext: '' } /** * Controls the pattern of dashes and gaps used to stroke paths. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/stroke-dasharray) * */ interface strokeΞdasharray extends _ { set(val: this | Ψlength | Ψpercentage | Ψnumber): void; /** Indicates that no dashing is used. */ none: '' } /** * Specifies the distance into the dash pattern to start the dash. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/stroke-dashoffset) * */ interface strokeΞdashoffset extends _ { set(val: Ψpercentage | Ψlength): void; } /** * `@font-face` descriptor. Defines the set of Unicode codepoints that may be supported by the font face for which it is declared. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/unicode-range) * */ interface unicodeΞrange extends _ { set(val: this | ΨunicodeΞrange): void; /** Ampersand. */ 'U+26': '' /** Basic Latin (ASCII). */ 'U+00Ξ7F': '' /** Latin-1 Supplement. Accented characters for Western European languages, common punctuation characters, multiplication and division signs. */ 'U+80ΞFF': '' /** Latin Extended-A. Accented characters for for Czech, Dutch, Polish, and Turkish. */ 'U+100Ξ17F': '' /** Latin Extended-B. Croatian, Slovenian, Romanian, Non-European and historic latin, Khoisan, Pinyin, Livonian, Sinology. */ 'U+180Ξ24F': '' /** Latin Extended Additional. Vietnamese, German captial sharp s, Medievalist, Latin general use. */ 'U+1E00Ξ1EFF': '' /** International Phonetic Alphabet Extensions. */ 'U+250Ξ2AF': '' /** Greek and Coptic. */ 'U+370Ξ3FF': '' /** Greek Extended. Accented characters for polytonic Greek. */ 'U+1F00Ξ1FFF': '' /** Cyrillic. */ 'U+400Ξ4FF': '' /** Cyrillic Supplement. Extra letters for Komi, Khanty, Chukchi, Mordvin, Kurdish, Aleut, Chuvash, Abkhaz, Azerbaijani, and Orok. */ 'U+500Ξ52F': '' /** Armenian. */ 'U+530–58F': '' /** Hebrew. */ 'U+590–5FF': '' /** Arabic. */ 'U+600–6FF': '' /** Arabic Supplement. Additional letters for African languages, Khowar, Torwali, Burushaski, and early Persian. */ 'U+750–77F': '' /** Arabic Extended-A. Additional letters for African languages, European and Central Asian languages, Rohingya, Tamazight, Arwi, and Koranic annotation signs. */ 'U+8A0–8FF': '' /** Syriac. */ 'U+700–74F': '' /** Devanagari. */ 'U+900–97F': '' /** Bengali. */ 'U+980–9FF': '' /** Gurmukhi. */ 'U+A00–A7F': '' /** Gujarati. */ 'U+A80–AFF': '' /** Oriya. */ 'U+B00–B7F': '' /** Tamil. */ 'U+B80–BFF': '' /** Telugu. */ 'U+C00–C7F': '' /** Kannada. */ 'U+C80–CFF': '' /** Malayalam. */ 'U+D00–D7F': '' /** Sinhala. */ 'U+D80–DFF': '' /** Warang Citi. */ 'U+118A0–118FF': '' /** Thai. */ 'U+E00–E7F': '' /** Tai Tham. */ 'U+1A20–1AAF': '' /** Tai Viet. */ 'U+AA80–AADF': '' /** Lao. */ 'U+E80–EFF': '' /** Tibetan. */ 'U+F00–FFF': '' /** Myanmar (Burmese). */ 'U+1000–109F': '' /** Georgian. */ 'U+10A0–10FF': '' /** Ethiopic. */ 'U+1200–137F': '' /** Ethiopic Supplement. Extra Syllables for Sebatbeit, and Tonal marks */ 'U+1380–139F': '' /** Ethiopic Extended. Extra Syllables for Me'en, Blin, and Sebatbeit. */ 'U+2D80–2DDF': '' /** Ethiopic Extended-A. Extra characters for Gamo-Gofa-Dawro, Basketo, and Gumuz. */ 'U+AB00–AB2F': '' /** Khmer. */ 'U+1780–17FF': '' /** Mongolian. */ 'U+1800–18AF': '' /** Sundanese. */ 'U+1B80–1BBF': '' /** Sundanese Supplement. Punctuation. */ 'U+1CC0–1CCF': '' /** CJK (Chinese, Japanese, Korean) Unified Ideographs. Most common ideographs for modern Chinese and Japanese. */ 'U+4E00–9FD5': '' /** CJK Unified Ideographs Extension A. Rare ideographs. */ 'U+3400–4DB5': '' /** Kangxi Radicals. */ 'U+2F00–2FDF': '' /** CJK Radicals Supplement. Alternative forms of Kangxi Radicals. */ 'U+2E80–2EFF': '' /** Hangul Jamo. */ 'U+1100–11FF': '' /** Hangul Syllables. */ 'U+AC00–D7AF': '' /** Hiragana. */ 'U+3040–309F': '' /** Katakana. */ 'U+30A0–30FF': '' /** Lisu. */ 'U+A4D0–A4FF': '' /** Yi Syllables. */ 'U+A000–A48F': '' /** Yi Radicals. */ 'U+A490–A4CF': '' /** General Punctuation. */ 'U+2000Ξ206F': '' /** CJK Symbols and Punctuation. */ 'U+3000–303F': '' /** Superscripts and Subscripts. */ 'U+2070–209F': '' /** Currency Symbols. */ 'U+20A0–20CF': '' /** Letterlike Symbols. */ 'U+2100–214F': '' /** Number Forms. */ 'U+2150–218F': '' /** Arrows. */ 'U+2190–21FF': '' /** Mathematical Operators. */ 'U+2200–22FF': '' /** Miscellaneous Technical. */ 'U+2300–23FF': '' /** Private Use Area. */ 'U+E000ΞF8FF': '' /** Alphabetic Presentation Forms. Ligatures for latin, Armenian, and Hebrew. */ 'U+FB00–FB4F': '' /** Arabic Presentation Forms-A. Contextual forms / ligatures for Persian, Urdu, Sindhi, Central Asian languages, etc, Arabic pedagogical symbols, word ligatures. */ 'U+FB50–FDFF': '' /** Emoji: Emoticons. */ 'U+1F600–1F64F': '' /** Emoji: Miscellaneous Symbols. */ 'U+2600–26FF': '' /** Emoji: Miscellaneous Symbols and Pictographs. */ 'U+1F300–1F5FF': '' /** Emoji: Supplemental Symbols and Pictographs. */ 'U+1F900–1F9FF': '' /** Emoji: Transport and Map Symbols. */ 'U+1F680–1F6FF': '' } /** * Specifies additional spacing between “words”. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/word-spacing) * */ interface wordΞspacing extends _ { set(val: this | Ψlength | Ψpercentage): void; /** No additional spacing is applied. Computes to zero. */ normal: '' } /** * The text-size-adjust CSS property controls the text inflation algorithm used on some smartphones and tablets. Other browsers will ignore this property. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/text-size-adjust) * */ interface textΞsizeΞadjust extends _ { set(val: any): void; } /** * Sets the style of the top border. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-top-style) * * @alias bst */ interface borderΞtopΞstyle extends _ { set(val: ΨlineΞstyle): void; } /** @proxy borderΞtopΞstyle */ interface bst extends borderΞtopΞstyle { } /** * Sets the style of the bottom border. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-bottom-style) * * @alias bsb */ interface borderΞbottomΞstyle extends _ { set(val: ΨlineΞstyle): void; } /** @proxy borderΞbottomΞstyle */ interface bsb extends borderΞbottomΞstyle { } /** * Defines whether or not the animation should play in reverse on alternate cycles. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/animation-direction) * */ interface animationΞdirection extends _ { set(val: this, arg1: any, arg2: any, arg3: any): void; /** The animation cycle iterations that are odd counts are played in the normal direction, and the animation cycle iterations that are even counts are played in a reverse direction. */ alternate: '' /** The animation cycle iterations that are odd counts are played in the reverse direction, and the animation cycle iterations that are even counts are played in a normal direction. */ alternateΞreverse: '' /** Normal playback. */ normal: '' /** All iterations of the animation are played in the reverse direction from the way they were specified. */ reverse: '' } /** * Provides a hint to the user-agent about what aspects of an image are most important to preserve when the image is scaled, to aid the user-agent in the choice of an appropriate scaling algorithm. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/image-rendering) * */ interface imageΞrendering extends _ { set(val: this): void; /** The image should be scaled with an algorithm that maximizes the appearance of the image. */ auto: '' /** The image must be scaled with an algorithm that preserves contrast and edges in the image, and which does not smooth colors or introduce blur to the image in the process. */ crispΞedges: '' ΞmozΞcrispΞedges: '' /** Deprecated. */ optimizeQuality: '' /** Deprecated. */ optimizeSpeed: '' /** When scaling the image up, the 'nearest neighbor' or similar algorithm must be used, so that the image appears to be simply composed of very large pixels. */ pixelated: '' } /** * Applies the same transform as the perspective(<number>) transform function, except that it applies only to the positioned or transformed children of the element, not to the transform on the element itself. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/perspective) * */ interface perspective extends _ { set(val: this | Ψlength): void; /** No perspective transform is applied. */ none: '' } /** * specifies, as a space-separated track list, the line names and track sizing functions of the grid. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template-columns) * * @alias gtc */ interface gridΞtemplateΞcolumns extends _ { set(val: this | Ψidentifier | Ψlength | Ψpercentage): void; /** There is no explicit grid; any rows/columns will be implicitly generated. */ none: '' /** Represents the largest min-content contribution of the grid items occupying the grid track. */ minΞcontent: '' /** Represents the largest max-content contribution of the grid items occupying the grid track. */ maxΞcontent: '' /** As a maximum, identical to 'max-content'. As a minimum, represents the largest minimum size (as specified by min-width/min-height) of the grid items occupying the grid track. */ auto: '' /** Indicates that the grid will align to its parent grid in that axis. */ subgrid: '' /** Defines a size range greater than or equal to min and less than or equal to max. */ minmax(): '' /** Represents a repeated fragment of the track list, allowing a large number of columns or rows that exhibit a recurring pattern to be written in a more compact form. */ repeat(): '' } /** @proxy gridΞtemplateΞcolumns */ interface gtc extends gridΞtemplateΞcolumns { } /** * Specifies the position of the '::marker' pseudo-element's box in the list item. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/list-style-position) * */ interface listΞstyleΞposition extends _ { set(val: this): void; /** The marker box is outside the principal block box, as described in the section on the ::marker pseudo-element below. */ inside: '' /** The ::marker pseudo-element is an inline element placed immediately before all ::before pseudo-elements in the principal block box, after which the element's content flows. */ outside: '' } /** * Provides low-level control over OpenType font features. It is intended as a way of providing access to font features that are not widely used but are needed for a particular use case. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/font-feature-settings) * */ interface fontΞfeatureΞsettings extends _ { set(val: this | Ψstring | Ψinteger): void; /** No change in glyph substitution or positioning occurs. */ normal: '' /** Disable feature. */ off: '' /** Enable feature. */ on: '' } /** * Indicates that an element and its contents are, as much as possible, independent of the rest of the document tree. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/contain) * */ interface contain extends _ { set(val: this): void; /** Indicates that the property has no effect. */ none: '' /** Turns on all forms of containment for the element. */ strict: '' /** All containment rules except size are applied to the element. */ content: '' /** For properties that can have effects on more than just an element and its descendants, those effects don't escape the containing element. */ size: '' /** Turns on layout containment for the element. */ layout: '' /** Turns on style containment for the element. */ style: '' /** Turns on paint containment for the element. */ paint: '' } /** * If background images have been specified, this property specifies their initial position (after any resizing) within their corresponding background positioning area. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/background-position-x) * */ interface backgroundΞpositionΞx extends _ { set(val: this | Ψlength | Ψpercentage, arg1: any, arg2: any, arg3: any): void; /** Equivalent to '50%' ('left 50%') for the horizontal position if the horizontal position is not otherwise specified, or '50%' ('top 50%') for the vertical position if it is. */ center: '' /** Equivalent to '0%' for the horizontal position if one or two values are given, otherwise specifies the left edge as the origin for the next offset. */ left: '' /** Equivalent to '100%' for the horizontal position if one or two values are given, otherwise specifies the right edge as the origin for the next offset. */ right: '' } /** * Defines how nested elements are rendered in 3D space. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/transform-style) * */ interface transformΞstyle extends _ { set(val: this): void; /** All children of this element are rendered flattened into the 2D plane of the element. */ flat: '' /** Flattening is not performed, so children maintain their position in 3D space. */ preserveΞ3d: '' } /** * For elements rendered as a single box, specifies the background positioning area. For elements rendered as multiple boxes (e.g., inline boxes on several lines, boxes on several pages) specifies which boxes 'box-decoration-break' operates on to determine the background positioning area(s). * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/background-origin) * * @alias bgo */ interface backgroundΞorigin extends _ { set(val: Ψbox, arg1: any, arg2: any, arg3: any): void; } /** @proxy backgroundΞorigin */ interface bgo extends backgroundΞorigin { } /** * Sets the style of the left border. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-left-style) * * @alias bsl */ interface borderΞleftΞstyle extends _ { set(val: ΨlineΞstyle): void; } /** @proxy borderΞleftΞstyle */ interface bsl extends borderΞleftΞstyle { } /** * The font-display descriptor determines how a font face is displayed based on whether and when it is downloaded and ready to use. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/font-display) * */ interface fontΞdisplay extends _ { set(val: any): void; } /** * Specifies a clipping path where everything inside the path is visible and everything outside is clipped out. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/clip-path) * */ interface clipΞpath extends _ { set(val: this | Ψurl | Ψshape | ΨgeometryΞbox): void; /** No clipping path gets created. */ none: '' /** References a <clipPath> element to create a clipping path. */ url(): '' } /** * Controls whether hyphenation is allowed to create more break opportunities within a line of text. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/hyphens) * */ interface hyphens extends _ { set(val: this): void; /** Conditional hyphenation characters inside a word, if present, take priority over automatic resources when determining hyphenation points within the word. */ auto: '' /** Words are only broken at line breaks where there are characters inside the word that suggest line break opportunities */ manual: '' /** Words are not broken at line breaks, even if characters inside the word suggest line break points. */ none: '' } /** * Specifies whether the background images are fixed with regard to the viewport ('fixed') or scroll along with the element ('scroll') or its contents ('local'). * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/background-attachment) * * @alias bga */ interface backgroundΞattachment extends _ { set(val: this, arg1: any, arg2: any, arg3: any): void; /** The background is fixed with regard to the viewport. In paged media where there is no viewport, a 'fixed' background is fixed with respect to the page box and therefore replicated on every page. */ fixed: '' /** The background is fixed with regard to the element’s contents: if the element has a scrolling mechanism, the background scrolls with the element’s contents. */ local: '' /** The background is fixed with regard to the element itself and does not scroll with its contents. (It is effectively attached to the element’s border.) */ scroll: '' } /** @proxy backgroundΞattachment */ interface bga extends backgroundΞattachment { } /** * Sets the style of the right border. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-right-style) * * @alias bsr */ interface borderΞrightΞstyle extends _ { set(val: ΨlineΞstyle): void; } /** @proxy borderΞrightΞstyle */ interface bsr extends borderΞrightΞstyle { } /** * The color of the outline. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/outline-color) * */ interface outlineΞcolor extends _ { set(val: this | Ψcolor): void; /** Performs a color inversion on the pixels on the screen. */ invert: '' } /** * Logical 'margin-bottom'. Mapping depends on the parent element’s 'writing-mode', 'direction', and 'text-orientation'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/margin-block-end) * */ interface marginΞblockΞend extends _ { set(val: this | Ψlength | Ψpercentage): void; auto: '' } /** * Defines whether the animation is running or paused. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/animation-play-state) * */ interface animationΞplayΞstate extends _ { set(val: this): void; /** A running animation will be paused. */ paused: '' /** Resume playback of a paused animation. */ running: '' } /** * Specifies quotation marks for any number of embedded quotations. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/quotes) * */ interface quotes extends _ { set(val: this | Ψstring): void; /** The 'open-quote' and 'close-quote' values of the 'content' property produce no quotations marks, as if they were 'no-open-quote' and 'no-close-quote' respectively. */ none: '' } /** * If background images have been specified, this property specifies their initial position (after any resizing) within their corresponding background positioning area. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/background-position-y) * */ interface backgroundΞpositionΞy extends _ { set(val: this | Ψlength | Ψpercentage, arg1: any, arg2: any, arg3: any): void; /** Equivalent to '100%' for the vertical position if one or two values are given, otherwise specifies the bottom edge as the origin for the next offset. */ bottom: '' /** Equivalent to '50%' ('left 50%') for the horizontal position if the horizontal position is not otherwise specified, or '50%' ('top 50%') for the vertical position if it is. */ center: '' /** Equivalent to '0%' for the vertical position if one or two values are given, otherwise specifies the top edge as the origin for the next offset. */ top: '' } /** * Selects a normal, condensed, or expanded face from a font family. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/font-stretch) * */ interface fontΞstretch extends _ { set(val: this): void; condensed: '' expanded: '' extraΞcondensed: '' extraΞexpanded: '' /** Indicates a narrower value relative to the width of the parent element. */ narrower: '' normal: '' semiΞcondensed: '' semiΞexpanded: '' ultraΞcondensed: '' ultraΞexpanded: '' /** Indicates a wider value relative to the width of the parent element. */ wider: '' } /** * Specifies the shape to be used at the end of open subpaths when they are stroked. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/stroke-linecap) * */ interface strokeΞlinecap extends _ { set(val: this): void; /** Indicates that the stroke for each subpath does not extend beyond its two endpoints. */ butt: '' /** Indicates that at each end of each subpath, the shape representing the stroke will be extended by a half circle with a radius equal to the stroke width. */ round: '' /** Indicates that at the end of each subpath, the shape representing the stroke will be extended by a rectangle with the same width as the stroke width and whose length is half of the stroke width. */ square: '' } /** * Determines the alignment of the replaced element inside its box. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) * */ interface objectΞposition extends _ { set(val: Ψposition | Ψlength | Ψpercentage): void; } /** * Property accepts one or more names of counters (identifiers), each one optionally followed by an integer. The integer gives the value that the counter is set to on each occurrence of the element. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/counter-reset) * */ interface counterΞreset extends _ { set(val: this | Ψidentifier | Ψinteger): void; /** The counter is not modified. */ none: '' } /** * Logical 'margin-top'. Mapping depends on the parent element’s 'writing-mode', 'direction', and 'text-orientation'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/margin-block-start) * */ interface marginΞblockΞstart extends _ { set(val: this | Ψlength | Ψpercentage): void; auto: '' } /** * Manipulate the value of existing counters. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/counter-increment) * */ interface counterΞincrement extends _ { set(val: this | Ψidentifier | Ψinteger): void; /** This element does not alter the value of any counters. */ none: '' } /** * undefined * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/size) * */ interface size extends _ { set(val: Ψlength): void; } /** * Specifies the color of text decoration (underlines overlines, and line-throughs) set on the element with text-decoration-line. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/text-decoration-color) * * @alias tdc */ interface textΞdecorationΞcolor extends _ { set(val: Ψcolor): void; } /** @proxy textΞdecorationΞcolor */ interface tdc extends textΞdecorationΞcolor { } /** * Sets the image that will be used as the list item marker. When the image is available, it will replace the marker set with the 'list-style-type' marker. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/list-style-image) * */ interface listΞstyleΞimage extends _ { set(val: this | Ψimage): void; /** The default contents of the of the list item’s marker are given by 'list-style-type' instead. */ none: '' } /** * Describes the optimal number of columns into which the content of the element will be flowed. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/column-count) * */ interface columnΞcount extends _ { set(val: this | Ψinteger): void; /** Determines the number of columns by the 'column-width' property and the element width. */ auto: '' } /** * Shorthand property for setting 'border-image-source', 'border-image-slice', 'border-image-width', 'border-image-outset' and 'border-image-repeat'. Omitted values are set to their initial values. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-image) * */ interface borderΞimage extends _ { set(val: this | Ψlength | Ψpercentage | Ψnumber | Ψurl): void; /** If 'auto' is specified then the border image width is the intrinsic width or height (whichever is applicable) of the corresponding image slice. If the image does not have the required intrinsic dimension then the corresponding border-width is used instead. */ auto: '' /** Causes the middle part of the border-image to be preserved. */ fill: '' /** Use the border styles. */ none: '' /** The image is tiled (repeated) to fill the area. */ repeat: '' /** The image is tiled (repeated) to fill the area. If it does not fill the area with a whole number of tiles, the image is rescaled so that it does. */ round: '' /** The image is tiled (repeated) to fill the area. If it does not fill the area with a whole number of tiles, the extra space is distributed around the tiles. */ space: '' /** The image is stretched to fill the area. */ stretch: '' url(): '' } /** * Sets the gap between columns. If there is a column rule between columns, it will appear in the middle of the gap. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/column-gap) * * @alias cg */ interface columnΞgap extends _ { set(val: this | Ψlength): void; /** User agent specific and typically equivalent to 1em. */ normal: '' } /** @proxy columnΞgap */ interface cg extends columnΞgap { } /** * Defines rules for page breaks inside an element. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/page-break-inside) * */ interface pageΞbreakΞinside extends _ { set(val: this): void; /** Neither force nor forbid a page break inside the generated box. */ auto: '' /** Avoid a page break inside the generated box. */ avoid: '' } /** * Specifies the opacity of the painting operation used to paint the interior the current object. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/fill-opacity) * */ interface fillΞopacity extends _ { set(val: Ψnumber): void; } /** * Logical 'padding-left'. Mapping depends on the parent element’s 'writing-mode', 'direction', and 'text-orientation'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/padding-inline-start) * */ interface paddingΞinlineΞstart extends _ { set(val: Ψlength | Ψpercentage): void; } /** * In the separated borders model, this property controls the rendering of borders and backgrounds around cells that have no visible content. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/empty-cells) * */ interface emptyΞcells extends _ { set(val: this): void; /** No borders or backgrounds are drawn around/behind empty cells. */ hide: '' ΞmozΞshowΞbackground: '' /** Borders and backgrounds are drawn around/behind empty cells (like normal cells). */ show: '' } /** * Specifies control over which ligatures are enabled or disabled. A value of ‘normal’ implies that the defaults set by the font are used. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/font-variant-ligatures) * */ interface fontΞvariantΞligatures extends _ { set(val: this): void; /** Enables display of additional ligatures. */ additionalΞligatures: '' /** Enables display of common ligatures. */ commonΞligatures: '' /** Enables display of contextual alternates. */ contextual: '' /** Enables display of discretionary ligatures. */ discretionaryΞligatures: '' /** Enables display of historical ligatures. */ historicalΞligatures: '' /** Disables display of additional ligatures. */ noΞadditionalΞligatures: '' /** Disables display of common ligatures. */ noΞcommonΞligatures: '' /** Disables display of contextual alternates. */ noΞcontextual: '' /** Disables display of discretionary ligatures. */ noΞdiscretionaryΞligatures: '' /** Disables display of historical ligatures. */ noΞhistoricalΞligatures: '' /** Disables all ligatures. */ none: '' /** Implies that the defaults set by the font are used. */ normal: '' } /** * The text-decoration-skip CSS property specifies what parts of the element’s content any text decoration affecting the element must skip over. It controls all text decoration lines drawn by the element and also any text decoration lines drawn by its ancestors. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/text-decoration-skip) * */ interface textΞdecorationΞskip extends _ { set(val: any): void; } /** * Defines the way of justifying a box inside its container along the appropriate axis. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-self) * * @alias js */ interface justifyΞself extends _ { set(val: this): void; auto: '' normal: '' end: '' start: '' /** "Flex items are packed toward the end of the line." */ flexΞend: '' /** "Flex items are packed toward the start of the line." */ flexΞstart: '' /** The item is packed flush to the edge of the alignment container of the end side of the item, in the appropriate axis. */ selfΞend: '' /** The item is packed flush to the edge of the alignment container of the start side of the item, in the appropriate axis.. */ selfΞstart: '' /** The items are packed flush to each other toward the center of the of the alignment container. */ center: '' left: '' right: '' baseline: '' 'first baseline': '' 'last baseline': '' /** If the cross size property of the flex item computes to auto, and neither of the cross-axis margins are auto, the flex item is stretched. */ stretch: '' save: '' unsave: '' } /** @proxy justifyΞself */ interface js extends justifyΞself { } /** * Defines rules for page breaks after an element. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/page-break-after) * */ interface pageΞbreakΞafter extends _ { set(val: this): void; /** Always force a page break after the generated box. */ always: '' /** Neither force nor forbid a page break after generated box. */ auto: '' /** Avoid a page break after the generated box. */ avoid: '' /** Force one or two page breaks after the generated box so that the next page is formatted as a left page. */ left: '' /** Force one or two page breaks after the generated box so that the next page is formatted as a right page. */ right: '' } /** * specifies, as a space-separated track list, the line names and track sizing functions of the grid. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template-rows) * * @alias gtr */ interface gridΞtemplateΞrows extends _ { set(val: this | Ψidentifier | Ψlength | Ψpercentage | Ψstring): void; /** There is no explicit grid; any rows/columns will be implicitly generated. */ none: '' /** Represents the largest min-content contribution of the grid items occupying the grid track. */ minΞcontent: '' /** Represents the largest max-content contribution of the grid items occupying the grid track. */ maxΞcontent: '' /** As a maximum, identical to 'max-content'. As a minimum, represents the largest minimum size (as specified by min-width/min-height) of the grid items occupying the grid track. */ auto: '' /** Indicates that the grid will align to its parent grid in that axis. */ subgrid: '' /** Defines a size range greater than or equal to min and less than or equal to max. */ minmax(): '' /** Represents a repeated fragment of the track list, allowing a large number of columns or rows that exhibit a recurring pattern to be written in a more compact form. */ repeat(): '' } /** @proxy gridΞtemplateΞrows */ interface gtr extends gridΞtemplateΞrows { } /** * Logical 'padding-right'. Mapping depends on the parent element’s 'writing-mode', 'direction', and 'text-orientation'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/padding-inline-end) * */ interface paddingΞinlineΞend extends _ { set(val: Ψlength | Ψpercentage): void; } /** * Shorthand that specifies the gutters between grid columns and grid rows in one declaration. Replaced by 'gap' property. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/grid-gap) * */ interface gridΞgap extends _ { set(val: Ψlength): void; } /** * Shorthand that resets all properties except 'direction' and 'unicode-bidi'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/all) * */ interface all extends _ { set(val: this): void; } /** * Shorthand for 'grid-column-start' and 'grid-column-end'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/grid-column) * * @alias gc */ interface gridΞcolumn extends _ { set(val: this | Ψidentifier | Ψinteger): void; /** The property contributes nothing to the grid item’s placement, indicating auto-placement, an automatic span, or a default span of one. */ auto: '' /** Contributes a grid span to the grid item’s placement such that the corresponding edge of the grid item’s grid area is N lines from its opposite edge. */ span: '' } /** @proxy gridΞcolumn */ interface gc extends gridΞcolumn { } /** * Specifies the opacity of the painting operation used to stroke the current object. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/stroke-opacity) * */ interface strokeΞopacity extends _ { set(val: Ψnumber): void; } /** * Logical 'margin-left'. Mapping depends on the parent element’s 'writing-mode', 'direction', and 'text-orientation'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/margin-inline-start) * */ interface marginΞinlineΞstart extends _ { set(val: this | Ψlength | Ψpercentage): void; auto: '' } /** * Logical 'margin-right'. Mapping depends on the parent element’s 'writing-mode', 'direction', and 'text-orientation'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/margin-inline-end) * */ interface marginΞinlineΞend extends _ { set(val: this | Ψlength | Ψpercentage): void; auto: '' } /** * Controls the color of the text insertion indicator. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/caret-color) * */ interface caretΞcolor extends _ { set(val: this | Ψcolor): void; /** The user agent selects an appropriate color for the caret. This is generally currentcolor, but the user agent may choose a different color to ensure good visibility and contrast with the surrounding content, taking into account the value of currentcolor, the background, shadows, and other factors. */ auto: '' } /** * Specifies the minimum number of line boxes in a block container that must be left in a fragment before a fragmentation break. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/orphans) * */ interface orphans extends _ { set(val: Ψinteger): void; } /** * Specifies the position of the caption box with respect to the table box. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/caption-side) * */ interface captionΞside extends _ { set(val: this): void; /** Positions the caption box below the table box. */ bottom: '' /** Positions the caption box above the table box. */ top: '' } /** * Establishes the origin for the perspective property. It effectively sets the X and Y position at which the viewer appears to be looking at the children of the element. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/perspective-origin) * */ interface perspectiveΞorigin extends _ { set(val: Ψposition | Ψpercentage | Ψlength): void; } /** * Indicates what color to use at that gradient stop. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/stop-color) * */ interface stopΞcolor extends _ { set(val: Ψcolor): void; } /** * Specifies the minimum number of line boxes of a block container that must be left in a fragment after a break. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/widows) * */ interface widows extends _ { set(val: Ψinteger): void; } /** * Specifies the scrolling behavior for a scrolling box, when scrolling happens due to navigation or CSSOM scrolling APIs. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-behavior) * */ interface scrollΞbehavior extends _ { set(val: this): void; /** Scrolls in an instant fashion. */ auto: '' /** Scrolls in a smooth fashion using a user-agent-defined timing function and time period. */ smooth: '' } /** * Specifies the gutters between grid columns. Replaced by 'column-gap' property. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/grid-column-gap) * * @alias gcg */ interface gridΞcolumnΞgap extends _ { set(val: Ψlength): void; } /** @proxy gridΞcolumnΞgap */ interface gcg extends gridΞcolumnΞgap { } /** * A shorthand property which sets both 'column-width' and 'column-count'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/columns) * */ interface columns extends _ { set(val: this | Ψlength | Ψinteger): void; /** The width depends on the values of other properties. */ auto: '' } /** * Describes the width of columns in multicol elements. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/column-width) * */ interface columnΞwidth extends _ { set(val: this | Ψlength): void; /** The width depends on the values of other properties. */ auto: '' } /** * Defines the formula that must be used to mix the colors with the backdrop. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/mix-blend-mode) * */ interface mixΞblendΞmode extends _ { set(val: this): void; /** Default attribute which specifies no blending */ normal: '' /** The source color is multiplied by the destination color and replaces the destination. */ multiply: '' /** Multiplies the complements of the backdrop and source color values, then complements the result. */ screen: '' /** Multiplies or screens the colors, depending on the backdrop color value. */ overlay: '' /** Selects the darker of the backdrop and source colors. */ darken: '' /** Selects the lighter of the backdrop and source colors. */ lighten: '' /** Brightens the backdrop color to reflect the source color. */ colorΞdodge: '' /** Darkens the backdrop color to reflect the source color. */ colorΞburn: '' /** Multiplies or screens the colors, depending on the source color value. */ hardΞlight: '' /** Darkens or lightens the colors, depending on the source color value. */ softΞlight: '' /** Subtracts the darker of the two constituent colors from the lighter color.. */ difference: '' /** Produces an effect similar to that of the Difference mode but lower in contrast. */ exclusion: '' /** Creates a color with the hue of the source color and the saturation and luminosity of the backdrop color. */ hue: '' /** Creates a color with the saturation of the source color and the hue and luminosity of the backdrop color. */ saturation: '' /** Creates a color with the hue and saturation of the source color and the luminosity of the backdrop color. */ color: '' /** Creates a color with the luminosity of the source color and the hue and saturation of the backdrop color. */ luminosity: '' } /** * Kerning is the contextual adjustment of inter-glyph spacing. This property controls metric kerning, kerning that utilizes adjustment data contained in the font. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/font-kerning) * */ interface fontΞkerning extends _ { set(val: this): void; /** Specifies that kerning is applied at the discretion of the user agent. */ auto: '' /** Specifies that kerning is not applied. */ none: '' /** Specifies that kerning is applied. */ normal: '' } /** * Specifies inward offsets from the top, right, bottom, and left edges of the image, dividing it into nine regions: four corners, four edges and a middle. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-image-slice) * */ interface borderΞimageΞslice extends _ { set(val: this | Ψnumber | Ψpercentage): void; /** Causes the middle part of the border-image to be preserved. */ fill: '' } /** * Specifies how the images for the sides and the middle part of the border image are scaled and tiled. If the second keyword is absent, it is assumed to be the same as the first. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-image-repeat) * */ interface borderΞimageΞrepeat extends _ { set(val: this): void; /** The image is tiled (repeated) to fill the area. */ repeat: '' /** The image is tiled (repeated) to fill the area. If it does not fill the area with a whole number of tiles, the image is rescaled so that it does. */ round: '' /** The image is tiled (repeated) to fill the area. If it does not fill the area with a whole number of tiles, the extra space is distributed around the tiles. */ space: '' /** The image is stretched to fill the area. */ stretch: '' } /** * The four values of 'border-image-width' specify offsets that are used to divide the border image area into nine parts. They represent inward distances from the top, right, bottom, and left sides of the area, respectively. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-image-width) * */ interface borderΞimageΞwidth extends _ { set(val: this | Ψlength | Ψpercentage | Ψnumber): void; /** The border image width is the intrinsic width or height (whichever is applicable) of the corresponding image slice. If the image does not have the required intrinsic dimension then the corresponding border-width is used instead. */ auto: '' } /** * Shorthand for 'grid-row-start' and 'grid-row-end'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/grid-row) * * @alias gr */ interface gridΞrow extends _ { set(val: this | Ψidentifier | Ψinteger): void; /** The property contributes nothing to the grid item’s placement, indicating auto-placement, an automatic span, or a default span of one. */ auto: '' /** Contributes a grid span to the grid item’s placement such that the corresponding edge of the grid item’s grid area is N lines from its opposite edge. */ span: '' } /** @proxy gridΞrow */ interface gr extends gridΞrow { } /** * Determines the width of the tab character (U+0009), in space characters (U+0020), when rendered. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/tab-size) * */ interface tabΞsize extends _ { set(val: Ψinteger | Ψlength): void; } /** * Specifies the gutters between grid rows. Replaced by 'row-gap' property. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/grid-row-gap) * * @alias grg */ interface gridΞrowΞgap extends _ { set(val: Ψlength): void; } /** @proxy gridΞrowΞgap */ interface grg extends gridΞrowΞgap { } /** * Specifies the line style for underline, line-through and overline text decoration. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/text-decoration-style) * * @alias tds */ interface textΞdecorationΞstyle extends _ { set(val: this): void; /** Produces a dashed line style. */ dashed: '' /** Produces a dotted line. */ dotted: '' /** Produces a double line. */ double: '' /** Produces no line. */ none: '' /** Produces a solid line. */ solid: '' /** Produces a wavy line. */ wavy: '' } /** @proxy textΞdecorationΞstyle */ interface tds extends textΞdecorationΞstyle { } /** * Specifies what set of line breaking restrictions are in effect within the element. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/line-break) * */ interface lineΞbreak extends _ { set(val: this): void; /** The UA determines the set of line-breaking restrictions to use for CJK scripts, and it may vary the restrictions based on the length of the line; e.g., use a less restrictive set of line-break rules for short lines. */ auto: '' /** Breaks text using the least restrictive set of line-breaking rules. Typically used for short lines, such as in newspapers. */ loose: '' /** Breaks text using the most common set of line-breaking rules. */ normal: '' /** Breaks CJK scripts using a more restrictive set of line-breaking rules than 'normal'. */ strict: '' } /** * The values specify the amount by which the border image area extends beyond the border box on the top, right, bottom, and left sides respectively. If the fourth value is absent, it is the same as the second. If the third one is also absent, it is the same as the first. If the second one is also absent, it is the same as the first. Numbers represent multiples of the corresponding border-width. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-image-outset) * */ interface borderΞimageΞoutset extends _ { set(val: Ψlength | Ψnumber): void; } /** * Shorthand for setting 'column-rule-width', 'column-rule-style', and 'column-rule-color' at the same place in the style sheet. Omitted values are set to their initial values. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/column-rule) * */ interface columnΞrule extends _ { set(val: Ψlength | ΨlineΞwidth | ΨlineΞstyle | Ψcolor): void; } /** * Defines the default justify-self for all items of the box, giving them the default way of justifying each box along the appropriate axis * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-items) * * @alias ji */ interface justifyΞitems extends _ { set(val: this): void; auto: '' normal: '' end: '' start: '' /** "Flex items are packed toward the end of the line." */ flexΞend: '' /** "Flex items are packed toward the start of the line." */ flexΞstart: '' /** The item is packed flush to the edge of the alignment container of the end side of the item, in the appropriate axis. */ selfΞend: '' /** The item is packed flush to the edge of the alignment container of the start side of the item, in the appropriate axis.. */ selfΞstart: '' /** The items are packed flush to each other toward the center of the of the alignment container. */ center: '' left: '' right: '' baseline: '' 'first baseline': '' 'last baseline': '' /** If the cross size property of the flex item computes to auto, and neither of the cross-axis margins are auto, the flex item is stretched. */ stretch: '' save: '' unsave: '' legacy: '' } /** @proxy justifyΞitems */ interface ji extends justifyΞitems { } /** * Determine a grid item’s size and location within the grid by contributing a line, a span, or nothing (automatic) to its grid placement. Shorthand for 'grid-row-start', 'grid-column-start', 'grid-row-end', and 'grid-column-end'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/grid-area) * * @alias ga */ interface gridΞarea extends _ { set(val: this | Ψidentifier | Ψinteger): void; /** The property contributes nothing to the grid item’s placement, indicating auto-placement, an automatic span, or a default span of one. */ auto: '' /** Contributes a grid span to the grid item’s placement such that the corresponding edge of the grid item’s grid area is N lines from its opposite edge. */ span: '' } /** @proxy gridΞarea */ interface ga extends gridΞarea { } /** * When two line segments meet at a sharp angle and miter joins have been specified for 'stroke-linejoin', it is possible for the miter to extend far beyond the thickness of the line stroking the path. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/stroke-miterlimit) * */ interface strokeΞmiterlimit extends _ { set(val: Ψnumber): void; } /** * Describes how the last line of a block or a line right before a forced line break is aligned when 'text-align' is set to 'justify'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align-last) * */ interface textΞalignΞlast extends _ { set(val: this): void; /** Content on the affected line is aligned per 'text-align' unless 'text-align' is set to 'justify', in which case it is 'start-aligned'. */ auto: '' /** The inline contents are centered within the line box. */ center: '' /** The text is justified according to the method specified by the 'text-justify' property. */ justify: '' /** The inline contents are aligned to the left edge of the line box. In vertical text, 'left' aligns to the edge of the line box that would be the start edge for left-to-right text. */ left: '' /** The inline contents are aligned to the right edge of the line box. In vertical text, 'right' aligns to the edge of the line box that would be the end edge for left-to-right text. */ right: '' } /** * The backdrop-filter CSS property lets you apply graphical effects such as blurring or color shifting to the area behind an element. Because it applies to everything behind the element, to see the effect you must make the element or its background at least partially transparent. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/backdrop-filter) * */ interface backdropΞfilter extends _ { set(val: any): void; } /** * Specifies the size of implicitly created rows. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/grid-auto-rows) * * @alias gar */ interface gridΞautoΞrows extends _ { set(val: this | Ψlength | Ψpercentage, arg1: any, arg2: any, arg3: any): void; /** Represents the largest min-content contribution of the grid items occupying the grid track. */ minΞcontent: '' /** Represents the largest max-content contribution of the grid items occupying the grid track. */ maxΞcontent: '' /** As a maximum, identical to 'max-content'. As a minimum, represents the largest minimum size (as specified by min-width/min-height) of the grid items occupying the grid track. */ auto: '' /** Defines a size range greater than or equal to min and less than or equal to max. */ minmax(): '' } /** @proxy gridΞautoΞrows */ interface gar extends gridΞautoΞrows { } /** * Specifies the shape to be used at the corners of paths or basic shapes when they are stroked. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/stroke-linejoin) * */ interface strokeΞlinejoin extends _ { set(val: this): void; /** Indicates that a bevelled corner is to be used to join path segments. */ bevel: '' /** Indicates that a sharp corner is to be used to join path segments. */ miter: '' /** Indicates that a round corner is to be used to join path segments. */ round: '' } /** * Specifies an orthogonal rotation to be applied to an image before it is laid out. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/shape-outside) * */ interface shapeΞoutside extends _ { set(val: this | Ψimage | Ψbox | Ψshape): void; /** The background is painted within (clipped to) the margin box. */ marginΞbox: '' /** The float area is unaffected. */ none: '' } /** * Specifies what line decorations, if any, are added to the element. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/text-decoration-line) * * @alias tdl */ interface textΞdecorationΞline extends _ { set(val: this): void; /** Each line of text has a line through the middle. */ lineΞthrough: '' /** Neither produces nor inhibits text decoration. */ none: '' /** Each line of text has a line above it. */ overline: '' /** Each line of text is underlined. */ underline: '' } /** @proxy textΞdecorationΞline */ interface tdl extends textΞdecorationΞline { } /** * The scroll-snap-align property specifies the box’s snap position as an alignment of its snap area (as the alignment subject) within its snap container’s snapport (as the alignment container). The two values specify the snapping alignment in the block axis and inline axis, respectively. If only one value is specified, the second value defaults to the same value. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-snap-align) * */ interface scrollΞsnapΞalign extends _ { set(val: any, arg1: any): void; } /** * Indicates the algorithm (or winding rule) which is to be used to determine what parts of the canvas are included inside the shape. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/fill-rule) * */ interface fillΞrule extends _ { set(val: this): void; /** Determines the ‘insideness’ of a point on the canvas by drawing a ray from that point to infinity in any direction and counting the number of path segments from the given shape that the ray crosses. */ evenodd: '' /** Determines the ‘insideness’ of a point on the canvas by drawing a ray from that point to infinity in any direction and then examining the places where a segment of the shape crosses the ray. */ nonzero: '' } /** * Controls how the auto-placement algorithm works, specifying exactly how auto-placed items get flowed into the grid. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/grid-auto-flow) * * @alias gaf */ interface gridΞautoΞflow extends _ { set(val: this): void; /** The auto-placement algorithm places items by filling each row in turn, adding new rows as necessary. */ row: '' /** The auto-placement algorithm places items by filling each column in turn, adding new columns as necessary. */ column: '' /** If specified, the auto-placement algorithm uses a “dense” packing algorithm, which attempts to fill in holes earlier in the grid if smaller items come up later. */ dense: '' } /** @proxy gridΞautoΞflow */ interface gaf extends gridΞautoΞflow { } /** * Defines how strictly snap points are enforced on the scroll container. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-snap-type) * */ interface scrollΞsnapΞtype extends _ { set(val: this): void; /** The visual viewport of this scroll container must ignore snap points, if any, when scrolled. */ none: '' /** The visual viewport of this scroll container is guaranteed to rest on a snap point when there are no active scrolling operations. */ mandatory: '' /** The visual viewport of this scroll container may come to rest on a snap point at the termination of a scroll at the discretion of the UA given the parameters of the scroll. */ proximity: '' } /** * Defines rules for page breaks before an element. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/page-break-before) * */ interface pageΞbreakΞbefore extends _ { set(val: this): void; /** Always force a page break before the generated box. */ always: '' /** Neither force nor forbid a page break before the generated box. */ auto: '' /** Avoid a page break before the generated box. */ avoid: '' /** Force one or two page breaks before the generated box so that the next page is formatted as a left page. */ left: '' /** Force one or two page breaks before the generated box so that the next page is formatted as a right page. */ right: '' } /** * Determine a grid item’s size and location within the grid by contributing a line, a span, or nothing (automatic) to its grid placement. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/grid-column-start) * * @alias gcs */ interface gridΞcolumnΞstart extends _ { set(val: this | Ψidentifier | Ψinteger): void; /** The property contributes nothing to the grid item’s placement, indicating auto-placement, an automatic span, or a default span of one. */ auto: '' /** Contributes a grid span to the grid item’s placement such that the corresponding edge of the grid item’s grid area is N lines from its opposite edge. */ span: '' } /** @proxy gridΞcolumnΞstart */ interface gcs extends gridΞcolumnΞstart { } /** * Specifies named grid areas, which are not associated with any particular grid item, but can be referenced from the grid-placement properties. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template-areas) * * @alias gta */ interface gridΞtemplateΞareas extends _ { set(val: this | Ψstring): void; /** The grid container doesn’t define any named grid areas. */ none: '' } /** @proxy gridΞtemplateΞareas */ interface gta extends gridΞtemplateΞareas { } /** * Describes the page/column/region break behavior inside the principal box. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/break-inside) * */ interface breakΞinside extends _ { set(val: this): void; /** Impose no additional breaking constraints within the box. */ auto: '' /** Avoid breaks within the box. */ avoid: '' /** Avoid a column break within the box. */ avoidΞcolumn: '' /** Avoid a page break within the box. */ avoidΞpage: '' } /** * In continuous media, this property will only be consulted if the length of columns has been constrained. Otherwise, columns will automatically be balanced. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/column-fill) * */ interface columnΞfill extends _ { set(val: this): void; /** Fills columns sequentially. */ auto: '' /** Balance content equally between columns, if possible. */ balance: '' } /** * Determine a grid item’s size and location within the grid by contributing a line, a span, or nothing (automatic) to its grid placement. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/grid-column-end) * * @alias gce */ interface gridΞcolumnΞend extends _ { set(val: this | Ψidentifier | Ψinteger): void; /** The property contributes nothing to the grid item’s placement, indicating auto-placement, an automatic span, or a default span of one. */ auto: '' /** Contributes a grid span to the grid item’s placement such that the corresponding edge of the grid item’s grid area is N lines from its opposite edge. */ span: '' } /** @proxy gridΞcolumnΞend */ interface gce extends gridΞcolumnΞend { } /** * Specifies an image to use instead of the border styles given by the 'border-style' properties and as an additional background layer for the element. If the value is 'none' or if the image cannot be displayed, the border styles will be used. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-image-source) * */ interface borderΞimageΞsource extends _ { set(val: this | Ψimage): void; /** Use the border styles. */ none: '' } /** * The overflow-anchor CSS property provides a way to opt out browser scroll anchoring behavior which adjusts scroll position to minimize content shifts. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/overflow-anchor) * * @alias ofa */ interface overflowΞanchor extends _ { set(val: any): void; } /** @proxy overflowΞanchor */ interface ofa extends overflowΞanchor { } /** * Determine a grid item’s size and location within the grid by contributing a line, a span, or nothing (automatic) to its grid placement. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/grid-row-start) * * @alias grs */ interface gridΞrowΞstart extends _ { set(val: this | Ψidentifier | Ψinteger): void; /** The property contributes nothing to the grid item’s placement, indicating auto-placement, an automatic span, or a default span of one. */ auto: '' /** Contributes a grid span to the grid item’s placement such that the corresponding edge of the grid item’s grid area is N lines from its opposite edge. */ span: '' } /** @proxy gridΞrowΞstart */ interface grs extends gridΞrowΞstart { } /** * Determine a grid item’s size and location within the grid by contributing a line, a span, or nothing (automatic) to its grid placement. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/grid-row-end) * * @alias gre */ interface gridΞrowΞend extends _ { set(val: this | Ψidentifier | Ψinteger): void; /** The property contributes nothing to the grid item’s placement, indicating auto-placement, an automatic span, or a default span of one. */ auto: '' /** Contributes a grid span to the grid item’s placement such that the corresponding edge of the grid item’s grid area is N lines from its opposite edge. */ span: '' } /** @proxy gridΞrowΞend */ interface gre extends gridΞrowΞend { } /** * Specifies control over numerical forms. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/font-variant-numeric) * */ interface fontΞvariantΞnumeric extends _ { set(val: this): void; /** Enables display of lining diagonal fractions. */ diagonalΞfractions: '' /** Enables display of lining numerals. */ liningΞnums: '' /** None of the features are enabled. */ normal: '' /** Enables display of old-style numerals. */ oldstyleΞnums: '' /** Enables display of letter forms used with ordinal numbers. */ ordinal: '' /** Enables display of proportional numerals. */ proportionalΞnums: '' /** Enables display of slashed zeros. */ slashedΞzero: '' /** Enables display of lining stacked fractions. */ stackedΞfractions: '' /** Enables display of tabular numerals. */ tabularΞnums: '' } /** * Defines the blending mode of each background layer. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/background-blend-mode) * */ interface backgroundΞblendΞmode extends _ { set(val: this): void; /** Default attribute which specifies no blending */ normal: '' /** The source color is multiplied by the destination color and replaces the destination. */ multiply: '' /** Multiplies the complements of the backdrop and source color values, then complements the result. */ screen: '' /** Multiplies or screens the colors, depending on the backdrop color value. */ overlay: '' /** Selects the darker of the backdrop and source colors. */ darken: '' /** Selects the lighter of the backdrop and source colors. */ lighten: '' /** Brightens the backdrop color to reflect the source color. */ colorΞdodge: '' /** Darkens the backdrop color to reflect the source color. */ colorΞburn: '' /** Multiplies or screens the colors, depending on the source color value. */ hardΞlight: '' /** Darkens or lightens the colors, depending on the source color value. */ softΞlight: '' /** Subtracts the darker of the two constituent colors from the lighter color.. */ difference: '' /** Produces an effect similar to that of the Difference mode but lower in contrast. */ exclusion: '' /** Creates a color with the hue of the source color and the saturation and luminosity of the backdrop color. */ hue: '' /** Creates a color with the saturation of the source color and the hue and luminosity of the backdrop color. */ saturation: '' /** Creates a color with the hue and saturation of the source color and the luminosity of the backdrop color. */ color: '' /** Creates a color with the luminosity of the source color and the hue and saturation of the backdrop color. */ luminosity: '' } /** * The text-decoration-skip-ink CSS property specifies how overlines and underlines are drawn when they pass over glyph ascenders and descenders. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/text-decoration-skip-ink) * * @alias tdsi */ interface textΞdecorationΞskipΞink extends _ { set(val: any): void; } /** @proxy textΞdecorationΞskipΞink */ interface tdsi extends textΞdecorationΞskipΞink { } /** * Sets the color of the column rule * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/column-rule-color) * */ interface columnΞruleΞcolor extends _ { set(val: Ψcolor): void; } /** * In CSS setting to 'isolate' will turn the element into a stacking context. In SVG, it defines whether an element is isolated or not. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/isolation) * */ interface isolation extends _ { set(val: this): void; /** Elements are not isolated unless an operation is applied that causes the creation of a stacking context. */ auto: '' /** In CSS will turn the element into a stacking context. */ isolate: '' } /** * Provides hints about what tradeoffs to make as it renders vector graphics elements such as <path> elements and basic shapes such as circles and rectangles. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/shape-rendering) * */ interface shapeΞrendering extends _ { set(val: this): void; /** Suppresses aural rendering. */ auto: '' /** Emphasize the contrast between clean edges of artwork over rendering speed and geometric precision. */ crispEdges: '' /** Emphasize geometric precision over speed and crisp edges. */ geometricPrecision: '' /** Emphasize rendering speed over geometric precision and crisp edges. */ optimizeSpeed: '' } /** * Sets the style of the rule between columns of an element. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/column-rule-style) * */ interface columnΞruleΞstyle extends _ { set(val: ΨlineΞstyle): void; } /** * Logical 'border-right-width'. Mapping depends on the parent element’s 'writing-mode', 'direction', and 'text-orientation'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-inline-end-width) * */ interface borderΞinlineΞendΞwidth extends _ { set(val: Ψlength | ΨlineΞwidth): void; } /** * Logical 'border-left-width'. Mapping depends on the parent element’s 'writing-mode', 'direction', and 'text-orientation'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-inline-start-width) * */ interface borderΞinlineΞstartΞwidth extends _ { set(val: Ψlength | ΨlineΞwidth): void; } /** * Specifies the size of implicitly created columns. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/grid-auto-columns) * * @alias gac */ interface gridΞautoΞcolumns extends _ { set(val: this | Ψlength | Ψpercentage, arg1: any, arg2: any, arg3: any): void; /** Represents the largest min-content contribution of the grid items occupying the grid track. */ minΞcontent: '' /** Represents the largest max-content contribution of the grid items occupying the grid track. */ maxΞcontent: '' /** As a maximum, identical to 'max-content'. As a minimum, represents the largest minimum size (as specified by min-width/min-height) of the grid items occupying the grid track. */ auto: '' /** Defines a size range greater than or equal to min and less than or equal to max. */ minmax(): '' } /** @proxy gridΞautoΞcolumns */ interface gac extends gridΞautoΞcolumns { } /** * This is a shorthand property for both 'direction' and 'block-progression'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/writing-mode) * */ interface writingΞmode extends _ { set(val: this): void; /** Top-to-bottom block flow direction. The writing mode is horizontal. */ horizontalΞtb: '' /** Left-to-right block flow direction. The writing mode is vertical, while the typographic mode is horizontal. */ sidewaysΞlr: '' /** Right-to-left block flow direction. The writing mode is vertical, while the typographic mode is horizontal. */ sidewaysΞrl: '' /** Left-to-right block flow direction. The writing mode is vertical. */ verticalΞlr: '' /** Right-to-left block flow direction. The writing mode is vertical. */ verticalΞrl: '' } /** * Indicates the algorithm which is to be used to determine what parts of the canvas are included inside the shape. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/clip-rule) * */ interface clipΞrule extends _ { set(val: this): void; /** Determines the ‘insideness’ of a point on the canvas by drawing a ray from that point to infinity in any direction and counting the number of path segments from the given shape that the ray crosses. */ evenodd: '' /** Determines the ‘insideness’ of a point on the canvas by drawing a ray from that point to infinity in any direction and then examining the places where a segment of the shape crosses the ray. */ nonzero: '' } /** * Specifies control over capitalized forms. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/font-variant-caps) * */ interface fontΞvariantΞcaps extends _ { set(val: this): void; /** Enables display of petite capitals for both upper and lowercase letters. */ allΞpetiteΞcaps: '' /** Enables display of small capitals for both upper and lowercase letters. */ allΞsmallΞcaps: '' /** None of the features are enabled. */ normal: '' /** Enables display of petite capitals. */ petiteΞcaps: '' /** Enables display of small capitals. Small-caps glyphs typically use the form of uppercase letters but are reduced to the size of lowercase letters. */ smallΞcaps: '' /** Enables display of titling capitals. */ titlingΞcaps: '' /** Enables display of mixture of small capitals for uppercase letters with normal lowercase letters. */ unicase: '' } /** * Used to align (start-, middle- or end-alignment) a string of text relative to a given point. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/text-anchor) * */ interface textΞanchor extends _ { set(val: this): void; /** The rendered characters are aligned such that the end of the resulting rendered text is at the initial current text position. */ end: '' /** The rendered characters are aligned such that the geometric middle of the resulting rendered text is at the initial current text position. */ middle: '' /** The rendered characters are aligned such that the start of the resulting rendered text is at the initial current text position. */ start: '' } /** * Defines the opacity of a given gradient stop. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/stop-opacity) * */ interface stopΞopacity extends _ { set(val: Ψnumber): void; } /** * The mask CSS property alters the visibility of an element by either partially or fully hiding it. This is accomplished by either masking or clipping the image at specific points. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/mask) * */ interface mask extends _ { set(val: any, arg1: any, arg2: any, arg3: any): void; } /** * Describes the page/column break behavior after the generated box. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/column-span) * */ interface columnΞspan extends _ { set(val: this): void; /** The element spans across all columns. Content in the normal flow that appears before the element is automatically balanced across all columns before the element appear. */ all: '' /** The element does not span multiple columns. */ none: '' } /** * Allows control of glyph substitute and positioning in East Asian text. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/font-variant-east-asian) * */ interface fontΞvariantΞeastΞasian extends _ { set(val: this): void; /** Enables rendering of full-width variants. */ fullΞwidth: '' /** Enables rendering of JIS04 forms. */ jis04: '' /** Enables rendering of JIS78 forms. */ jis78: '' /** Enables rendering of JIS83 forms. */ jis83: '' /** Enables rendering of JIS90 forms. */ jis90: '' /** None of the features are enabled. */ normal: '' /** Enables rendering of proportionally-spaced variants. */ proportionalΞwidth: '' /** Enables display of ruby variant glyphs. */ ruby: '' /** Enables rendering of simplified forms. */ simplified: '' /** Enables rendering of traditional forms. */ traditional: '' } /** * Sets the position of an underline specified on the same element: it does not affect underlines specified by ancestor elements. This property is typically used in vertical writing contexts such as in Japanese documents where it often desired to have the underline appear 'over' (to the right of) the affected run of text * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/text-underline-position) * */ interface textΞunderlineΞposition extends _ { set(val: this): void; above: '' /** The user agent may use any algorithm to determine the underline’s position. In horizontal line layout, the underline should be aligned as for alphabetic. In vertical line layout, if the language is set to Japanese or Korean, the underline should be aligned as for over. */ auto: '' /** The underline is aligned with the under edge of the element’s content box. */ below: '' } /** * Describes the page/column/region break behavior after the generated box. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/break-after) * */ interface breakΞafter extends _ { set(val: this): void; /** Always force a page break before/after the generated box. */ always: '' /** Neither force nor forbid a page/column break before/after the principal box. */ auto: '' /** Avoid a break before/after the principal box. */ avoid: '' /** Avoid a column break before/after the principal box. */ avoidΞcolumn: '' /** Avoid a page break before/after the principal box. */ avoidΞpage: '' /** Always force a column break before/after the principal box. */ column: '' /** Force one or two page breaks before/after the generated box so that the next page is formatted as a left page. */ left: '' /** Always force a page break before/after the principal box. */ page: '' /** Force one or two page breaks before/after the generated box so that the next page is formatted as a right page. */ right: '' } /** * Describes the page/column/region break behavior before the generated box. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/break-before) * */ interface breakΞbefore extends _ { set(val: this): void; /** Always force a page break before/after the generated box. */ always: '' /** Neither force nor forbid a page/column break before/after the principal box. */ auto: '' /** Avoid a break before/after the principal box. */ avoid: '' /** Avoid a column break before/after the principal box. */ avoidΞcolumn: '' /** Avoid a page break before/after the principal box. */ avoidΞpage: '' /** Always force a column break before/after the principal box. */ column: '' /** Force one or two page breaks before/after the generated box so that the next page is formatted as a left page. */ left: '' /** Always force a page break before/after the principal box. */ page: '' /** Force one or two page breaks before/after the generated box so that the next page is formatted as a right page. */ right: '' } /** * Defines whether the content of the <mask> element is treated as as luminance mask or alpha mask. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/mask-type) * */ interface maskΞtype extends _ { set(val: this): void; /** Indicates that the alpha values of the mask should be used. */ alpha: '' /** Indicates that the luminance values of the mask should be used. */ luminance: '' } /** * Sets the width of the rule between columns. Negative values are not allowed. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/column-rule-width) * */ interface columnΞruleΞwidth extends _ { set(val: Ψlength | ΨlineΞwidth): void; } /** * The row-gap CSS property specifies the gutter between grid rows. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/row-gap) * * @alias rg */ interface rowΞgap extends _ { set(val: any): void; } /** @proxy rowΞgap */ interface rg extends rowΞgap { } /** * Specifies the orientation of text within a line. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/text-orientation) * */ interface textΞorientation extends _ { set(val: this): void; /** This value is equivalent to 'sideways-right' in 'vertical-rl' writing mode and equivalent to 'sideways-left' in 'vertical-lr' writing mode. */ sideways: '' /** In vertical writing modes, this causes text to be set as if in a horizontal layout, but rotated 90° clockwise. */ sidewaysΞright: '' /** In vertical writing modes, characters from horizontal-only scripts are rendered upright, i.e. in their standard horizontal orientation. */ upright: '' } /** * The scroll-padding property is a shorthand property which sets all of the scroll-padding longhands, assigning values much like the padding property does for the padding-* longhands. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-padding) * */ interface scrollΞpadding extends _ { set(val: any, arg1: any, arg2: any, arg3: any): void; } /** * Shorthand for setting grid-template-columns, grid-template-rows, and grid-template-areas in a single declaration. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template) * * @alias gt */ interface gridΞtemplate extends _ { set(val: this | Ψidentifier | Ψlength | Ψpercentage | Ψstring): void; /** Sets all three properties to their initial values. */ none: '' /** Represents the largest min-content contribution of the grid items occupying the grid track. */ minΞcontent: '' /** Represents the largest max-content contribution of the grid items occupying the grid track. */ maxΞcontent: '' /** As a maximum, identical to 'max-content'. As a minimum, represents the largest minimum size (as specified by min-width/min-height) of the grid items occupying the grid track. */ auto: '' /** Sets 'grid-template-rows' and 'grid-template-columns' to 'subgrid', and 'grid-template-areas' to its initial value. */ subgrid: '' /** Defines a size range greater than or equal to min and less than or equal to max. */ minmax(): '' /** Represents a repeated fragment of the track list, allowing a large number of columns or rows that exhibit a recurring pattern to be written in a more compact form. */ repeat(): '' } /** @proxy gridΞtemplate */ interface gt extends gridΞtemplate { } /** * Logical 'border-right-color'. Mapping depends on the parent element’s 'writing-mode', 'direction', and 'text-orientation'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-inline-end-color) * */ interface borderΞinlineΞendΞcolor extends _ { set(val: Ψcolor): void; } /** * Logical 'border-left-color'. Mapping depends on the parent element’s 'writing-mode', 'direction', and 'text-orientation'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-inline-start-color) * */ interface borderΞinlineΞstartΞcolor extends _ { set(val: Ψcolor): void; } /** * The scroll-snap-stop CSS property defines whether the scroll container is allowed to "pass over" possible snap positions. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-snap-stop) * */ interface scrollΞsnapΞstop extends _ { set(val: any): void; } /** * Adds a margin to a 'shape-outside'. This defines a new shape that is the smallest contour that includes all the points that are the 'shape-margin' distance outward in the perpendicular direction from a point on the underlying shape. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/shape-margin) * */ interface shapeΞmargin extends _ { set(val: Ψurl | Ψlength | Ψpercentage): void; } /** * Defines the alpha channel threshold used to extract the shape using an image. A value of 0.5 means that the shape will enclose all the pixels that are more than 50% opaque. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/shape-image-threshold) * */ interface shapeΞimageΞthreshold extends _ { set(val: Ψnumber): void; } /** * The gap CSS property is a shorthand property for row-gap and column-gap specifying the gutters between grid rows and columns. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/gap) * * @alias g */ interface gap extends _ { set(val: any): void; } /** @proxy gap */ interface g extends gap { } /** * Logical 'min-height'. Mapping depends on the element’s 'writing-mode'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/min-inline-size) * */ interface minΞinlineΞsize extends _ { set(val: Ψlength | Ψpercentage): void; } /** * Specifies an orthogonal rotation to be applied to an image before it is laid out. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/image-orientation) * */ interface imageΞorientation extends _ { set(val: this | Ψangle): void; /** After rotating by the precededing angle, the image is flipped horizontally. Defaults to 0deg if the angle is ommitted. */ flip: '' /** If the image has an orientation specified in its metadata, such as EXIF, this value computes to the angle that the metadata specifies is necessary to correctly orient the image. */ fromΞimage: '' } /** * Logical 'height'. Mapping depends on the element’s 'writing-mode'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/inline-size) * */ interface inlineΞsize extends _ { set(val: this | Ψlength | Ψpercentage): void; /** Depends on the values of other properties. */ auto: '' } /** * Logical 'padding-top'. Mapping depends on the parent element’s 'writing-mode', 'direction', and 'text-orientation'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/padding-block-start) * */ interface paddingΞblockΞstart extends _ { set(val: Ψlength | Ψpercentage): void; } /** * Logical 'padding-bottom'. Mapping depends on the parent element’s 'writing-mode', 'direction', and 'text-orientation'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/padding-block-end) * */ interface paddingΞblockΞend extends _ { set(val: Ψlength | Ψpercentage): void; } /** * The text-combine-upright CSS property specifies the combination of multiple characters into the space of a single character. If the combined text is wider than 1em, the user agent must fit the contents within 1em. The resulting composition is treated as a single upright glyph for layout and decoration. This property only has an effect in vertical writing modes. This is used to produce an effect that is known as tate-chū-yoko (縦中横) in Japanese, or as 直書橫向 in Chinese. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/text-combine-upright) * */ interface textΞcombineΞupright extends _ { set(val: any): void; } /** * Logical 'width'. Mapping depends on the element’s 'writing-mode'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/block-size) * */ interface blockΞsize extends _ { set(val: this | Ψlength | Ψpercentage): void; /** Depends on the values of other properties. */ auto: '' } /** * Logical 'min-width'. Mapping depends on the element’s 'writing-mode'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/min-block-size) * */ interface minΞblockΞsize extends _ { set(val: Ψlength | Ψpercentage): void; } /** * The scroll-padding-top property defines offsets for the top of the optimal viewing region of the scrollport: the region used as the target region for placing things in view of the user. This allows the author to exclude regions of the scrollport that are obscured by other content (such as fixed-positioned toolbars or sidebars) or simply to put more breathing room between a targeted element and the edges of the scrollport. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-padding-top) * */ interface scrollΞpaddingΞtop extends _ { set(val: any): void; } /** * Logical 'border-right-style'. Mapping depends on the parent element’s 'writing-mode', 'direction', and 'text-orientation'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-inline-end-style) * */ interface borderΞinlineΞendΞstyle extends _ { set(val: ΨlineΞstyle): void; } /** * Logical 'border-top-width'. Mapping depends on the parent element’s 'writing-mode', 'direction', and 'text-orientation'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-block-start-width) * */ interface borderΞblockΞstartΞwidth extends _ { set(val: Ψlength | ΨlineΞwidth): void; } /** * Logical 'border-bottom-width'. Mapping depends on the parent element’s 'writing-mode', 'direction', and 'text-orientation'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-block-end-width) * */ interface borderΞblockΞendΞwidth extends _ { set(val: Ψlength | ΨlineΞwidth): void; } /** * Logical 'border-bottom-color'. Mapping depends on the parent element’s 'writing-mode', 'direction', and 'text-orientation'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-block-end-color) * */ interface borderΞblockΞendΞcolor extends _ { set(val: Ψcolor): void; } /** * Logical 'border-left-style'. Mapping depends on the parent element’s 'writing-mode', 'direction', and 'text-orientation'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-inline-start-style) * */ interface borderΞinlineΞstartΞstyle extends _ { set(val: ΨlineΞstyle): void; } /** * Logical 'border-top-color'. Mapping depends on the parent element’s 'writing-mode', 'direction', and 'text-orientation'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-block-start-color) * */ interface borderΞblockΞstartΞcolor extends _ { set(val: Ψcolor): void; } /** * Logical 'border-bottom-style'. Mapping depends on the parent element’s 'writing-mode', 'direction', and 'text-orientation'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-block-end-style) * */ interface borderΞblockΞendΞstyle extends _ { set(val: ΨlineΞstyle): void; } /** * Logical 'border-top-style'. Mapping depends on the parent element’s 'writing-mode', 'direction', and 'text-orientation'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-block-start-style) * */ interface borderΞblockΞstartΞstyle extends _ { set(val: ΨlineΞstyle): void; } /** * The font-variation-settings CSS property provides low-level control over OpenType or TrueType font variations, by specifying the four letter axis names of the features you want to vary, along with their variation values. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/font-variation-settings) * */ interface fontΞvariationΞsettings extends _ { set(val: any): void; } /** * Controls the order that the three paint operations that shapes and text are rendered with: their fill, their stroke and any markers they might have. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/paint-order) * */ interface paintΞorder extends _ { set(val: this): void; fill: '' markers: '' /** The element is painted with the standard order of painting operations: the 'fill' is painted first, then its 'stroke' and finally its markers. */ normal: '' stroke: '' } /** * Specifies the color space for imaging operations performed via filter effects. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/color-interpolation-filters) * */ interface colorΞinterpolationΞfilters extends _ { set(val: this): void; /** Color operations are not required to occur in a particular color space. */ auto: '' /** Color operations should occur in the linearized RGB color space. */ linearRGB: '' /** Color operations should occur in the sRGB color space. */ sRGB: '' } /** * Specifies the marker that will be drawn at the last vertices of the given markable element. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/marker-end) * */ interface markerΞend extends _ { set(val: this | Ψurl): void; /** Indicates that no marker symbol will be drawn at the given vertex or vertices. */ none: '' /** Indicates that the <marker> element referenced will be used. */ url(): '' } /** * The scroll-padding-left property defines offsets for the left of the optimal viewing region of the scrollport: the region used as the target region for placing things in view of the user. This allows the author to exclude regions of the scrollport that are obscured by other content (such as fixed-positioned toolbars or sidebars) or simply to put more breathing room between a targeted element and the edges of the scrollport. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-padding-left) * */ interface scrollΞpaddingΞleft extends _ { set(val: any): void; } /** * Indicates what color to use to flood the current filter primitive subregion. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/flood-color) * */ interface floodΞcolor extends _ { set(val: Ψcolor): void; } /** * Indicates what opacity to use to flood the current filter primitive subregion. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/flood-opacity) * */ interface floodΞopacity extends _ { set(val: Ψnumber | Ψpercentage): void; } /** * Defines the color of the light source for filter primitives 'feDiffuseLighting' and 'feSpecularLighting'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/lighting-color) * */ interface lightingΞcolor extends _ { set(val: Ψcolor): void; } /** * Specifies the marker that will be drawn at the first vertices of the given markable element. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/marker-start) * */ interface markerΞstart extends _ { set(val: this | Ψurl): void; /** Indicates that no marker symbol will be drawn at the given vertex or vertices. */ none: '' /** Indicates that the <marker> element referenced will be used. */ url(): '' } /** * Specifies the marker that will be drawn at all vertices except the first and last. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/marker-mid) * */ interface markerΞmid extends _ { set(val: this | Ψurl): void; /** Indicates that no marker symbol will be drawn at the given vertex or vertices. */ none: '' /** Indicates that the <marker> element referenced will be used. */ url(): '' } /** * Specifies the marker symbol that shall be used for all points on the sets the value for all vertices on the given ‘path’ element or basic shape. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/marker) * */ interface marker extends _ { set(val: this | Ψurl): void; /** Indicates that no marker symbol will be drawn at the given vertex or vertices. */ none: '' /** Indicates that the <marker> element referenced will be used. */ url(): '' } /** * The place-content CSS shorthand property sets both the align-content and justify-content properties. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/place-content) * */ interface placeΞcontent extends _ { set(val: any): void; } /** * The offset-path CSS property specifies the offset path where the element gets positioned. The exact element’s position on the offset path is determined by the offset-distance property. An offset path is either a specified path with one or multiple sub-paths or the geometry of a not-styled basic shape. Each shape or path must define an initial position for the computed value of "0" for offset-distance and an initial direction which specifies the rotation of the object to the initial position. In this specification, a direction (or rotation) of 0 degrees is equivalent to the direction of the positive x-axis in the object’s local coordinate system. In other words, a rotation of 0 degree points to the right side of the UA if the object and its ancestors have no transformation applied. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/offset-path) * */ interface offsetΞpath extends _ { set(val: any): void; } /** * The offset-rotate CSS property defines the direction of the element while positioning along the offset path. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/offset-rotate) * */ interface offsetΞrotate extends _ { set(val: any): void; } /** * The offset-distance CSS property specifies a position along an offset-path. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/offset-distance) * */ interface offsetΞdistance extends _ { set(val: any): void; } /** * The transform-box CSS property defines the layout box to which the transform and transform-origin properties relate. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/transform-box) * */ interface transformΞbox extends _ { set(val: any): void; } /** * The CSS place-items shorthand property sets both the align-items and justify-items properties. The first value is the align-items property value, the second the justify-items one. If the second value is not present, the first value is also used for it. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/place-items) * */ interface placeΞitems extends _ { set(val: any): void; } /** * Logical 'max-height'. Mapping depends on the element’s 'writing-mode'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/max-inline-size) * */ interface maxΞinlineΞsize extends _ { set(val: this | Ψlength | Ψpercentage): void; /** No limit on the height of the box. */ none: '' } /** * Logical 'max-width'. Mapping depends on the element’s 'writing-mode'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/max-block-size) * */ interface maxΞblockΞsize extends _ { set(val: this | Ψlength | Ψpercentage): void; /** No limit on the width of the box. */ none: '' } /** * Used by the parent of elements with display: ruby-text to control the position of the ruby text with respect to its base. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/ruby-position) * */ interface rubyΞposition extends _ { set(val: this): void; /** The ruby text appears after the base. This is a relatively rare setting used in ideographic East Asian writing systems, most easily found in educational text. */ after: '' /** The ruby text appears before the base. This is the most common setting used in ideographic East Asian writing systems. */ before: '' inline: '' /** The ruby text appears on the right of the base. Unlike 'before' and 'after', this value is not relative to the text flow direction. */ right: '' } /** * The scroll-padding-right property defines offsets for the right of the optimal viewing region of the scrollport: the region used as the target region for placing things in view of the user. This allows the author to exclude regions of the scrollport that are obscured by other content (such as fixed-positioned toolbars or sidebars) or simply to put more breathing room between a targeted element and the edges of the scrollport. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-padding-right) * */ interface scrollΞpaddingΞright extends _ { set(val: any): void; } /** * The scroll-padding-bottom property defines offsets for the bottom of the optimal viewing region of the scrollport: the region used as the target region for placing things in view of the user. This allows the author to exclude regions of the scrollport that are obscured by other content (such as fixed-positioned toolbars or sidebars) or simply to put more breathing room between a targeted element and the edges of the scrollport. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-padding-bottom) * */ interface scrollΞpaddingΞbottom extends _ { set(val: any): void; } /** * The scroll-padding-inline-start property defines offsets for the start edge in the inline dimension of the optimal viewing region of the scrollport: the region used as the target region for placing things in view of the user. This allows the author to exclude regions of the scrollport that are obscured by other content (such as fixed-positioned toolbars or sidebars) or simply to put more breathing room between a targeted element and the edges of the scrollport. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-padding-inline-start) * */ interface scrollΞpaddingΞinlineΞstart extends _ { set(val: any): void; } /** * The scroll-padding-block-start property defines offsets for the start edge in the block dimension of the optimal viewing region of the scrollport: the region used as the target region for placing things in view of the user. This allows the author to exclude regions of the scrollport that are obscured by other content (such as fixed-positioned toolbars or sidebars) or simply to put more breathing room between a targeted element and the edges of the scrollport. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-padding-block-start) * */ interface scrollΞpaddingΞblockΞstart extends _ { set(val: any): void; } /** * The scroll-padding-block-end property defines offsets for the end edge in the block dimension of the optimal viewing region of the scrollport: the region used as the target region for placing things in view of the user. This allows the author to exclude regions of the scrollport that are obscured by other content (such as fixed-positioned toolbars or sidebars) or simply to put more breathing room between a targeted element and the edges of the scrollport. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-padding-block-end) * */ interface scrollΞpaddingΞblockΞend extends _ { set(val: any): void; } /** * The scroll-padding-inline-end property defines offsets for the end edge in the inline dimension of the optimal viewing region of the scrollport: the region used as the target region for placing things in view of the user. This allows the author to exclude regions of the scrollport that are obscured by other content (such as fixed-positioned toolbars or sidebars) or simply to put more breathing room between a targeted element and the edges of the scrollport. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-padding-inline-end) * */ interface scrollΞpaddingΞinlineΞend extends _ { set(val: any): void; } /** * The place-self CSS property is a shorthand property sets both the align-self and justify-self properties. The first value is the align-self property value, the second the justify-self one. If the second value is not present, the first value is also used for it. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/place-self) * */ interface placeΞself extends _ { set(val: any): void; } /** * The font-optical-sizing CSS property allows developers to control whether browsers render text with slightly differing visual representations to optimize viewing at different sizes, or not. This only works for fonts that have an optical size variation axis. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/font-optical-sizing) * */ interface fontΞopticalΞsizing extends _ { set(val: any): void; } /** * The grid CSS property is a shorthand property that sets all of the explicit grid properties ('grid-template-rows', 'grid-template-columns', and 'grid-template-areas'), and all the implicit grid properties ('grid-auto-rows', 'grid-auto-columns', and 'grid-auto-flow'), in a single declaration. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/grid) * */ interface grid extends _ { set(val: Ψidentifier | Ψlength | Ψpercentage | Ψstring | this): void; } /** * Logical 'border-left'. Mapping depends on the parent element’s 'writing-mode', 'direction', and 'text-orientation'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-inline-start) * */ interface borderΞinlineΞstart extends _ { set(val: Ψlength | ΨlineΞwidth | ΨlineΞstyle | Ψcolor): void; } /** * Logical 'border-right'. Mapping depends on the parent element’s 'writing-mode', 'direction', and 'text-orientation'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-inline-end) * */ interface borderΞinlineΞend extends _ { set(val: Ψlength | ΨlineΞwidth | ΨlineΞstyle | Ψcolor): void; } /** * Logical 'border-bottom'. Mapping depends on the parent element’s 'writing-mode', 'direction', and 'text-orientation'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-block-end) * */ interface borderΞblockΞend extends _ { set(val: Ψlength | ΨlineΞwidth | ΨlineΞstyle | Ψcolor): void; } /** * The offset CSS property is a shorthand property for animating an element along a defined path. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/offset) * */ interface offset extends _ { set(val: any): void; } /** * Logical 'border-top'. Mapping depends on the parent element’s 'writing-mode', 'direction', and 'text-orientation'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-block-start) * */ interface borderΞblockΞstart extends _ { set(val: Ψlength | ΨlineΞwidth | ΨlineΞstyle | Ψcolor): void; } /** * The scroll-padding-block property is a shorthand property which sets the scroll-padding longhands for the block dimension. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-padding-block) * */ interface scrollΞpaddingΞblock extends _ { set(val: any, arg1: any): void; } /** * The scroll-padding-inline property is a shorthand property which sets the scroll-padding longhands for the inline dimension. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-padding-inline) * */ interface scrollΞpaddingΞinline extends _ { set(val: any, arg1: any): void; } /** * The overscroll-behavior-block CSS property sets the browser's behavior when the block direction boundary of a scrolling area is reached. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/overscroll-behavior-block) * */ interface overscrollΞbehaviorΞblock extends _ { set(val: any): void; } /** * The overscroll-behavior-inline CSS property sets the browser's behavior when the inline direction boundary of a scrolling area is reached. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/overscroll-behavior-inline) * */ interface overscrollΞbehaviorΞinline extends _ { set(val: any): void; } /** * Shorthand property for setting 'motion-path', 'motion-offset' and 'motion-rotation'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/motion) * */ interface motion extends _ { set(val: this | Ψurl | Ψlength | Ψpercentage | Ψangle | Ψshape | ΨgeometryΞbox): void; /** No motion path gets created. */ none: '' /** Defines an SVG path as a string, with optional 'fill-rule' as the first argument. */ path(): '' /** Indicates that the object is rotated by the angle of the direction of the motion path. */ auto: '' /** Indicates that the object is rotated by the angle of the direction of the motion path plus 180 degrees. */ reverse: '' } /** * Preserves the readability of text when font fallback occurs by adjusting the font-size so that the x-height is the same regardless of the font used. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/font-size-adjust) * */ interface fontΞsizeΞadjust extends _ { set(val: this | Ψnumber): void; /** Do not preserve the font’s x-height. */ none: '' } /** * The inset CSS property defines the logical block and inline start and end offsets of an element, which map to physical offsets depending on the element's writing mode, directionality, and text orientation. It corresponds to the top and bottom, or right and left properties depending on the values defined for writing-mode, direction, and text-orientation. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/inset) * */ interface inset extends _ { set(val: any, arg1: any, arg2: any, arg3: any): void; } /** * Selects the justification algorithm used when 'text-align' is set to 'justify'. The property applies to block containers, but the UA may (but is not required to) also support it on inline elements. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/text-justify) * */ interface textΞjustify extends _ { set(val: this): void; /** The UA determines the justification algorithm to follow, based on a balance between performance and adequate presentation quality. */ auto: '' /** Justification primarily changes spacing both at word separators and at grapheme cluster boundaries in all scripts except those in the connected and cursive groups. This value is sometimes used in e.g. Japanese, often with the 'text-align-last' property. */ distribute: '' distributeΞallΞlines: '' /** Justification primarily changes spacing at word separators and at grapheme cluster boundaries in clustered scripts. This value is typically used for Southeast Asian scripts such as Thai. */ interΞcluster: '' /** Justification primarily changes spacing at word separators and at inter-graphemic boundaries in scripts that use no word spaces. This value is typically used for CJK languages. */ interΞideograph: '' /** Justification primarily changes spacing at word separators. This value is typically used for languages that separate words using spaces, like English or (sometimes) Korean. */ interΞword: '' /** Justification primarily stretches Arabic and related scripts through the use of kashida or other calligraphic elongation. */ kashida: '' newspaper: '' } /** * Specifies the motion path the element gets positioned at. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/motion-path) * */ interface motionΞpath extends _ { set(val: this | Ψurl | Ψshape | ΨgeometryΞbox): void; /** No motion path gets created. */ none: '' /** Defines an SVG path as a string, with optional 'fill-rule' as the first argument. */ path(): '' } /** * The inset-inline-start CSS property defines the logical inline start inset of an element, which maps to a physical offset depending on the element's writing mode, directionality, and text orientation. It corresponds to the top, right, bottom, or left property depending on the values defined for writing-mode, direction, and text-orientation. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/inset-inline-start) * */ interface insetΞinlineΞstart extends _ { set(val: any): void; } /** * The inset-inline-end CSS property defines the logical inline end inset of an element, which maps to a physical inset depending on the element's writing mode, directionality, and text orientation. It corresponds to the top, right, bottom, or left property depending on the values defined for writing-mode, direction, and text-orientation. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/inset-inline-end) * */ interface insetΞinlineΞend extends _ { set(val: any): void; } /** * The scale CSS property allows you to specify scale transforms individually and independently of the transform property. This maps better to typical user interface usage, and saves having to remember the exact order of transform functions to specify in the transform value. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scale) * * @alias scale */ interface scale extends _ { set(val: any): void; } /** @proxy scale */ interface scale extends scale { } /** * The translate CSS property allows you to specify translation transforms individually and independently of the transform property. This maps better to typical user interface usage, and saves having to remember the exact order of transform functions to specify in the transform value. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/translate) * */ interface translate extends _ { set(val: any): void; } /** * Defines an anchor point of the box positioned along the path. The anchor point specifies the point of the box which is to be considered as the point that is moved along the path. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/offset-anchor) * */ interface offsetΞanchor extends _ { set(val: any): void; } /** * Specifies the initial position of the offset path. If position is specified with static, offset-position would be ignored. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/offset-position) * */ interface offsetΞposition extends _ { set(val: any): void; } /** * The padding-block CSS property defines the logical block start and end padding of an element, which maps to physical padding properties depending on the element's writing mode, directionality, and text orientation. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/padding-block) * */ interface paddingΞblock extends _ { set(val: any, arg1: any): void; } /** * The orientation CSS @media media feature can be used to apply styles based on the orientation of the viewport (or the page box, for paged media). * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/orientation) * */ interface orientation extends _ { set(val: any): void; } /** * The user-zoom CSS descriptor controls whether or not the user can change the zoom factor of a document defined by @viewport. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/user-zoom) * */ interface userΞzoom extends _ { set(val: any): void; } /** * The margin-block CSS property defines the logical block start and end margins of an element, which maps to physical margins depending on the element's writing mode, directionality, and text orientation. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/margin-block) * */ interface marginΞblock extends _ { set(val: any, arg1: any): void; } /** * The margin-inline CSS property defines the logical inline start and end margins of an element, which maps to physical margins depending on the element's writing mode, directionality, and text orientation. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/margin-inline) * */ interface marginΞinline extends _ { set(val: any, arg1: any): void; } /** * The padding-inline CSS property defines the logical inline start and end padding of an element, which maps to physical padding properties depending on the element's writing mode, directionality, and text orientation. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/padding-inline) * */ interface paddingΞinline extends _ { set(val: any, arg1: any): void; } /** * The inset-block CSS property defines the logical block start and end offsets of an element, which maps to physical offsets depending on the element's writing mode, directionality, and text orientation. It corresponds to the top and bottom, or right and left properties depending on the values defined for writing-mode, direction, and text-orientation. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/inset-block) * */ interface insetΞblock extends _ { set(val: any, arg1: any): void; } /** * The inset-inline CSS property defines the logical block start and end offsets of an element, which maps to physical offsets depending on the element's writing mode, directionality, and text orientation. It corresponds to the top and bottom, or right and left properties depending on the values defined for writing-mode, direction, and text-orientation. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/inset-inline) * */ interface insetΞinline extends _ { set(val: any, arg1: any): void; } /** * The border-block-color CSS property defines the color of the logical block borders of an element, which maps to a physical border color depending on the element's writing mode, directionality, and text orientation. It corresponds to the border-top-color and border-bottom-color, or border-right-color and border-left-color property depending on the values defined for writing-mode, direction, and text-orientation. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-block-color) * */ interface borderΞblockΞcolor extends _ { set(val: any, arg1: any): void; } /** * The border-block CSS property is a shorthand property for setting the individual logical block border property values in a single place in the style sheet. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-block) * */ interface borderΞblock extends _ { set(val: any): void; } /** * The border-inline CSS property is a shorthand property for setting the individual logical inline border property values in a single place in the style sheet. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-inline) * */ interface borderΞinline extends _ { set(val: any): void; } /** * The inset-block-start CSS property defines the logical block start offset of an element, which maps to a physical offset depending on the element's writing mode, directionality, and text orientation. It corresponds to the top, right, bottom, or left property depending on the values defined for writing-mode, direction, and text-orientation. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/inset-block-start) * */ interface insetΞblockΞstart extends _ { set(val: any): void; } /** * The inset-block-end CSS property defines the logical block end offset of an element, which maps to a physical offset depending on the element's writing mode, directionality, and text orientation. It corresponds to the top, right, bottom, or left property depending on the values defined for writing-mode, direction, and text-orientation. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/inset-block-end) * */ interface insetΞblockΞend extends _ { set(val: any): void; } /** * Deprecated. Use 'isolation' property instead when support allows. Specifies how the accumulation of the background image is managed. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/enable-background) * */ interface enableΞbackground extends _ { set(val: this | Ψinteger | Ψlength | Ψpercentage): void; /** If the ancestor container element has a property of new, then all graphics elements within the current container are rendered both on the parent's background image and onto the target. */ accumulate: '' /** Create a new background image canvas. All children of the current container element can access the background, and they will be rendered onto both the parent's background image canvas in addition to the target device. */ new: '' } /** * Controls glyph orientation when the inline-progression-direction is horizontal. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/glyph-orientation-horizontal) * */ interface glyphΞorientationΞhorizontal extends _ { set(val: Ψangle | Ψnumber): void; } /** * Controls glyph orientation when the inline-progression-direction is vertical. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/glyph-orientation-vertical) * */ interface glyphΞorientationΞvertical extends _ { set(val: this | Ψangle | Ψnumber): void; /** Sets the orientation based on the fullwidth or non-fullwidth characters and the most common orientation. */ auto: '' } /** * Indicates whether the user agent should adjust inter-glyph spacing based on kerning tables that are included in the relevant font or instead disable auto-kerning and set inter-character spacing to a specific length. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/kerning) * */ interface kerning extends _ { set(val: this | Ψlength): void; /** Indicates that the user agent should adjust inter-glyph spacing based on kerning tables that are included in the font that will be used. */ auto: '' } /** * The image-resolution property specifies the intrinsic resolution of all raster images used in or on the element. It affects both content images (e.g. replaced elements and generated content) and decorative images (such as background-image). The intrinsic resolution of an image is used to determine the image’s intrinsic dimensions. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/image-resolution) * */ interface imageΞresolution extends _ { set(val: any): void; } /** * The max-zoom CSS descriptor sets the maximum zoom factor of a document defined by the @viewport at-rule. The browser will not zoom in any further than this, whether automatically or at the user's request. A zoom factor of 1.0 or 100% corresponds to no zooming. Larger values are zoomed in. Smaller values are zoomed out. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/max-zoom) * */ interface maxΞzoom extends _ { set(val: any): void; } /** * The min-zoom CSS descriptor sets the minimum zoom factor of a document defined by the @viewport at-rule. The browser will not zoom out any further than this, whether automatically or at the user's request. A zoom factor of 1.0 or 100% corresponds to no zooming. Larger values are zoomed in. Smaller values are zoomed out. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/min-zoom) * */ interface minΞzoom extends _ { set(val: any): void; } /** * A distance that describes the position along the specified motion path. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/motion-offset) * */ interface motionΞoffset extends _ { set(val: Ψlength | Ψpercentage): void; } /** * Defines the direction of the element while positioning along the motion path. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/motion-rotation) * */ interface motionΞrotation extends _ { set(val: this | Ψangle): void; /** Indicates that the object is rotated by the angle of the direction of the motion path. */ auto: '' /** Indicates that the object is rotated by the angle of the direction of the motion path plus 180 degrees. */ reverse: '' } /** * Defines the positioning of snap points along the x axis of the scroll container it is applied to. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-snap-points-x) * */ interface scrollΞsnapΞpointsΞx extends _ { set(val: this): void; /** No snap points are defined by this scroll container. */ none: '' /** Defines an interval at which snap points are defined, starting from the container’s relevant start edge. */ repeat(): '' } /** * Defines the positioning of snap points along the y axis of the scroll container it is applied to. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-snap-points-y) * */ interface scrollΞsnapΞpointsΞy extends _ { set(val: this): void; /** No snap points are defined by this scroll container. */ none: '' /** Defines an interval at which snap points are defined, starting from the container’s relevant start edge. */ repeat(): '' } /** * Defines the x and y coordinate within the element which will align with the nearest ancestor scroll container’s snap-destination for the respective axis. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-snap-coordinate) * */ interface scrollΞsnapΞcoordinate extends _ { set(val: this | Ψposition | Ψlength | Ψpercentage): void; /** Specifies that this element does not contribute a snap point. */ none: '' } /** * Define the x and y coordinate within the scroll container’s visual viewport which element snap points will align with. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-snap-destination) * */ interface scrollΞsnapΞdestination extends _ { set(val: Ψposition | Ψlength | Ψpercentage): void; } /** * The border-block-style CSS property defines the style of the logical block borders of an element, which maps to a physical border style depending on the element's writing mode, directionality, and text orientation. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/viewport-fit) * */ interface viewportΞfit extends _ { set(val: any): void; } /** * The border-block-style CSS property defines the style of the logical block borders of an element, which maps to a physical border style depending on the element's writing mode, directionality, and text orientation. It corresponds to the border-top-style and border-bottom-style, or border-left-style and border-right-style properties depending on the values defined for writing-mode, direction, and text-orientation. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-block-style) * */ interface borderΞblockΞstyle extends _ { set(val: any): void; } /** * The border-block-width CSS property defines the width of the logical block borders of an element, which maps to a physical border width depending on the element's writing mode, directionality, and text orientation. It corresponds to the border-top-width and border-bottom-width, or border-left-width, and border-right-width property depending on the values defined for writing-mode, direction, and text-orientation. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-block-width) * */ interface borderΞblockΞwidth extends _ { set(val: any): void; } /** * The border-inline-color CSS property defines the color of the logical inline borders of an element, which maps to a physical border color depending on the element's writing mode, directionality, and text orientation. It corresponds to the border-top-color and border-bottom-color, or border-right-color and border-left-color property depending on the values defined for writing-mode, direction, and text-orientation. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-inline-color) * */ interface borderΞinlineΞcolor extends _ { set(val: any, arg1: any): void; } /** * The border-inline-style CSS property defines the style of the logical inline borders of an element, which maps to a physical border style depending on the element's writing mode, directionality, and text orientation. It corresponds to the border-top-style and border-bottom-style, or border-left-style and border-right-style properties depending on the values defined for writing-mode, direction, and text-orientation. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-inline-style) * */ interface borderΞinlineΞstyle extends _ { set(val: any): void; } /** * The border-inline-width CSS property defines the width of the logical inline borders of an element, which maps to a physical border width depending on the element's writing mode, directionality, and text orientation. It corresponds to the border-top-width and border-bottom-width, or border-left-width, and border-right-width property depending on the values defined for writing-mode, direction, and text-orientation. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-inline-width) * */ interface borderΞinlineΞwidth extends _ { set(val: any): void; } /** * The overflow-block CSS media feature can be used to test how the output device handles content that overflows the initial containing block along the block axis. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/overflow-block) * */ interface overflowΞblock extends _ { set(val: any): void; } /** * `@counter-style` descriptor. Specifies the symbols used by the marker-construction algorithm specified by the system descriptor. Needs to be specified if the counter system is 'additive'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/additive-symbols) * */ interface additiveΞsymbols extends _ { set(val: Ψinteger | Ψstring | Ψimage | Ψidentifier): void; } /** * Provides alternative text for assistive technology to replace the generated content of a ::before or ::after element. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/alt) * */ interface alt extends _ { set(val: Ψstring | this): void; } /** * IE only. Used to extend behaviors of the browser. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/behavior) * */ interface behavior extends _ { set(val: Ψurl): void; } /** * Specifies whether individual boxes are treated as broken pieces of one continuous box, or whether each box is individually wrapped with the border and padding. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/box-decoration-break) * */ interface boxΞdecorationΞbreak extends _ { set(val: this): void; /** Each box is independently wrapped with the border and padding. */ clone: '' /** The effect is as though the element were rendered with no breaks present, and then sliced by the breaks afterward. */ slice: '' } /** * `@counter-style` descriptor. Specifies a fallback counter style to be used when the current counter style can’t create a representation for a given counter value. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/fallback) * */ interface fallback extends _ { set(val: Ψidentifier): void; } /** * The value of 'normal' implies that when rendering with OpenType fonts the language of the document is used to infer the OpenType language system, used to select language specific features when rendering. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/font-language-override) * */ interface fontΞlanguageΞoverride extends _ { set(val: this | Ψstring): void; /** Implies that when rendering with OpenType fonts the language of the document is used to infer the OpenType language system, used to select language specific features when rendering. */ normal: '' } /** * Controls whether user agents are allowed to synthesize bold or oblique font faces when a font family lacks bold or italic faces. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/font-synthesis) * */ interface fontΞsynthesis extends _ { set(val: this): void; /** Disallow all synthetic faces. */ none: '' /** Allow synthetic italic faces. */ style: '' /** Allow synthetic bold faces. */ weight: '' } /** * For any given character, fonts can provide a variety of alternate glyphs in addition to the default glyph for that character. This property provides control over the selection of these alternate glyphs. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/font-variant-alternates) * */ interface fontΞvariantΞalternates extends _ { set(val: this): void; /** Enables display of alternate annotation forms. */ annotation(): '' /** Enables display of specific character variants. */ characterΞvariant(): '' /** Enables display of historical forms. */ historicalΞforms: '' /** None of the features are enabled. */ normal: '' /** Enables replacement of default glyphs with ornaments, if provided in the font. */ ornaments(): '' /** Enables display with stylistic sets. */ styleset(): '' /** Enables display of stylistic alternates. */ stylistic(): '' /** Enables display of swash glyphs. */ swash(): '' } /** * Specifies the vertical position * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/font-variant-position) * */ interface fontΞvariantΞposition extends _ { set(val: this): void; /** None of the features are enabled. */ normal: '' /** Enables display of subscript variants (OpenType feature: subs). */ sub: '' /** Enables display of superscript variants (OpenType feature: sups). */ super: '' } /** * Controls the state of the input method editor for text fields. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/ime-mode) * */ interface imeΞmode extends _ { set(val: this): void; /** The input method editor is initially active; text entry is performed using it unless the user specifically dismisses it. */ active: '' /** No change is made to the current input method editor state. This is the default. */ auto: '' /** The input method editor is disabled and may not be activated by the user. */ disabled: '' /** The input method editor is initially inactive, but the user may activate it if they wish. */ inactive: '' /** The IME state should be normal; this value can be used in a user style sheet to override the page setting. */ normal: '' } /** * Sets the mask layer image of an element. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/mask-image) * */ interface maskΞimage extends _ { set(val: this | Ψurl | Ψimage, arg1: any, arg2: any, arg3: any): void; /** Counts as a transparent black image layer. */ none: '' /** Reference to a <mask element or to a CSS image. */ url(): '' } /** * Indicates whether the mask layer image is treated as luminance mask or alpha mask. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/mask-mode) * */ interface maskΞmode extends _ { set(val: this | Ψurl | Ψimage, arg1: any, arg2: any, arg3: any): void; /** Alpha values of the mask layer image should be used as the mask values. */ alpha: '' /** Use alpha values if 'mask-image' is an image, luminance if a <mask> element or a CSS image. */ auto: '' /** Luminance values of the mask layer image should be used as the mask values. */ luminance: '' } /** * Specifies the mask positioning area. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/mask-origin) * */ interface maskΞorigin extends _ { set(val: ΨgeometryΞbox | this, arg1: any, arg2: any, arg3: any): void; } /** * Specifies how mask layer images are positioned. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/mask-position) * */ interface maskΞposition extends _ { set(val: Ψposition | Ψlength | Ψpercentage, arg1: any, arg2: any, arg3: any): void; } /** * Specifies how mask layer images are tiled after they have been sized and positioned. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/mask-repeat) * */ interface maskΞrepeat extends _ { set(val: Ψrepeat, arg1: any, arg2: any, arg3: any): void; } /** * Specifies the size of the mask layer images. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/mask-size) * */ interface maskΞsize extends _ { set(val: this | Ψlength | Ψpercentage, arg1: any, arg2: any, arg3: any): void; /** Resolved by using the image’s intrinsic ratio and the size of the other dimension, or failing that, using the image’s intrinsic size, or failing that, treating it as 100%. */ auto: '' /** Scale the image, while preserving its intrinsic aspect ratio (if any), to the largest size such that both its width and its height can fit inside the background positioning area. */ contain: '' /** Scale the image, while preserving its intrinsic aspect ratio (if any), to the smallest size such that both its width and its height can completely cover the background positioning area. */ cover: '' } /** * Provides an way to control directional focus navigation. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/nav-down) * */ interface navΞdown extends _ { set(val: this | Ψidentifier | Ψstring): void; /** The user agent automatically determines which element to navigate the focus to in response to directional navigational input. */ auto: '' /** Indicates that the user agent should target the frame that the element is in. */ current: '' /** Indicates that the user agent should target the full window. */ root: '' } /** * Provides an input-method-neutral way of specifying the sequential navigation order (also known as 'tabbing order'). * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/nav-index) * */ interface navΞindex extends _ { set(val: this | Ψnumber): void; /** The element's sequential navigation order is assigned automatically by the user agent. */ auto: '' } /** * Provides an way to control directional focus navigation. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/nav-left) * */ interface navΞleft extends _ { set(val: this | Ψidentifier | Ψstring): void; /** The user agent automatically determines which element to navigate the focus to in response to directional navigational input. */ auto: '' /** Indicates that the user agent should target the frame that the element is in. */ current: '' /** Indicates that the user agent should target the full window. */ root: '' } /** * Provides an way to control directional focus navigation. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/nav-right) * */ interface navΞright extends _ { set(val: this | Ψidentifier | Ψstring): void; /** The user agent automatically determines which element to navigate the focus to in response to directional navigational input. */ auto: '' /** Indicates that the user agent should target the frame that the element is in. */ current: '' /** Indicates that the user agent should target the full window. */ root: '' } /** * Provides an way to control directional focus navigation. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/nav-up) * */ interface navΞup extends _ { set(val: this | Ψidentifier | Ψstring): void; /** The user agent automatically determines which element to navigate the focus to in response to directional navigational input. */ auto: '' /** Indicates that the user agent should target the frame that the element is in. */ current: '' /** Indicates that the user agent should target the full window. */ root: '' } /** * `@counter-style` descriptor. Defines how to alter the representation when the counter value is negative. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/negative) * */ interface negative extends _ { set(val: Ψimage | Ψidentifier | Ψstring): void; } /** * Logical 'bottom'. Mapping depends on the parent element’s 'writing-mode', 'direction', and 'text-orientation'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/offset-block-end) * */ interface offsetΞblockΞend extends _ { set(val: this | Ψlength | Ψpercentage): void; /** For non-replaced elements, the effect of this value depends on which of related properties have the value 'auto' as well. */ auto: '' } /** * Logical 'top'. Mapping depends on the parent element’s 'writing-mode', 'direction', and 'text-orientation'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/offset-block-start) * */ interface offsetΞblockΞstart extends _ { set(val: this | Ψlength | Ψpercentage): void; /** For non-replaced elements, the effect of this value depends on which of related properties have the value 'auto' as well. */ auto: '' } /** * Logical 'right'. Mapping depends on the parent element’s 'writing-mode', 'direction', and 'text-orientation'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/offset-inline-end) * */ interface offsetΞinlineΞend extends _ { set(val: this | Ψlength | Ψpercentage): void; /** For non-replaced elements, the effect of this value depends on which of related properties have the value 'auto' as well. */ auto: '' } /** * Logical 'left'. Mapping depends on the parent element’s 'writing-mode', 'direction', and 'text-orientation'. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/offset-inline-start) * */ interface offsetΞinlineΞstart extends _ { set(val: this | Ψlength | Ψpercentage): void; /** For non-replaced elements, the effect of this value depends on which of related properties have the value 'auto' as well. */ auto: '' } /** * `@counter-style` descriptor. Specifies a “fixed-width” counter style, where representations shorter than the pad value are padded with a particular <symbol> * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/pad) * */ interface pad extends _ { set(val: Ψinteger | Ψimage | Ψstring | Ψidentifier): void; } /** * `@counter-style` descriptor. Specifies a <symbol> that is prepended to the marker representation. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/prefix) * */ interface prefix extends _ { set(val: Ψimage | Ψstring | Ψidentifier): void; } /** * `@counter-style` descriptor. Defines the ranges over which the counter style is defined. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/range) * */ interface range extends _ { set(val: this | Ψinteger): void; /** The range depends on the counter system. */ auto: '' /** If used as the first value in a range, it represents negative infinity; if used as the second value, it represents positive infinity. */ infinite: '' } /** * Specifies how text is distributed within the various ruby boxes when their contents do not exactly fill their respective boxes. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/ruby-align) * */ interface rubyΞalign extends _ { set(val: this): void; /** The user agent determines how the ruby contents are aligned. This is the initial value. */ auto: '' /** The ruby content is centered within its box. */ center: '' /** If the width of the ruby text is smaller than that of the base, then the ruby text contents are evenly distributed across the width of the base, with the first and last ruby text glyphs lining up with the corresponding first and last base glyphs. If the width of the ruby text is at least the width of the base, then the letters of the base are evenly distributed across the width of the ruby text. */ distributeΞletter: '' /** If the width of the ruby text is smaller than that of the base, then the ruby text contents are evenly distributed across the width of the base, with a certain amount of white space preceding the first and following the last character in the ruby text. That amount of white space is normally equal to half the amount of inter-character space of the ruby text. */ distributeΞspace: '' /** The ruby text content is aligned with the start edge of the base. */ left: '' /** If the ruby text is not adjacent to a line edge, it is aligned as in 'auto'. If it is adjacent to a line edge, then it is still aligned as in auto, but the side of the ruby text that touches the end of the line is lined up with the corresponding edge of the base. */ lineΞedge: '' /** The ruby text content is aligned with the end edge of the base. */ right: '' /** The ruby text content is aligned with the start edge of the base. */ start: '' /** The ruby content expands as defined for normal text justification (as defined by 'text-justify'), */ spaceΞbetween: '' /** As for 'space-between' except that there exists an extra justification opportunities whose space is distributed half before and half after the ruby content. */ spaceΞaround: '' } /** * Determines whether, and on which side, ruby text is allowed to partially overhang any adjacent text in addition to its own base, when the ruby text is wider than the ruby base. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/ruby-overhang) * */ interface rubyΞoverhang extends _ { set(val: this): void; /** The ruby text can overhang text adjacent to the base on either side. This is the initial value. */ auto: '' /** The ruby text can overhang the text that follows it. */ end: '' /** The ruby text cannot overhang any text adjacent to its base, only its own base. */ none: '' /** The ruby text can overhang the text that precedes it. */ start: '' } /** * Determines whether, and on which side, ruby text is allowed to partially overhang any adjacent text in addition to its own base, when the ruby text is wider than the ruby base. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/ruby-span) * */ interface rubyΞspan extends _ { set(val: this): void; /** The value of attribute 'x' is a string value. The string value is evaluated as a <number> to determine the number of ruby base elements to be spanned by the annotation element. */ attr(x): '' /** No spanning. The computed value is '1'. */ none: '' } /** * Determines the color of the top and left edges of the scroll box and scroll arrows of a scroll bar. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scrollbar-3dlight-color) * */ interface scrollbarΞ3dlightΞcolor extends _ { set(val: Ψcolor): void; } /** * Determines the color of the arrow elements of a scroll arrow. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scrollbar-arrow-color) * */ interface scrollbarΞarrowΞcolor extends _ { set(val: Ψcolor): void; } /** * Determines the color of the main elements of a scroll bar, which include the scroll box, track, and scroll arrows. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scrollbar-base-color) * */ interface scrollbarΞbaseΞcolor extends _ { set(val: Ψcolor): void; } /** * Determines the color of the gutter of a scroll bar. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scrollbar-darkshadow-color) * */ interface scrollbarΞdarkshadowΞcolor extends _ { set(val: Ψcolor): void; } /** * Determines the color of the scroll box and scroll arrows of a scroll bar. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scrollbar-face-color) * */ interface scrollbarΞfaceΞcolor extends _ { set(val: Ψcolor): void; } /** * Determines the color of the top and left edges of the scroll box and scroll arrows of a scroll bar. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scrollbar-highlight-color) * */ interface scrollbarΞhighlightΞcolor extends _ { set(val: Ψcolor): void; } /** * Determines the color of the bottom and right edges of the scroll box and scroll arrows of a scroll bar. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scrollbar-shadow-color) * */ interface scrollbarΞshadowΞcolor extends _ { set(val: Ψcolor): void; } /** * Determines the color of the track element of a scroll bar. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scrollbar-track-color) * */ interface scrollbarΞtrackΞcolor extends _ { set(val: Ψcolor): void; } /** * `@counter-style` descriptor. Specifies a <symbol> that is appended to the marker representation. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/suffix) * */ interface suffix extends _ { set(val: Ψimage | Ψstring | Ψidentifier): void; } /** * `@counter-style` descriptor. Specifies which algorithm will be used to construct the counter’s representation based on the counter value. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/system) * */ interface system extends _ { set(val: this | Ψinteger): void; /** Represents “sign-value” numbering systems, which, rather than using reusing digits in different positions to change their value, define additional digits with much larger values, so that the value of the number can be obtained by adding all the digits together. */ additive: '' /** Interprets the list of counter symbols as digits to an alphabetic numbering system, similar to the default lower-alpha counter style, which wraps from "a", "b", "c", to "aa", "ab", "ac". */ alphabetic: '' /** Cycles repeatedly through its provided symbols, looping back to the beginning when it reaches the end of the list. */ cyclic: '' /** Use the algorithm of another counter style, but alter other aspects. */ extends: '' /** Runs through its list of counter symbols once, then falls back. */ fixed: '' /** interprets the list of counter symbols as digits to a "place-value" numbering system, similar to the default 'decimal' counter style. */ numeric: '' /** Cycles repeatedly through its provided symbols, doubling, tripling, etc. the symbols on each successive pass through the list. */ symbolic: '' } /** * `@counter-style` descriptor. Specifies the symbols used by the marker-construction algorithm specified by the system descriptor. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/symbols) * */ interface symbols extends _ { set(val: Ψimage | Ψstring | Ψidentifier): void; } /** * The aspect-ratio CSS property sets a preferred aspect ratio for the box, which will be used in the calculation of auto sizes and some other layout functions. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio) * */ interface aspectΞratio extends _ { set(val: any): void; } /** * In combination with elevation, the azimuth CSS property enables different audio sources to be positioned spatially for aural presentation. This is important in that it provides a natural way to tell several voices apart, as each can be positioned to originate at a different location on the sound stage. Stereo output produce a lateral sound stage, while binaural headphones and multi-speaker setups allow for a fully three-dimensional stage. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/azimuth) * */ interface azimuth extends _ { set(val: any): void; } /** * The border-end-end-radius CSS property defines a logical border radius on an element, which maps to a physical border radius that depends on on the element's writing-mode, direction, and text-orientation. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-end-end-radius) * */ interface borderΞendΞendΞradius extends _ { set(val: Ψradius, arg1: any): void; } /** * The border-end-start-radius CSS property defines a logical border radius on an element, which maps to a physical border radius depending on the element's writing-mode, direction, and text-orientation. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-end-start-radius) * */ interface borderΞendΞstartΞradius extends _ { set(val: Ψradius, arg1: any): void; } /** * The border-start-end-radius CSS property defines a logical border radius on an element, which maps to a physical border radius depending on the element's writing-mode, direction, and text-orientation. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-start-end-radius) * */ interface borderΞstartΞendΞradius extends _ { set(val: Ψradius, arg1: any): void; } /** * The border-start-start-radius CSS property defines a logical border radius on an element, which maps to a physical border radius that depends on the element's writing-mode, direction, and text-orientation. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-start-start-radius) * */ interface borderΞstartΞstartΞradius extends _ { set(val: Ψradius, arg1: any): void; } /** * The box-ordinal-group CSS property assigns the flexbox's child elements to an ordinal group. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/box-ordinal-group) * */ interface boxΞordinalΞgroup extends _ { set(val: any): void; } /** * The color-adjust property is a non-standard CSS extension that can be used to force printing of background colors and images in browsers based on the WebKit engine. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/color-adjust) * */ interface colorΞadjust extends _ { set(val: any): void; } /** * The counter-set CSS property sets a CSS counter to a given value. It manipulates the value of existing counters, and will only create new counters if there isn't already a counter of the given name on the element. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/counter-set) * */ interface counterΞset extends _ { set(val: any): void; } /** * The hanging-punctuation CSS property specifies whether a punctuation mark should hang at the start or end of a line of text. Hanging punctuation may be placed outside the line box. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/hanging-punctuation) * */ interface hangingΞpunctuation extends _ { set(val: any): void; } /** * The initial-letter CSS property specifies styling for dropped, raised, and sunken initial letters. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/initial-letter) * */ interface initialΞletter extends _ { set(val: any): void; } /** * The initial-letter-align CSS property specifies the alignment of initial letters within a paragraph. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/initial-letter-align) * */ interface initialΞletterΞalign extends _ { set(val: any): void; } /** * The line-clamp property allows limiting the contents of a block container to the specified number of lines; remaining content is fragmented away and neither rendered nor measured. Optionally, it also allows inserting content into the last line box to indicate the continuity of truncated/interrupted content. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/line-clamp) * */ interface lineΞclamp extends _ { set(val: any): void; } /** * The line-height-step CSS property defines the step units for line box heights. When the step unit is positive, line box heights are rounded up to the closest multiple of the unit. Negative values are invalid. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height-step) * */ interface lineΞheightΞstep extends _ { set(val: any): void; } /** * The margin-trim property allows the container to trim the margins of its children where they adjoin the container’s edges. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/margin-trim) * */ interface marginΞtrim extends _ { set(val: any): void; } /** * The mask-border CSS property lets you create a mask along the edge of an element's border. This property is a shorthand for mask-border-source, mask-border-slice, mask-border-width, mask-border-outset, mask-border-repeat, and mask-border-mode. As with all shorthand properties, any omitted sub-values will be set to their initial value. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/mask-border) * */ interface maskΞborder extends _ { set(val: any): void; } /** * The mask-border-mode CSS property specifies the blending mode used in a mask border. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/mask-border-mode) * */ interface maskΞborderΞmode extends _ { set(val: any): void; } /** * The mask-border-outset CSS property specifies the distance by which an element's mask border is set out from its border box. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/mask-border-outset) * */ interface maskΞborderΞoutset extends _ { set(val: any, arg1: any, arg2: any, arg3: any): void; } /** * The mask-border-repeat CSS property defines how the edge regions of a source image are adjusted to fit the dimensions of an element's mask border. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/mask-border-repeat) * */ interface maskΞborderΞrepeat extends _ { set(val: any, arg1: any): void; } /** * The mask-border-slice CSS property divides the image specified by mask-border-source into regions. These regions are used to form the components of an element's mask border. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/mask-border-slice) * */ interface maskΞborderΞslice extends _ { set(val: any, arg1: any, arg2: any, arg3: any): void; } /** * The mask-border-source CSS property specifies the source image used to create an element's mask border. The mask-border-slice property is used to divide the source image into regions, which are then dynamically applied to the final mask border. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/mask-border-source) * */ interface maskΞborderΞsource extends _ { set(val: any): void; } /** * The mask-border-width CSS property specifies the width of an element's mask border. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/mask-border-width) * */ interface maskΞborderΞwidth extends _ { set(val: any, arg1: any, arg2: any, arg3: any): void; } /** * The mask-clip CSS property determines the area, which is affected by a mask. The painted content of an element must be restricted to this area. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/mask-clip) * */ interface maskΞclip extends _ { set(val: any, arg1: any, arg2: any, arg3: any): void; } /** * The mask-composite CSS property represents a compositing operation used on the current mask layer with the mask layers below it. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/mask-composite) * */ interface maskΞcomposite extends _ { set(val: any, arg1: any, arg2: any, arg3: any): void; } /** * The max-liens property forces a break after a set number of lines * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/max-lines) * */ interface maxΞlines extends _ { set(val: any): void; } /** * The overflow-clip-box CSS property specifies relative to which box the clipping happens when there is an overflow. It is short hand for the overflow-clip-box-inline and overflow-clip-box-block properties. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/overflow-clip-box) * */ interface overflowΞclipΞbox extends _ { set(val: any): void; } /** * The overflow-inline CSS media feature can be used to test how the output device handles content that overflows the initial containing block along the inline axis. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/overflow-inline) * */ interface overflowΞinline extends _ { set(val: any): void; } /** * The overscroll-behavior CSS property is shorthand for the overscroll-behavior-x and overscroll-behavior-y properties, which allow you to control the browser's scroll overflow behavior — what happens when the boundary of a scrolling area is reached. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/overscroll-behavior) * */ interface overscrollΞbehavior extends _ { set(val: any, arg1: any): void; } /** * The overscroll-behavior-x CSS property is allows you to control the browser's scroll overflow behavior — what happens when the boundary of a scrolling area is reached — in the x axis direction. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/overscroll-behavior-x) * */ interface overscrollΞbehaviorΞx extends _ { set(val: any): void; } /** * The overscroll-behavior-y CSS property is allows you to control the browser's scroll overflow behavior — what happens when the boundary of a scrolling area is reached — in the y axis direction. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/overscroll-behavior-y) * */ interface overscrollΞbehaviorΞy extends _ { set(val: any): void; } /** * This property controls how ruby annotation boxes should be rendered when there are more than one in a ruby container box: whether each pair should be kept separate, the annotations should be collapsed and rendered as a group, or the separation should be determined based on the space available. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/ruby-merge) * */ interface rubyΞmerge extends _ { set(val: any): void; } /** * The scrollbar-color CSS property sets the color of the scrollbar track and thumb. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scrollbar-color) * */ interface scrollbarΞcolor extends _ { set(val: any): void; } /** * The scrollbar-width property allows the author to set the maximum thickness of an element’s scrollbars when they are shown. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scrollbar-width) * */ interface scrollbarΞwidth extends _ { set(val: any): void; } /** * The scroll-margin property is a shorthand property which sets all of the scroll-margin longhands, assigning values much like the margin property does for the margin-* longhands. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-margin) * */ interface scrollΞmargin extends _ { set(val: any, arg1: any, arg2: any, arg3: any): void; } /** * The scroll-margin-block property is a shorthand property which sets the scroll-margin longhands in the block dimension. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-margin-block) * */ interface scrollΞmarginΞblock extends _ { set(val: any, arg1: any): void; } /** * The scroll-margin-block-start property defines the margin of the scroll snap area at the start of the block dimension that is used for snapping this box to the snapport. The scroll snap area is determined by taking the transformed border box, finding its rectangular bounding box (axis-aligned in the scroll container’s coordinate space), then adding the specified outsets. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-margin-block-start) * */ interface scrollΞmarginΞblockΞstart extends _ { set(val: any): void; } /** * The scroll-margin-block-end property defines the margin of the scroll snap area at the end of the block dimension that is used for snapping this box to the snapport. The scroll snap area is determined by taking the transformed border box, finding its rectangular bounding box (axis-aligned in the scroll container’s coordinate space), then adding the specified outsets. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-margin-block-end) * */ interface scrollΞmarginΞblockΞend extends _ { set(val: any): void; } /** * The scroll-margin-bottom property defines the bottom margin of the scroll snap area that is used for snapping this box to the snapport. The scroll snap area is determined by taking the transformed border box, finding its rectangular bounding box (axis-aligned in the scroll container’s coordinate space), then adding the specified outsets. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-margin-bottom) * */ interface scrollΞmarginΞbottom extends _ { set(val: any): void; } /** * The scroll-margin-inline property is a shorthand property which sets the scroll-margin longhands in the inline dimension. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-margin-inline) * */ interface scrollΞmarginΞinline extends _ { set(val: any, arg1: any): void; } /** * The scroll-margin-inline-start property defines the margin of the scroll snap area at the start of the inline dimension that is used for snapping this box to the snapport. The scroll snap area is determined by taking the transformed border box, finding its rectangular bounding box (axis-aligned in the scroll container’s coordinate space), then adding the specified outsets. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-margin-inline-start) * */ interface scrollΞmarginΞinlineΞstart extends _ { set(val: any): void; } /** * The scroll-margin-inline-end property defines the margin of the scroll snap area at the end of the inline dimension that is used for snapping this box to the snapport. The scroll snap area is determined by taking the transformed border box, finding its rectangular bounding box (axis-aligned in the scroll container’s coordinate space), then adding the specified outsets. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-margin-inline-end) * */ interface scrollΞmarginΞinlineΞend extends _ { set(val: any): void; } /** * The scroll-margin-left property defines the left margin of the scroll snap area that is used for snapping this box to the snapport. The scroll snap area is determined by taking the transformed border box, finding its rectangular bounding box (axis-aligned in the scroll container’s coordinate space), then adding the specified outsets. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-margin-left) * */ interface scrollΞmarginΞleft extends _ { set(val: any): void; } /** * The scroll-margin-right property defines the right margin of the scroll snap area that is used for snapping this box to the snapport. The scroll snap area is determined by taking the transformed border box, finding its rectangular bounding box (axis-aligned in the scroll container’s coordinate space), then adding the specified outsets. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-margin-right) * */ interface scrollΞmarginΞright extends _ { set(val: any): void; } /** * The scroll-margin-top property defines the top margin of the scroll snap area that is used for snapping this box to the snapport. The scroll snap area is determined by taking the transformed border box, finding its rectangular bounding box (axis-aligned in the scroll container’s coordinate space), then adding the specified outsets. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-margin-top) * */ interface scrollΞmarginΞtop extends _ { set(val: any): void; } /** * The scroll-snap-type-x CSS property defines how strictly snap points are enforced on the horizontal axis of the scroll container in case there is one. Specifying any precise animations or physics used to enforce those snap points is not covered by this property but instead left up to the user agent. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-snap-type-x) * */ interface scrollΞsnapΞtypeΞx extends _ { set(val: any): void; } /** * The scroll-snap-type-y CSS property defines how strictly snap points are enforced on the vertical axis of the scroll container in case there is one. Specifying any precise animations or physics used to enforce those snap points is not covered by this property but instead left up to the user agent. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-snap-type-y) * */ interface scrollΞsnapΞtypeΞy extends _ { set(val: any): void; } /** * The text-decoration-thickness CSS property sets the thickness, or width, of the decoration line that is used on text in an element, such as a line-through, underline, or overline. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/text-decoration-thickness) * * @alias tdt */ interface textΞdecorationΞthickness extends _ { set(val: any): void; } /** @proxy textΞdecorationΞthickness */ interface tdt extends textΞdecorationΞthickness { } /** * The text-emphasis CSS property is a shorthand property for setting text-emphasis-style and text-emphasis-color in one declaration. This property will apply the specified emphasis mark to each character of the element's text, except separator characters, like spaces, and control characters. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/text-emphasis) * * @alias te */ interface textΞemphasis extends _ { set(val: any): void; } /** @proxy textΞemphasis */ interface te extends textΞemphasis { } /** * The text-emphasis-color CSS property defines the color used to draw emphasis marks on text being rendered in the HTML document. This value can also be set and reset using the text-emphasis shorthand. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/text-emphasis-color) * * @alias tec */ interface textΞemphasisΞcolor extends _ { set(val: any): void; } /** @proxy textΞemphasisΞcolor */ interface tec extends textΞemphasisΞcolor { } /** * The text-emphasis-position CSS property describes where emphasis marks are drawn at. The effect of emphasis marks on the line height is the same as for ruby text: if there isn't enough place, the line height is increased. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/text-emphasis-position) * * @alias tep */ interface textΞemphasisΞposition extends _ { set(val: any): void; } /** @proxy textΞemphasisΞposition */ interface tep extends textΞemphasisΞposition { } /** * The text-emphasis-style CSS property defines the type of emphasis used. It can also be set, and reset, using the text-emphasis shorthand. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/text-emphasis-style) * * @alias tes */ interface textΞemphasisΞstyle extends _ { set(val: any): void; } /** @proxy textΞemphasisΞstyle */ interface tes extends textΞemphasisΞstyle { } /** * The text-underline-offset CSS property sets the offset distance of an underline text decoration line (applied using text-decoration) from its original position. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/text-underline-offset) * */ interface textΞunderlineΞoffset extends _ { set(val: any): void; } /** * The speak-as descriptor specifies how a counter symbol constructed with a given @counter-style will be represented in the spoken form. For example, an author can specify a counter symbol to be either spoken as its numerical value or just represented with an audio cue. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/speak-as) * */ interface speakΞas extends _ { set(val: any): void; } /** * The bleed CSS at-rule descriptor, used with the @page at-rule, specifies the extent of the page bleed area outside the page box. This property only has effect if crop marks are enabled using the marks property. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/bleed) * */ interface bleed extends _ { set(val: any): void; } /** * The marks CSS at-rule descriptor, used with the @page at-rule, adds crop and/or cross marks to the presentation of the document. Crop marks indicate where the page should be cut. Cross marks are used to align sheets. * * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/marks) * */ interface marks extends _ { set(val: any): void; } interface Ψcolor { /** The current color */ current: 'current'; /** Clear */ transparent: 'transparent'; /** Clear */ clear: 'clear'; /** @color hsla(0,0%,0%,1) */ black: 'hsla(0,0%,0%,1)'; /** @color hsla(0,0%,100%,1) */ white: 'hsla(0,0%,100%,1)'; /** @color hsla(355,100%,97%,1) */ rose0: 'hsla(355,100%,97%,1)'; /** @color hsla(355,100%,94%,1) */ rose1: 'hsla(355,100%,94%,1)'; /** @color hsla(352,96%,90%,1) */ rose2: 'hsla(352,96%,90%,1)'; /** @color hsla(352,95%,81%,1) */ rose3: 'hsla(352,95%,81%,1)'; /** @color hsla(351,94%,71%,1) */ rose4: 'hsla(351,94%,71%,1)'; /** @color hsla(349,89%,60%,1) */ rose5: 'hsla(349,89%,60%,1)'; /** @color hsla(346,77%,49%,1) */ rose6: 'hsla(346,77%,49%,1)'; /** @color hsla(345,82%,40%,1) */ rose7: 'hsla(345,82%,40%,1)'; /** @color hsla(343,79%,34%,1) */ rose8: 'hsla(343,79%,34%,1)'; /** @color hsla(341,75%,30%,1) */ rose9: 'hsla(341,75%,30%,1)'; /** @color hsla(327,73%,97%,1) */ pink0: 'hsla(327,73%,97%,1)'; /** @color hsla(325,77%,94%,1) */ pink1: 'hsla(325,77%,94%,1)'; /** @color hsla(325,84%,89%,1) */ pink2: 'hsla(325,84%,89%,1)'; /** @color hsla(327,87%,81%,1) */ pink3: 'hsla(327,87%,81%,1)'; /** @color hsla(328,85%,70%,1) */ pink4: 'hsla(328,85%,70%,1)'; /** @color hsla(330,81%,60%,1) */ pink5: 'hsla(330,81%,60%,1)'; /** @color hsla(333,71%,50%,1) */ pink6: 'hsla(333,71%,50%,1)'; /** @color hsla(335,77%,41%,1) */ pink7: 'hsla(335,77%,41%,1)'; /** @color hsla(335,74%,35%,1) */ pink8: 'hsla(335,74%,35%,1)'; /** @color hsla(335,69%,30%,1) */ pink9: 'hsla(335,69%,30%,1)'; /** @color hsla(289,100%,97%,1) */ fuchsia0: 'hsla(289,100%,97%,1)'; /** @color hsla(286,100%,95%,1) */ fuchsia1: 'hsla(286,100%,95%,1)'; /** @color hsla(288,95%,90%,1) */ fuchsia2: 'hsla(288,95%,90%,1)'; /** @color hsla(291,93%,82%,1) */ fuchsia3: 'hsla(291,93%,82%,1)'; /** @color hsla(292,91%,72%,1) */ fuchsia4: 'hsla(292,91%,72%,1)'; /** @color hsla(292,84%,60%,1) */ fuchsia5: 'hsla(292,84%,60%,1)'; /** @color hsla(293,69%,48%,1) */ fuchsia6: 'hsla(293,69%,48%,1)'; /** @color hsla(294,72%,39%,1) */ fuchsia7: 'hsla(294,72%,39%,1)'; /** @color hsla(295,70%,32%,1) */ fuchsia8: 'hsla(295,70%,32%,1)'; /** @color hsla(296,63%,28%,1) */ fuchsia9: 'hsla(296,63%,28%,1)'; /** @color hsla(269,100%,98%,1) */ purple0: 'hsla(269,100%,98%,1)'; /** @color hsla(268,100%,95%,1) */ purple1: 'hsla(268,100%,95%,1)'; /** @color hsla(268,100%,91%,1) */ purple2: 'hsla(268,100%,91%,1)'; /** @color hsla(269,97%,85%,1) */ purple3: 'hsla(269,97%,85%,1)'; /** @color hsla(270,95%,75%,1) */ purple4: 'hsla(270,95%,75%,1)'; /** @color hsla(270,91%,65%,1) */ purple5: 'hsla(270,91%,65%,1)'; /** @color hsla(271,81%,55%,1) */ purple6: 'hsla(271,81%,55%,1)'; /** @color hsla(272,71%,47%,1) */ purple7: 'hsla(272,71%,47%,1)'; /** @color hsla(272,67%,39%,1) */ purple8: 'hsla(272,67%,39%,1)'; /** @color hsla(273,65%,31%,1) */ purple9: 'hsla(273,65%,31%,1)'; /** @color hsla(250,100%,97%,1) */ violet0: 'hsla(250,100%,97%,1)'; /** @color hsla(251,91%,95%,1) */ violet1: 'hsla(251,91%,95%,1)'; /** @color hsla(250,95%,91%,1) */ violet2: 'hsla(250,95%,91%,1)'; /** @color hsla(252,94%,85%,1) */ violet3: 'hsla(252,94%,85%,1)'; /** @color hsla(255,91%,76%,1) */ violet4: 'hsla(255,91%,76%,1)'; /** @color hsla(258,89%,66%,1) */ violet5: 'hsla(258,89%,66%,1)'; /** @color hsla(262,83%,57%,1) */ violet6: 'hsla(262,83%,57%,1)'; /** @color hsla(263,69%,50%,1) */ violet7: 'hsla(263,69%,50%,1)'; /** @color hsla(263,69%,42%,1) */ violet8: 'hsla(263,69%,42%,1)'; /** @color hsla(263,67%,34%,1) */ violet9: 'hsla(263,67%,34%,1)'; /** @color hsla(225,100%,96%,1) */ indigo0: 'hsla(225,100%,96%,1)'; /** @color hsla(226,100%,93%,1) */ indigo1: 'hsla(226,100%,93%,1)'; /** @color hsla(228,96%,88%,1) */ indigo2: 'hsla(228,96%,88%,1)'; /** @color hsla(229,93%,81%,1) */ indigo3: 'hsla(229,93%,81%,1)'; /** @color hsla(234,89%,73%,1) */ indigo4: 'hsla(234,89%,73%,1)'; /** @color hsla(238,83%,66%,1) */ indigo5: 'hsla(238,83%,66%,1)'; /** @color hsla(243,75%,58%,1) */ indigo6: 'hsla(243,75%,58%,1)'; /** @color hsla(244,57%,50%,1) */ indigo7: 'hsla(244,57%,50%,1)'; /** @color hsla(243,54%,41%,1) */ indigo8: 'hsla(243,54%,41%,1)'; /** @color hsla(242,47%,34%,1) */ indigo9: 'hsla(242,47%,34%,1)'; /** @color hsla(213,100%,96%,1) */ blue0: 'hsla(213,100%,96%,1)'; /** @color hsla(213,100%,96%,1) */ hue0: 'hsla(213,100%,96%,1)'; /** @color hsla(214,94%,92%,1) */ blue1: 'hsla(214,94%,92%,1)'; /** @color hsla(214,94%,92%,1) */ hue1: 'hsla(214,94%,92%,1)'; /** @color hsla(213,96%,87%,1) */ blue2: 'hsla(213,96%,87%,1)'; /** @color hsla(213,96%,87%,1) */ hue2: 'hsla(213,96%,87%,1)'; /** @color hsla(211,96%,78%,1) */ blue3: 'hsla(211,96%,78%,1)'; /** @color hsla(211,96%,78%,1) */ hue3: 'hsla(211,96%,78%,1)'; /** @color hsla(213,93%,67%,1) */ blue4: 'hsla(213,93%,67%,1)'; /** @color hsla(213,93%,67%,1) */ hue4: 'hsla(213,93%,67%,1)'; /** @color hsla(217,91%,59%,1) */ blue5: 'hsla(217,91%,59%,1)'; /** @color hsla(217,91%,59%,1) */ hue5: 'hsla(217,91%,59%,1)'; /** @color hsla(221,83%,53%,1) */ blue6: 'hsla(221,83%,53%,1)'; /** @color hsla(221,83%,53%,1) */ hue6: 'hsla(221,83%,53%,1)'; /** @color hsla(224,76%,48%,1) */ blue7: 'hsla(224,76%,48%,1)'; /** @color hsla(224,76%,48%,1) */ hue7: 'hsla(224,76%,48%,1)'; /** @color hsla(225,70%,40%,1) */ blue8: 'hsla(225,70%,40%,1)'; /** @color hsla(225,70%,40%,1) */ hue8: 'hsla(225,70%,40%,1)'; /** @color hsla(224,64%,32%,1) */ blue9: 'hsla(224,64%,32%,1)'; /** @color hsla(224,64%,32%,1) */ hue9: 'hsla(224,64%,32%,1)'; /** @color hsla(204,100%,97%,1) */ sky0: 'hsla(204,100%,97%,1)'; /** @color hsla(204,93%,93%,1) */ sky1: 'hsla(204,93%,93%,1)'; /** @color hsla(200,94%,86%,1) */ sky2: 'hsla(200,94%,86%,1)'; /** @color hsla(199,95%,73%,1) */ sky3: 'hsla(199,95%,73%,1)'; /** @color hsla(198,93%,59%,1) */ sky4: 'hsla(198,93%,59%,1)'; /** @color hsla(198,88%,48%,1) */ sky5: 'hsla(198,88%,48%,1)'; /** @color hsla(200,98%,39%,1) */ sky6: 'hsla(200,98%,39%,1)'; /** @color hsla(201,96%,32%,1) */ sky7: 'hsla(201,96%,32%,1)'; /** @color hsla(200,89%,27%,1) */ sky8: 'hsla(200,89%,27%,1)'; /** @color hsla(202,80%,23%,1) */ sky9: 'hsla(202,80%,23%,1)'; /** @color hsla(183,100%,96%,1) */ cyan0: 'hsla(183,100%,96%,1)'; /** @color hsla(185,95%,90%,1) */ cyan1: 'hsla(185,95%,90%,1)'; /** @color hsla(186,93%,81%,1) */ cyan2: 'hsla(186,93%,81%,1)'; /** @color hsla(186,92%,69%,1) */ cyan3: 'hsla(186,92%,69%,1)'; /** @color hsla(187,85%,53%,1) */ cyan4: 'hsla(187,85%,53%,1)'; /** @color hsla(188,94%,42%,1) */ cyan5: 'hsla(188,94%,42%,1)'; /** @color hsla(191,91%,36%,1) */ cyan6: 'hsla(191,91%,36%,1)'; /** @color hsla(192,82%,30%,1) */ cyan7: 'hsla(192,82%,30%,1)'; /** @color hsla(194,69%,27%,1) */ cyan8: 'hsla(194,69%,27%,1)'; /** @color hsla(196,63%,23%,1) */ cyan9: 'hsla(196,63%,23%,1)'; /** @color hsla(166,76%,96%,1) */ teal0: 'hsla(166,76%,96%,1)'; /** @color hsla(167,85%,89%,1) */ teal1: 'hsla(167,85%,89%,1)'; /** @color hsla(168,83%,78%,1) */ teal2: 'hsla(168,83%,78%,1)'; /** @color hsla(170,76%,64%,1) */ teal3: 'hsla(170,76%,64%,1)'; /** @color hsla(172,66%,50%,1) */ teal4: 'hsla(172,66%,50%,1)'; /** @color hsla(173,80%,40%,1) */ teal5: 'hsla(173,80%,40%,1)'; /** @color hsla(174,83%,31%,1) */ teal6: 'hsla(174,83%,31%,1)'; /** @color hsla(175,77%,26%,1) */ teal7: 'hsla(175,77%,26%,1)'; /** @color hsla(176,69%,21%,1) */ teal8: 'hsla(176,69%,21%,1)'; /** @color hsla(175,60%,19%,1) */ teal9: 'hsla(175,60%,19%,1)'; /** @color hsla(151,80%,95%,1) */ emerald0: 'hsla(151,80%,95%,1)'; /** @color hsla(149,80%,89%,1) */ emerald1: 'hsla(149,80%,89%,1)'; /** @color hsla(152,75%,80%,1) */ emerald2: 'hsla(152,75%,80%,1)'; /** @color hsla(156,71%,66%,1) */ emerald3: 'hsla(156,71%,66%,1)'; /** @color hsla(158,64%,51%,1) */ emerald4: 'hsla(158,64%,51%,1)'; /** @color hsla(160,84%,39%,1) */ emerald5: 'hsla(160,84%,39%,1)'; /** @color hsla(161,93%,30%,1) */ emerald6: 'hsla(161,93%,30%,1)'; /** @color hsla(162,93%,24%,1) */ emerald7: 'hsla(162,93%,24%,1)'; /** @color hsla(163,88%,19%,1) */ emerald8: 'hsla(163,88%,19%,1)'; /** @color hsla(164,85%,16%,1) */ emerald9: 'hsla(164,85%,16%,1)'; /** @color hsla(138,76%,96%,1) */ green0: 'hsla(138,76%,96%,1)'; /** @color hsla(140,84%,92%,1) */ green1: 'hsla(140,84%,92%,1)'; /** @color hsla(141,78%,85%,1) */ green2: 'hsla(141,78%,85%,1)'; /** @color hsla(141,76%,73%,1) */ green3: 'hsla(141,76%,73%,1)'; /** @color hsla(141,69%,58%,1) */ green4: 'hsla(141,69%,58%,1)'; /** @color hsla(142,70%,45%,1) */ green5: 'hsla(142,70%,45%,1)'; /** @color hsla(142,76%,36%,1) */ green6: 'hsla(142,76%,36%,1)'; /** @color hsla(142,71%,29%,1) */ green7: 'hsla(142,71%,29%,1)'; /** @color hsla(142,64%,24%,1) */ green8: 'hsla(142,64%,24%,1)'; /** @color hsla(143,61%,20%,1) */ green9: 'hsla(143,61%,20%,1)'; /** @color hsla(78,92%,95%,1) */ lime0: 'hsla(78,92%,95%,1)'; /** @color hsla(79,89%,89%,1) */ lime1: 'hsla(79,89%,89%,1)'; /** @color hsla(80,88%,79%,1) */ lime2: 'hsla(80,88%,79%,1)'; /** @color hsla(81,84%,67%,1) */ lime3: 'hsla(81,84%,67%,1)'; /** @color hsla(82,77%,55%,1) */ lime4: 'hsla(82,77%,55%,1)'; /** @color hsla(83,80%,44%,1) */ lime5: 'hsla(83,80%,44%,1)'; /** @color hsla(84,85%,34%,1) */ lime6: 'hsla(84,85%,34%,1)'; /** @color hsla(85,78%,27%,1) */ lime7: 'hsla(85,78%,27%,1)'; /** @color hsla(86,68%,22%,1) */ lime8: 'hsla(86,68%,22%,1)'; /** @color hsla(87,61%,20%,1) */ lime9: 'hsla(87,61%,20%,1)'; /** @color hsla(54,91%,95%,1) */ yellow0: 'hsla(54,91%,95%,1)'; /** @color hsla(54,96%,88%,1) */ yellow1: 'hsla(54,96%,88%,1)'; /** @color hsla(52,98%,76%,1) */ yellow2: 'hsla(52,98%,76%,1)'; /** @color hsla(50,97%,63%,1) */ yellow3: 'hsla(50,97%,63%,1)'; /** @color hsla(47,95%,53%,1) */ yellow4: 'hsla(47,95%,53%,1)'; /** @color hsla(45,93%,47%,1) */ yellow5: 'hsla(45,93%,47%,1)'; /** @color hsla(40,96%,40%,1) */ yellow6: 'hsla(40,96%,40%,1)'; /** @color hsla(35,91%,32%,1) */ yellow7: 'hsla(35,91%,32%,1)'; /** @color hsla(31,80%,28%,1) */ yellow8: 'hsla(31,80%,28%,1)'; /** @color hsla(28,72%,25%,1) */ yellow9: 'hsla(28,72%,25%,1)'; /** @color hsla(47,100%,96%,1) */ amber0: 'hsla(47,100%,96%,1)'; /** @color hsla(47,96%,88%,1) */ amber1: 'hsla(47,96%,88%,1)'; /** @color hsla(48,96%,76%,1) */ amber2: 'hsla(48,96%,76%,1)'; /** @color hsla(45,96%,64%,1) */ amber3: 'hsla(45,96%,64%,1)'; /** @color hsla(43,96%,56%,1) */ amber4: 'hsla(43,96%,56%,1)'; /** @color hsla(37,92%,50%,1) */ amber5: 'hsla(37,92%,50%,1)'; /** @color hsla(32,94%,43%,1) */ amber6: 'hsla(32,94%,43%,1)'; /** @color hsla(25,90%,37%,1) */ amber7: 'hsla(25,90%,37%,1)'; /** @color hsla(22,82%,31%,1) */ amber8: 'hsla(22,82%,31%,1)'; /** @color hsla(21,77%,26%,1) */ amber9: 'hsla(21,77%,26%,1)'; /** @color hsla(33,100%,96%,1) */ orange0: 'hsla(33,100%,96%,1)'; /** @color hsla(34,100%,91%,1) */ orange1: 'hsla(34,100%,91%,1)'; /** @color hsla(32,97%,83%,1) */ orange2: 'hsla(32,97%,83%,1)'; /** @color hsla(30,97%,72%,1) */ orange3: 'hsla(30,97%,72%,1)'; /** @color hsla(27,95%,60%,1) */ orange4: 'hsla(27,95%,60%,1)'; /** @color hsla(24,94%,53%,1) */ orange5: 'hsla(24,94%,53%,1)'; /** @color hsla(20,90%,48%,1) */ orange6: 'hsla(20,90%,48%,1)'; /** @color hsla(17,88%,40%,1) */ orange7: 'hsla(17,88%,40%,1)'; /** @color hsla(15,79%,33%,1) */ orange8: 'hsla(15,79%,33%,1)'; /** @color hsla(15,74%,27%,1) */ orange9: 'hsla(15,74%,27%,1)'; /** @color hsla(0,85%,97%,1) */ red0: 'hsla(0,85%,97%,1)'; /** @color hsla(0,93%,94%,1) */ red1: 'hsla(0,93%,94%,1)'; /** @color hsla(0,96%,89%,1) */ red2: 'hsla(0,96%,89%,1)'; /** @color hsla(0,93%,81%,1) */ red3: 'hsla(0,93%,81%,1)'; /** @color hsla(0,90%,70%,1) */ red4: 'hsla(0,90%,70%,1)'; /** @color hsla(0,84%,60%,1) */ red5: 'hsla(0,84%,60%,1)'; /** @color hsla(0,72%,50%,1) */ red6: 'hsla(0,72%,50%,1)'; /** @color hsla(0,73%,41%,1) */ red7: 'hsla(0,73%,41%,1)'; /** @color hsla(0,70%,35%,1) */ red8: 'hsla(0,70%,35%,1)'; /** @color hsla(0,62%,30%,1) */ red9: 'hsla(0,62%,30%,1)'; /** @color hsla(60,9%,97%,1) */ warmer0: 'hsla(60,9%,97%,1)'; /** @color hsla(60,4%,95%,1) */ warmer1: 'hsla(60,4%,95%,1)'; /** @color hsla(20,5%,90%,1) */ warmer2: 'hsla(20,5%,90%,1)'; /** @color hsla(23,5%,82%,1) */ warmer3: 'hsla(23,5%,82%,1)'; /** @color hsla(23,5%,63%,1) */ warmer4: 'hsla(23,5%,63%,1)'; /** @color hsla(24,5%,44%,1) */ warmer5: 'hsla(24,5%,44%,1)'; /** @color hsla(33,5%,32%,1) */ warmer6: 'hsla(33,5%,32%,1)'; /** @color hsla(30,6%,25%,1) */ warmer7: 'hsla(30,6%,25%,1)'; /** @color hsla(12,6%,15%,1) */ warmer8: 'hsla(12,6%,15%,1)'; /** @color hsla(24,9%,10%,1) */ warmer9: 'hsla(24,9%,10%,1)'; /** @color hsla(0,0%,98%,1) */ warm0: 'hsla(0,0%,98%,1)'; /** @color hsla(0,0%,96%,1) */ warm1: 'hsla(0,0%,96%,1)'; /** @color hsla(0,0%,89%,1) */ warm2: 'hsla(0,0%,89%,1)'; /** @color hsla(0,0%,83%,1) */ warm3: 'hsla(0,0%,83%,1)'; /** @color hsla(0,0%,63%,1) */ warm4: 'hsla(0,0%,63%,1)'; /** @color hsla(0,0%,45%,1) */ warm5: 'hsla(0,0%,45%,1)'; /** @color hsla(0,0%,32%,1) */ warm6: 'hsla(0,0%,32%,1)'; /** @color hsla(0,0%,25%,1) */ warm7: 'hsla(0,0%,25%,1)'; /** @color hsla(0,0%,14%,1) */ warm8: 'hsla(0,0%,14%,1)'; /** @color hsla(0,0%,9%,1) */ warm9: 'hsla(0,0%,9%,1)'; /** @color hsla(0,0%,98%,1) */ gray0: 'hsla(0,0%,98%,1)'; /** @color hsla(240,4%,95%,1) */ gray1: 'hsla(240,4%,95%,1)'; /** @color hsla(240,5%,90%,1) */ gray2: 'hsla(240,5%,90%,1)'; /** @color hsla(240,4%,83%,1) */ gray3: 'hsla(240,4%,83%,1)'; /** @color hsla(240,5%,64%,1) */ gray4: 'hsla(240,5%,64%,1)'; /** @color hsla(240,3%,46%,1) */ gray5: 'hsla(240,3%,46%,1)'; /** @color hsla(240,5%,33%,1) */ gray6: 'hsla(240,5%,33%,1)'; /** @color hsla(240,5%,26%,1) */ gray7: 'hsla(240,5%,26%,1)'; /** @color hsla(240,3%,15%,1) */ gray8: 'hsla(240,3%,15%,1)'; /** @color hsla(240,5%,10%,1) */ gray9: 'hsla(240,5%,10%,1)'; /** @color hsla(210,19%,98%,1) */ cool0: 'hsla(210,19%,98%,1)'; /** @color hsla(219,14%,95%,1) */ cool1: 'hsla(219,14%,95%,1)'; /** @color hsla(220,13%,90%,1) */ cool2: 'hsla(220,13%,90%,1)'; /** @color hsla(215,12%,83%,1) */ cool3: 'hsla(215,12%,83%,1)'; /** @color hsla(217,10%,64%,1) */ cool4: 'hsla(217,10%,64%,1)'; /** @color hsla(220,8%,46%,1) */ cool5: 'hsla(220,8%,46%,1)'; /** @color hsla(215,13%,34%,1) */ cool6: 'hsla(215,13%,34%,1)'; /** @color hsla(216,19%,26%,1) */ cool7: 'hsla(216,19%,26%,1)'; /** @color hsla(214,27%,16%,1) */ cool8: 'hsla(214,27%,16%,1)'; /** @color hsla(220,39%,10%,1) */ cool9: 'hsla(220,39%,10%,1)'; /** @color hsla(210,40%,98%,1) */ cooler0: 'hsla(210,40%,98%,1)'; /** @color hsla(209,40%,96%,1) */ cooler1: 'hsla(209,40%,96%,1)'; /** @color hsla(214,31%,91%,1) */ cooler2: 'hsla(214,31%,91%,1)'; /** @color hsla(212,26%,83%,1) */ cooler3: 'hsla(212,26%,83%,1)'; /** @color hsla(215,20%,65%,1) */ cooler4: 'hsla(215,20%,65%,1)'; /** @color hsla(215,16%,46%,1) */ cooler5: 'hsla(215,16%,46%,1)'; /** @color hsla(215,19%,34%,1) */ cooler6: 'hsla(215,19%,34%,1)'; /** @color hsla(215,24%,26%,1) */ cooler7: 'hsla(215,24%,26%,1)'; /** @color hsla(217,32%,17%,1) */ cooler8: 'hsla(217,32%,17%,1)'; /** @color hsla(222,47%,11%,1) */ cooler9: 'hsla(222,47%,11%,1)'; } interface Ψhue { /** @color hsla(351,94%,71%,1) */ rose: 'hsla(351,94%,71%,1)'; /** @color hsla(328,85%,70%,1) */ pink: 'hsla(328,85%,70%,1)'; /** @color hsla(292,91%,72%,1) */ fuchsia: 'hsla(292,91%,72%,1)'; /** @color hsla(270,95%,75%,1) */ purple: 'hsla(270,95%,75%,1)'; /** @color hsla(255,91%,76%,1) */ violet: 'hsla(255,91%,76%,1)'; /** @color hsla(234,89%,73%,1) */ indigo: 'hsla(234,89%,73%,1)'; /** @color hsla(213,93%,67%,1) */ blue: 'hsla(213,93%,67%,1)'; /** @color hsla(198,93%,59%,1) */ sky: 'hsla(198,93%,59%,1)'; /** @color hsla(187,85%,53%,1) */ cyan: 'hsla(187,85%,53%,1)'; /** @color hsla(172,66%,50%,1) */ teal: 'hsla(172,66%,50%,1)'; /** @color hsla(158,64%,51%,1) */ emerald: 'hsla(158,64%,51%,1)'; /** @color hsla(141,69%,58%,1) */ green: 'hsla(141,69%,58%,1)'; /** @color hsla(82,77%,55%,1) */ lime: 'hsla(82,77%,55%,1)'; /** @color hsla(47,95%,53%,1) */ yellow: 'hsla(47,95%,53%,1)'; /** @color hsla(43,96%,56%,1) */ amber: 'hsla(43,96%,56%,1)'; /** @color hsla(27,95%,60%,1) */ orange: 'hsla(27,95%,60%,1)'; /** @color hsla(0,90%,70%,1) */ red: 'hsla(0,90%,70%,1)'; /** @color hsla(23,5%,63%,1) */ warmer: 'hsla(23,5%,63%,1)'; /** @color hsla(0,0%,63%,1) */ warm: 'hsla(0,0%,63%,1)'; /** @color hsla(240,5%,64%,1) */ gray: 'hsla(240,5%,64%,1)'; /** @color hsla(217,10%,64%,1) */ cool: 'hsla(217,10%,64%,1)'; /** @color hsla(215,20%,65%,1) */ cooler: 'hsla(215,20%,65%,1)'; } interface Ψfs { /** 10px */ 'xxs': '10px'; /** 12px */ 'xs': '12px'; /** 13px */ 'sm-': '13px'; /** 14px */ 'sm': '14px'; /** 15px */ 'md-': '15px'; /** 16px */ 'md': '16px'; /** 18px */ 'lg': '18px'; /** 20px */ 'xl': '20px'; /** 24px */ '2xl': '24px'; /** 30px */ '3xl': '30px'; /** 36px */ '4xl': '36px'; /** 48px */ '5xl': '48px'; /** 64px */ '6xl': '64px'; } interface Ψshadow { /** 0 0 0 1px rgba(0, 0, 0, 0.05) */ 'xxs': '0 0 0 1px rgba(0, 0, 0, 0.05)'; /** 0 1px 2px 0 rgba(0, 0, 0, 0.05) */ 'xs': '0 1px 2px 0 rgba(0, 0, 0, 0.05)'; /** 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06) */ 'sm': '0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)'; /** 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06) */ 'md': '0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)'; /** 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05) */ 'lg': '0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)'; /** 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04) */ 'xl': '0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)'; /** 0 25px 50px -6px rgba(0, 0, 0, 0.25) */ 'xxl': '0 25px 50px -6px rgba(0, 0, 0, 0.25)'; /** inset 0 2px 4px 0 rgba(0, 0, 0, 0.06) */ 'inner': 'inset 0 2px 4px 0 rgba(0, 0, 0, 0.06)'; /** 0 0 0 3px rgba(66, 153, 225, 0.5) */ 'outline': '0 0 0 3px rgba(66, 153, 225, 0.5)'; /** none */ 'none': 'none'; } interface Ψradius { /** 9999px */ 'full': '9999px'; /** 1px */ 'xxs': '1px'; /** 2px */ 'xs': '2px'; /** 3px */ 'sm': '3px'; /** 4px */ 'md': '4px'; /** 6px */ 'lg': '6px'; /** 8px */ 'xl': '8px'; } interface ΨeasingΞfunction { /** @easing cubic-bezier(0.47, 0, 0.745, 0.715) */ sineΞin: 'cubic-bezier(0.47, 0, 0.745, 0.715)'; /** @easing cubic-bezier(0.39, 0.575, 0.565, 1) */ sineΞout: 'cubic-bezier(0.39, 0.575, 0.565, 1)'; /** @easing cubic-bezier(0.445, 0.05, 0.55, 0.95) */ sineΞinΞout: 'cubic-bezier(0.445, 0.05, 0.55, 0.95)'; /** @easing cubic-bezier(0.55, 0.085, 0.68, 0.53) */ quadΞin: 'cubic-bezier(0.55, 0.085, 0.68, 0.53)'; /** @easing cubic-bezier(0.25, 0.46, 0.45, 0.94) */ quadΞout: 'cubic-bezier(0.25, 0.46, 0.45, 0.94)'; /** @easing cubic-bezier(0.455, 0.03, 0.515, 0.955) */ quadΞinΞout: 'cubic-bezier(0.455, 0.03, 0.515, 0.955)'; /** @easing cubic-bezier(0.55, 0.055, 0.675, 0.19) */ cubicΞin: 'cubic-bezier(0.55, 0.055, 0.675, 0.19)'; /** @easing cubic-bezier(0.215, 0.61, 0.355, 1) */ cubicΞout: 'cubic-bezier(0.215, 0.61, 0.355, 1)'; /** @easing cubic-bezier(0.645, 0.045, 0.355, 1) */ cubicΞinΞout: 'cubic-bezier(0.645, 0.045, 0.355, 1)'; /** @easing cubic-bezier(0.895, 0.03, 0.685, 0.22) */ quartΞin: 'cubic-bezier(0.895, 0.03, 0.685, 0.22)'; /** @easing cubic-bezier(0.165, 0.84, 0.44, 1) */ quartΞout: 'cubic-bezier(0.165, 0.84, 0.44, 1)'; /** @easing cubic-bezier(0.77, 0, 0.175, 1) */ quartΞinΞout: 'cubic-bezier(0.77, 0, 0.175, 1)'; /** @easing cubic-bezier(0.755, 0.05, 0.855, 0.06) */ quintΞin: 'cubic-bezier(0.755, 0.05, 0.855, 0.06)'; /** @easing cubic-bezier(0.23, 1, 0.32, 1) */ quintΞout: 'cubic-bezier(0.23, 1, 0.32, 1)'; /** @easing cubic-bezier(0.86, 0, 0.07, 1) */ quintΞinΞout: 'cubic-bezier(0.86, 0, 0.07, 1)'; /** @easing cubic-bezier(0.95, 0.05, 0.795, 0.035) */ expoΞin: 'cubic-bezier(0.95, 0.05, 0.795, 0.035)'; /** @easing cubic-bezier(0.19, 1, 0.22, 1) */ expoΞout: 'cubic-bezier(0.19, 1, 0.22, 1)'; /** @easing cubic-bezier(1, 0, 0, 1) */ expoΞinΞout: 'cubic-bezier(1, 0, 0, 1)'; /** @easing cubic-bezier(0.6, 0.04, 0.98, 0.335) */ circΞin: 'cubic-bezier(0.6, 0.04, 0.98, 0.335)'; /** @easing cubic-bezier(0.075, 0.82, 0.165, 1) */ circΞout: 'cubic-bezier(0.075, 0.82, 0.165, 1)'; /** @easing cubic-bezier(0.785, 0.135, 0.15, 0.86) */ circΞinΞout: 'cubic-bezier(0.785, 0.135, 0.15, 0.86)'; /** @easing cubic-bezier(0.6, -0.28, 0.735, 0.045) */ backΞin: 'cubic-bezier(0.6, -0.28, 0.735, 0.045)'; /** @easing cubic-bezier(0.175, 0.885, 0.32, 1.275) */ backΞout: 'cubic-bezier(0.175, 0.885, 0.32, 1.275)'; /** @easing cubic-bezier(0.68, -0.55, 0.265, 1.55) */ backΞinΞout: 'cubic-bezier(0.68, -0.55, 0.265, 1.55)'; } }
the_stack
import { DataTypeFieldConfig, Maybe, SortOrder, ReadonlyDataTypeFields, } from '@terascope/types'; import { isPrimitiveValue, getHashCodeFrom, } from '@terascope/utils'; import { ReadableData, WritableData } from '../core'; import { DataBuckets, SerializeOptions, VectorType } from './interfaces'; /** * An immutable typed Array class with a constrained API. */ export abstract class Vector<T = unknown> { /** * Make an instance of a Vector from a config */ static make<R>( data: DataBuckets<R>, options: VectorOptions ): Vector<R> { throw new Error(`This is overridden in the index file, ${options} ${data}`); } /** * Sort the values in a Vector and return * an array with the updated indices. */ static getSortedIndices( sortBy: { vector: Vector<any>; direction: SortOrder }[] ): number[] { const notSortable = sortBy.find(({ vector }) => !vector.sortable); if (notSortable) { throw new Error(`Sorting is not supported for ${notSortable.vector?.constructor.name}`); } const len = sortBy.reduce((size, { vector }) => Math.max(size, vector.size), 0); const indices: number[] = Array(len); const original: [number, any[]][] = Array(len); for (let i = 0; i < len; i++) { original[i] = [i, sortBy.map(({ vector }) => vector.get(i))]; } original .sort(([, a], [, b]) => ( sortBy.reduce((acc, { vector, direction: d }, i) => { const res = vector.compare(a[i], b[i]); return acc + (d === 'asc' ? res : -res); }, 0) )) .forEach(([i], newPosition) => { indices[i] = newPosition; }); return indices; } /** * The name of field, if specified this will just be used for metadata */ readonly name?: string; /** * The type of Vector, this should only be set the specific Vector type classes. */ readonly type: VectorType; /** * The field type configuration */ readonly config: Readonly<DataTypeFieldConfig>; /** * When Vector is an object type, this will be the data type fields * for the object */ readonly childConfig?: ReadonlyDataTypeFields; /** * A data type agnostic in-memory representation of the data * for a Vector and potential indices/unique values. Currently * there one ore more data buckets can be used. * * @internal */ readonly data: readonly ReadableData<T>[]; /** * If set to false, the Vector is not sortable */ sortable = true; /** * Returns the number items in the Vector */ readonly size: number; constructor( /** * This will be set automatically by specific Vector classes */ type: VectorType, data: DataBuckets<T>, options: VectorOptions ) { this.type = type; this.data = Object.isFrozen(data) ? data : Object.freeze(data.filter(isNotEmptyDataBucket)); this.name = options.name; this.config = options.config; this.childConfig = options.childConfig; this.size = this.data.reduce((acc, d) => acc + d.size, 0); } /** * A function for converting an in-memory representation of * a value to an JSON spec compatible format. */ abstract toJSONCompatibleValue?(value: T, options?: SerializeOptions): any; /** * A function for converting an in-memory representation of * a value to an JSON spec compatible format. */ abstract getComparableValue?(value: T): any; * [Symbol.iterator](): IterableIterator<Maybe<T>> { for (const data of this.data) { yield* data; } } /** * Check to see there are any nil values stored in the Vector */ hasNilValues(): boolean { return this.data.some((data) => data.hasNilValues()); } /** * Get the number of non-nil values in the Vector */ countValues(): number { return this.data.reduce((acc, data) => acc + data.countValues(), 0); } /** * Returns true if there are no non-nil values */ isEmpty(): boolean { if (this.size === 0) return true; return this.data.every((data) => data.isEmpty()); } /** * Iterate over the values and skip the nil ones, * returns tuples a with index and value */ * values(): IterableIterator<[index: number, value: T]> { let offset = 0; for (const data of this.data) { for (const [i, v] of data.entries()) { yield [offset + i, v]; } offset += data.size; } } /** * Get the count of distinct values. * * @note this is O(1) for non-object types and O(n) + extra hashing logic for larger objects */ countUnique(): number { let count = 0; // eslint-disable-next-line @typescript-eslint/no-unused-vars for (const v of this.unique()) { count++; } return count; } /** * Get the unique values with the index in a tuple form. * This is useful for reconstructing an Vector * with only the unique values */ * unique(): Iterable<[index: number, value: T]> { if (!this.data.length) return; const hashes = new Set<any>(); const getHash = this.data[0].isPrimitive ? (v: unknown) => v : getHashCodeFrom; // used to handle index offset between data buckets let offset = 0; for (const data of this.data) { for (const [index, value] of data.entries()) { const hash = getHash(value); if (!hashes.has(hash)) { hashes.add(hash); yield [offset + index, value]; } } offset += data.size; } } /** * Get the unique values, excluding nil values. * Useful for getting a list of unique values. */ * uniqueValues(): Iterable<T> { if (!this.data.length) return; const hashes = new Set<any>(); const getHash = this.data[0].isPrimitive ? (v: unknown) => v : getHashCodeFrom; for (const data of this.data) { for (const value of data.values()) { const hash = getHash(value); if (!hashes.has(hash)) { hashes.add(hash); yield value; } } } } /** * Add ReadableData to a end of the data buckets */ append(data: (ReadableData<T>[])|(readonly ReadableData<T>[])|ReadableData<T>): Vector<T> { if (Array.isArray(data)) { const add = data.filter(isNotEmptyDataBucket); if (!add.length) return this; // Make sure to freeze here so freezeArray doesn't slice the data buckets return this.fork(Object.freeze(this.data.concat(add))); } const _singleData = data as ReadableData<T>; if (_singleData.size === 0) return this; // Make sure to freeze here so freezeArray doesn't slice the data buckets return this.fork(Object.freeze(this.data.concat([data as ReadableData<T>]))); } /** * Add ReadableData to a beginning of the data buckets */ prepend(data: ReadableData<T>[]|readonly ReadableData<T>[]|ReadableData<T>): Vector<T> { const preData = ( Array.isArray(data) ? data : [data as ReadableData<T>] ).filter(isNotEmptyDataBucket); if (preData.length === 0) return this; // Make sure to freeze here so freezeArray doesn't slice the data buckets return this.fork(Object.freeze(preData.concat(this.data))); } /** * Get value by index */ get(index: number, json?: boolean, options?: SerializeOptions): Maybe<T> { const nilValue: any = options?.useNullForUndefined ? null : undefined; const found = this.findDataWithIndex(index); if (!found) return nilValue; const val = found[0].get(found[1]); if (val == null) return val ?? nilValue; if (!json || !this.toJSONCompatibleValue) { return val; } return this.toJSONCompatibleValue(val as T, options); } /** * Returns true if the value for that index is not nil */ has(index: number): boolean { const found = this.findDataWithIndex(index); if (!found) return false; return found[0].has(found[1]); } /** * Find the Data bucket that holds the value for that * bucket * @returns the data found and the index of the relative index of value */ findDataWithIndex(index: number): [data:ReadableData<T>, actualIndex: number]|undefined { if (this.data.length === 0) return; if (this.data.length === 1) { if (index + 1 > this.size) return; return [this.data[0], index]; } // if it on the second half of the data set then use the reverse index way if (index > (this.size / 2)) { return this._reverseFindDataWithIndex(index); } return this._forwardFindDataWithIndex(index); } /** * Find the Data bucket that holds the value for that * bucket */ private _forwardFindDataWithIndex( index: number ): [data:ReadableData<T>, actualIndex: number]|undefined { // used to handle index offset between data buckets let offset = 0; for (const data of this.data) { if (index < (data.size + offset)) { return [data, index - offset]; } offset += data.size; } } /** * Find the Data bucket that holds the value for that * bucket this works the in the reverse direction, this * will perform better when there are lots of buckets */ private _reverseFindDataWithIndex( index: number ): [data:ReadableData<T>, actualIndex: number]|undefined { // used to handle index offset between data buckets let offset = this.size; const start = this.data.length - 1; for (let i = start; i >= 0; i--) { const data = this.data[i]; offset -= data.size; if (index >= offset) { return [data, index - offset]; } } } /** * Create a new Vector with the same metadata but with different data */ fork(data: ReadableData<T>[]|readonly ReadableData<T>[]): this { const Constructor = this.constructor as { new( data: ReadableData<T>[]|readonly ReadableData<T>[], config: VectorOptions ): Vector<T>; }; return new Constructor(data, { childConfig: this.childConfig, config: this.config, name: this.name, }) as this; } /** * Create a new Vector with the range of values */ slice(start = 0, end = this.size): Vector<T> { const startIndex = start < 0 ? this.size + start : start; if (startIndex < 0 || startIndex > this.size) { throw new RangeError(`Starting offset of ${start} is out-of-bounds, must be >=0 OR <=${this.size}`); } const endIndex = end < 0 ? this.size + end : end; if (endIndex < 0 || endIndex > this.size) { throw new RangeError(`Ending offset of ${end} is out-of-bounds, must be >=0 OR <=${this.size}`); } const returnSize = endIndex - startIndex; let bucketIndex = 0; let totalProcessed = 0; let offset = 0; let hasStarted = false; const buckets: ReadableData<T>[] = []; while (totalProcessed < returnSize) { const bucket = this.data[bucketIndex]; if (bucket == null) break; const startIndexInBucket = hasStarted ? 0 : startIndex - offset; const endIndexInBucket = Math.min( endIndex - offset, bucket.size ); const totalFromBucket = endIndexInBucket - startIndexInBucket; if (startIndexInBucket >= 0 && totalFromBucket > 0) { const slicedBucket = new ReadableData(bucket.slice( startIndexInBucket, endIndexInBucket )); buckets.push(slicedBucket); hasStarted = true; totalProcessed += slicedBucket.size; } offset += bucket.size; bucketIndex++; } return this.fork(buckets); } /** * Compare two different values on the Vector type. * This can be used for equality or sorted. */ compare(a: Maybe<T>, b: Maybe<T>): -1|0|1 { // we need default undefined to null since // undefined has inconsistent behavior const aVal = this._getComparableValue(a); const bVal = this._getComparableValue(b); if (aVal < bVal) return -1; if (aVal > bVal) return 1; return 0; } private _getComparableValue(value: Maybe<T>): any { if (value == null) return null; if (this.getComparableValue) { return this.getComparableValue(value); } if (isPrimitiveValue(value)) { return value; } throw new Error('Unable to convert value to number for comparison'); } /** * Convert the Vector an array of values (the output is JSON compatible) */ toJSON(options?: SerializeOptions): Maybe<T>[] { const res: Maybe<T>[] = Array(this.size); for (let i = 0; i < this.size; i++) { res[i] = this.get(i, true, options); } return res; } /** * Convert the Vector to array of values (the in-memory representation of the data) * @note may not be JSON spec compatible */ toArray(): Maybe<T>[] { const res: Maybe<T>[] = Array(this.size); for (let i = 0; i < this.size; i++) { res[i] = this.get(i, false) as T; } return res; } /** * Fork the Data object with specific length. * * @param size optionally change the size of the Data */ toWritable(size?: number): WritableData<T> { return WritableData.make<T>( size ?? this.size, (index) => this.get(index) as Maybe<T> ); } } function isNotEmptyDataBucket<T>(data: ReadableData<T>): boolean { return data.size > 0; } /** * Returns true if the input is a Vector */ export function isVector<T>(input: unknown): input is Vector<T> { return input instanceof Vector; } /** * A list of Vector Options */ export interface VectorOptions { /** * The field config */ config: DataTypeFieldConfig|Readonly<DataTypeFieldConfig>; /** * The type config for any nested fields (currently only works for objects) */ childConfig?: ReadonlyDataTypeFields; /** * The name of field, if specified this will just be used for metadata */ name?: string; }
the_stack
* Namespace for All AlienTube operations. * @namespace AlienTube */ module AlienTube { /** Application class for AlienTube @class Application */ "use strict"; export class Application { static localisationManager: LocalisationManager; static commentSection: CommentSection; currentVideoIdentifier: string; constructor() { // Load preferences from disk. Preferences.initialise(function () { // Check if a version migration is necessary. if (Preferences.getString("lastRunVersion") !== Application.version()) { new Migration(Preferences.getString("lastRunVersion")); /* Update the last run version paramater with the current version so we'll know not to run this migration again. */ Preferences.set("lastRunVersion", Application.version()); } }); // Load language files. Application.localisationManager = new LocalisationManager(function () { // Load stylesheet if (Application.getCurrentBrowser() === Browser.SAFARI) { new HttpRequest(Application.getExtensionRessourcePath("style.css"), RequestType.GET, function (data) { var stylesheet = document.createElement("style"); stylesheet.setAttribute("type", "text/css"); stylesheet.textContent = data; document.head.appendChild(stylesheet); }); } if (Application.currentMediaService() === Service.YouTube) { // Start observer to detect when a new video is loaded. let observer = new MutationObserver(this.youtubeMutationObserver); let config = { attributes: true, childList: true, characterData: true }; //observer.observe(document.querySelector("content"), config); // Start a new comment section. this.currentVideoIdentifier = Application.getCurrentVideoId(); if (Utilities.isVideoPage) { this.waitForYTComments(); } } else if (Application.currentMediaService() === Service.Vimeo) { // Start observer to detect when a new video is loaded. let observer = new MutationObserver(this.vimeoMutationObserver); let config = { attributes: true, childList: true, characterData: true }; observer.observe(document.querySelector(".extras_wrapper"), config); } }.bind(this)); } private waitForYTComments() { if (!document.getElementById("contents")) { setTimeout(() => {this.waitForYTComments()}, 500); return; } if (document.getElementById("contents").childElementCount == 0) { var commentsHeader = document.getElementsByClassName('ytd-comments-header-renderer count-text'); if (commentsHeader.length && /^[^0]/.test(commentsHeader[0].innerHTML)) { setTimeout(() => {this.waitForYTComments()}, 500); return; } } setTimeout(() => {Application.commentSection = new CommentSection(this.currentVideoIdentifier)}, 500); } /** * Mutation Observer for monitoring for whenver the user changes to a new "page" on YouTube * @param mutations A collection of mutation records * @private */ private youtubeMutationObserver(mutations: Array<MutationRecord>) { mutations.forEach(function (mutation) { let target = <HTMLElement>mutation.target; if (target.classList.contains("yt-card") ||  target.id === "content") { let reportedVideoId = Application.getCurrentVideoId(); if (reportedVideoId !== this.currentVideoIdentifier) { this.currentVideoIdentifier = reportedVideoId; if (Utilities.isVideoPage) { Application.commentSection = new CommentSection(this.currentVideoIdentifier); } } } }.bind(this)); } /** * Mutation Observer for monitoring for whenver the user changes to a new "page" on YouTube * @param mutations A collection of mutation records * @private */ private vimeoMutationObserver(mutations: Array<MutationRecord>) { mutations.forEach(function (mutation) { let target = <HTMLElement>mutation.target; let reportedVideoId = Application.getCurrentVideoId(); if (reportedVideoId !== this.currentVideoIdentifier) { this.currentVideoIdentifier = reportedVideoId; if (Utilities.isVideoPage) { Application.commentSection = new CommentSection(this.currentVideoIdentifier); } } }.bind(this)); } /** * Get the current video identifier of the window. * @returns video identifier. */ public static getCurrentVideoId(): string { if (Application.currentMediaService() === Service.YouTube) { if (window.location.search.length > 0) { let s = window.location.search.substring(1); let requestObjects = s.split('&'); for (let i = 0, len = requestObjects.length; i < len; i += 1) { let obj = requestObjects[i].split('='); if (obj[0] === "v") { return obj[1]; } } } } else if (Application.currentMediaService() === Service.Vimeo) { if (window.location.pathname.length > 1) { return window.location.pathname.substring(1); } } return null; } /** * Get a Reddit-style "x time ago" Timestamp from a unix epoch time. * @param epochTime Epoch timestamp to calculate from. * @returns A string with a human readable time. */ public static getHumanReadableTimestamp(epochTime: number, localisationString = "timestamp_format"): string { let secs = Math.floor(((new Date()).getTime() / 1000) - epochTime); secs = Math.abs(secs); let timeUnits = { Year: Math.floor(secs / 60 / 60 / 24 / 365.27), Month: Math.floor(secs / 60 / 60 / 24 / 30), Day: Math.floor(secs / 60 / 60 / 24), Hour: Math.floor(secs / 60 / 60), Minute: Math.floor(secs / 60), Second: secs, }; /* Retrieve the most relevant number by retrieving the first one that is "1" or more. Decide if it is plural and retrieve the correct localisation */ for (let timeUnit in timeUnits) { if (timeUnits.hasOwnProperty(timeUnit) && timeUnits[timeUnit] >= 1) { return Application.localisationManager.get(localisationString, [ timeUnits[timeUnit], Application.localisationManager.getWithLocalisedPluralisation(`timestamp_format_${ timeUnit.toLowerCase() }`, timeUnits[timeUnit]) ]); } } return Application.localisationManager.get(localisationString, [ "0", Application.localisationManager.getWithLocalisedPluralisation('timestamp_format_second', 0) ]); } /** * Get the path to a ressource in the AlienTube folder. * @param path Filename to the ressource. * @returns Ressource path (file://) */ public static getExtensionRessourcePath(path: string): string { switch (Application.getCurrentBrowser()) { case Browser.SAFARI: return safari.extension.baseURI + 'res/' + path; case Browser.CHROME: return chrome.extension.getURL('res/' + path); case Browser.FIREFOX: return self.options.ressources[path]; default: return null; } } /** * Get the HTML templates for the extension * @param callback A callback to be called when the extension templates has been loaded. */ public static getExtensionTemplates(callback: any) { switch (Application.getCurrentBrowser()) { case Browser.FIREFOX: let template = document.createElement("div"); let handlebarHTML = Handlebars.compile(self.options.template); template.innerHTML = handlebarHTML(); if (callback) { callback(template); } break; case Browser.SAFARI: new HttpRequest(Application.getExtensionRessourcePath("templates.html"), RequestType.GET, function (data) { let template = document.createElement("div"); let handlebarHTML = Handlebars.compile(data); template.innerHTML = handlebarHTML(); if (callback) { callback(template); } }.bind(this), null, null); break; case Browser.CHROME: let templateLink = document.createElement("link"); templateLink.id = "alientubeTemplate"; templateLink.onload = function () { if (callback) { callback((<any>templateLink).import); } }.bind(this); templateLink.setAttribute("rel", "import"); templateLink.setAttribute("href", Application.getExtensionRessourcePath("templates.html")); document.head.appendChild(templateLink); break; } } /** * Get the current version of the extension. * @public */ public static version(): string { let version = ""; switch (Application.getCurrentBrowser()) { case Browser.CHROME: version = chrome.runtime.getManifest()["version"]; break; case Browser.FIREFOX: version = self.options.version; break; case Browser.SAFARI: version = safari.extension.displayVersion; break; } return version; } /** * Get an element from the template collection. * @param templateCollection The template collection to use. * @param id The id of the element you want to retreive. * @returns DOM node of a template section. */ public static getExtensionTemplateItem(templateCollection: any, id: string) { switch (Application.getCurrentBrowser()) { case Browser.CHROME: return templateCollection.getElementById(id).content.cloneNode(true); case Browser.FIREFOX: return templateCollection.querySelector("#" + id).content.cloneNode(true); case Browser.SAFARI: return templateCollection.querySelector("#" + id).content.cloneNode(true); } } /** * Get the current media website that AlienTube is on * @returns A "Service" enum value representing a media service. */ public static currentMediaService() : Service { if (window.location.host === "www.youtube.com") { return Service.YouTube; } else if (window.location.host === "vimeo.com") { return Service.Vimeo; } return null; } /** * Retrieve the current browser that AlienTube is running on. * @returns A "Browser" enum value representing a web browser. */ static getCurrentBrowser() { if (typeof (chrome) !== 'undefined') return Browser.CHROME; else if (typeof (self.on) !== 'undefined') return Browser.FIREFOX; else if (typeof (safari) !== 'undefined') return Browser.SAFARI; else { throw "Invalid Browser"; } } } } enum Service { YouTube, Vimeo }
the_stack
* @packageDocumentation * @module Voice * @publicapi * @internal */ import { EventEmitter } from 'events'; import Device from './device'; import DialtonePlayer from './dialtonePlayer'; import { TwilioError } from './errors'; import RTCSample from './rtc/sample'; import StatsMonitor from './statsMonitor'; /** * @private */ export declare type IAudioHelper = any; /** * @private */ export declare type IPStream = any; /** * @private */ export declare type IPeerConnection = any; /** * @private */ export declare type IPublisher = any; /** * @private */ export declare type ISound = any; /** * A {@link Connection} represents a media and signaling connection to a TwiML application. * @publicapi */ declare class Connection extends EventEmitter { /** * String representation of the {@link Connection} class. * @private */ static toString: () => string; /** * Returns caller verification information about the caller. * If no caller verification information is available this will return null. */ readonly callerInfo: Connection.CallerInfo | null; /** * The custom parameters sent to (outgoing) or received by (incoming) the TwiML app. */ readonly customParameters: Map<string, string>; /** * Whether this {@link Connection} is incoming or outgoing. */ get direction(): Connection.CallDirection; /** * Audio codec used for this {@link Connection}. Expecting {@link Connection.Codec} but * will copy whatever we get from RTC stats. */ get codec(): string; /** * The MediaStream (Twilio PeerConnection) this {@link Connection} is using for * media signaling. * @private */ mediaStream: IPeerConnection; /** * The temporary CallSid for this call, if it's outbound. */ readonly outboundConnectionId?: string; /** * Call parameters received from Twilio for an incoming call. */ parameters: Record<string, string>; /** * Audio codec used for this {@link Connection}. Expecting {@link Connection.Codec} but * will copy whatever we get from RTC stats. */ private _codec; /** * Whether this {@link Connection} is incoming or outgoing. */ private readonly _direction; /** * The number of times input volume has been the same consecutively. */ private _inputVolumeStreak; /** * Whether the call has been answered. */ private _isAnswered; /** * Whether the call has been cancelled. */ private _isCancelled; /** * Whether or not the browser uses unified-plan SDP by default. */ private readonly _isUnifiedPlanDefault; /** * The most recent public input volume value. 0 -> 1 representing -100 to -30 dB. */ private _latestInputVolume; /** * The most recent public output volume value. 0 -> 1 representing -100 to -30 dB. */ private _latestOutputVolume; /** * An instance of Logger to use. */ private _log; /** * An instance of Backoff for media reconnection */ private _mediaReconnectBackoff; /** * Timestamp for the initial media reconnection */ private _mediaReconnectStartTime; /** * A batch of metrics samples to send to Insights. Gets cleared after * each send and appended to on each new sample. */ private readonly _metricsSamples; /** * An instance of StatsMonitor. */ private readonly _monitor; /** * The number of times output volume has been the same consecutively. */ private _outputVolumeStreak; /** * An instance of EventPublisher. */ private readonly _publisher; /** * A Map of Sounds to play. */ private readonly _soundcache; /** * State of the {@link Connection}. */ private _status; /** * TwiML params for the call. May be set for either outgoing or incoming calls. */ private readonly message; /** * Options passed to this {@link Connection}. */ private options; /** * The PStream instance to use for Twilio call signaling. */ private readonly pstream; /** * Whether the {@link Connection} should send a hangup on disconnect. */ private sendHangup; /** * @constructor * @private * @param config - Mandatory configuration options * @param [options] - Optional settings */ constructor(config: Connection.Config, options?: Connection.Options); /** * Get the real CallSid. Returns null if not present or is a temporary call sid. * @deprecated * @private */ _getRealCallSid(): string | null; /** * Get the temporary CallSid. * @deprecated * @private */ _getTempCallSid(): string | undefined; /** * Set the audio input tracks from a given stream. * @param stream * @private */ _setInputTracksFromStream(stream: MediaStream | null): Promise<void>; /** * Set the audio output sink IDs. * @param sinkIds * @private */ _setSinkIds(sinkIds: string[]): Promise<void>; /** * Accept the incoming {@link Connection}. * @param [audioConstraints] * @param [rtcConfiguration] - An RTCConfiguration to override the one set in `Device.setup`. */ accept(audioConstraints?: MediaTrackConstraints | boolean, rtcConfiguration?: RTCConfiguration): void; /** * @deprecated - Set a handler for the {@link acceptEvent} * @param handler */ accept(handler: (connection: this) => void): void; /** * @deprecated - Ignore the incoming {@link Connection}. */ cancel(): void; /** * @deprecated - Set a handler for the {@link cancelEvent} */ cancel(handler: () => void): void; /** * Disconnect from the {@link Connection}. */ disconnect(): void; /** * @deprecated - Set a handler for the {@link disconnectEvent} */ disconnect(handler: (connection: this) => void): void; /** * @deprecated - Set a handler for the {@link errorEvent} */ error(handler: (error: Connection.Error) => void): void; /** * Get the local MediaStream, if set. */ getLocalStream(): MediaStream | undefined; /** * Get the remote MediaStream, if set. */ getRemoteStream(): MediaStream | undefined; /** * Ignore the incoming {@link Connection}. */ ignore(): void; /** * @deprecated - Set a handler for the {@link cancelEvent} */ ignore(handler: () => void): void; /** * Check if connection is muted */ isMuted(): boolean; /** * Mute incoming audio. * @param shouldMute - Whether the incoming audio should be muted. Defaults to true. */ mute(shouldMute?: boolean): void; /** * @deprecated - Set a handler for the {@link muteEvent} */ mute(handler: (isMuted: boolean, connection: this) => void): void; /** * Post an event to Endpoint Analytics indicating that the end user * has given call quality feedback. Called without a score, this * will report that the customer declined to give feedback. * @param score - The end-user's rating of the call; an * integer 1 through 5. Or undefined if the user declined to give * feedback. * @param issue - The primary issue the end user * experienced on the call. Can be: ['one-way-audio', 'choppy-audio', * 'dropped-call', 'audio-latency', 'noisy-call', 'echo'] */ postFeedback(score?: Connection.FeedbackScore, issue?: Connection.FeedbackIssue): Promise<void>; /** * Reject the incoming {@link Connection}. */ reject(): void; /** * @deprecated - Set a handler for the {@link rejectEvent} */ reject(handler: () => void): void; /** * Send a string of digits. * @param digits */ sendDigits(digits: string): void; /** * Get the current {@link Connection} status. */ status(): Connection.State; /** * String representation of {@link Connection} instance. * @private */ toString: () => string; /** * @deprecated - Unmute the {@link Connection}. */ unmute(): void; /** * @deprecated - Set a handler for the {@link volumeEvent} * @param handler */ volume(handler: (inputVolume: number, outputVolume: number) => void): void; /** * Add a handler for an EventEmitter and emit a deprecation warning on first call. * @param eventName - Name of the event * @param handler - A handler to call when the event is emitted */ private _addHandler; /** * Check the volume passed, emitting a warning if one way audio is detected or cleared. * @param currentVolume - The current volume for this direction * @param streakFieldName - The name of the field on the {@link Connection} object that tracks how many times the * current value has been repeated consecutively. * @param lastValueFieldName - The name of the field on the {@link Connection} object that tracks the most recent * volume for this direction * @param direction - The directionality of this audio track, either 'input' or 'output' * @returns The current streak; how many times in a row the same value has been polled. */ private _checkVolume; /** * Clean up event listeners. */ private _cleanupEventListeners; /** * Create the payload wrapper for a batch of metrics to be sent to Insights. */ private _createMetricPayload; /** * Disconnect the {@link Connection}. * @param message - A message explaining why the {@link Connection} is being disconnected. * @param wasRemote - Whether the disconnect was triggered locally or remotely. */ private _disconnect; private _emitWarning; /** * Transition to {@link ConnectionStatus.Open} if criteria is met. */ private _maybeTransitionToOpen; /** * Called when the {@link Connection} is answered. * @param payload */ private _onAnswer; /** * Called when the {@link Connection} is cancelled. * @param payload */ private _onCancel; /** * Called when the {@link Connection} is hung up. * @param payload */ private _onHangup; /** * Called when there is a media failure. * Manages all media-related states and takes action base on the states * @param type - Type of media failure */ private _onMediaFailure; /** * Called when media connection is restored */ private _onMediaReconnected; /** * When we get a RINGING signal from PStream, update the {@link Connection} status. * @param payload */ private _onRinging; /** * Called each time StatsMonitor emits a sample. * Emits stats event and batches the call stats metrics and sends them to Insights. * @param sample */ private _onRTCSample; /** * Called when we receive a transportClose event from pstream. * Re-emits the event. */ private _onTransportClose; /** * Post an event to Endpoint Analytics indicating that the end user * has ignored a request for feedback. */ private _postFeedbackDeclined; /** * Publish the current set of queued metrics samples to Insights. */ private _publishMetrics; /** * Re-emit an StatsMonitor warning as a {@link Connection}.warning or .warning-cleared event. * @param warningData * @param wasCleared - Whether this is a -cleared or -raised event. */ private _reemitWarning; /** * Re-emit an StatsMonitor warning-cleared as a .warning-cleared event. * @param warningData */ private _reemitWarningCleared; /** * Set the CallSid * @param payload */ private _setCallSid; } declare namespace Connection { /** * Possible states of the {@link Connection}. */ enum State { Closed = "closed", Connecting = "connecting", Open = "open", Pending = "pending", Reconnecting = "reconnecting", Ringing = "ringing" } /** * Different issues that may have been experienced during a call, that can be * reported to Twilio Insights via {@link Connection}.postFeedback(). */ enum FeedbackIssue { AudioLatency = "audio-latency", ChoppyAudio = "choppy-audio", DroppedCall = "dropped-call", Echo = "echo", NoisyCall = "noisy-call", OneWayAudio = "one-way-audio" } /** * A rating of call quality experienced during a call, to be reported to Twilio Insights * via {@link Connection}.postFeedback(). */ enum FeedbackScore { One = 1, Two = 2, Three = 3, Four = 4, Five = 5 } /** * The directionality of the {@link Connection}, whether incoming or outgoing. */ enum CallDirection { Incoming = "INCOMING", Outgoing = "OUTGOING" } /** * Valid audio codecs to use for the media connection. */ enum Codec { Opus = "opus", PCMU = "pcmu" } /** * Possible ICE Gathering failures */ enum IceGatheringFailureReason { None = "none", Timeout = "timeout" } /** * Possible media failures */ enum MediaFailure { ConnectionDisconnected = "ConnectionDisconnected", ConnectionFailed = "ConnectionFailed", IceGatheringFailed = "IceGatheringFailed", LowBytes = "LowBytes" } /** * The error format used by errors emitted from {@link Connection}. */ interface Error { /** * Error code */ code: number; /** * Reference to the {@link Connection} */ connection: Connection; /** * The info object from rtc/peerconnection. May contain code and message (duplicated here). */ info: { code?: number; message?: string; }; /** * Error message */ message: string; /** * Twilio Voice related error */ twilioError?: TwilioError; } /** * A CallerInfo provides caller verification information. */ interface CallerInfo { /** * Whether or not the caller's phone number has been verified by * Twilio using SHAKEN/STIR validation. True if the caller has * been validated at level 'A', false if the caller has been * verified at any lower level or has failed validation. */ isVerified: boolean; } /** * Mandatory config options to be passed to the {@link Connection} constructor. * @private */ interface Config { /** * An AudioHelper instance to be used for input/output devices. */ audioHelper: IAudioHelper; /** * A method to use for getUserMedia. */ getUserMedia: (constraints: MediaStreamConstraints) => Promise<MediaStream>; /** * Whether or not the browser uses unified-plan SDP by default. */ isUnifiedPlanDefault: boolean; /** * The PStream instance to use for Twilio call signaling. */ pstream: IPStream; /** * An EventPublisher instance to use for publishing events */ publisher: IPublisher; /** * A Map of Sounds to play. */ soundcache: Map<Device.SoundName, ISound>; } /** * Options to be passed to the {@link Connection} constructor. * @private */ interface Options { /** * Audio Constraints to pass to getUserMedia when making or accepting a Call. * This is placed directly under `audio` of the MediaStreamConstraints object. */ audioConstraints?: MediaTrackConstraints | boolean; /** * A method to call before Connection.accept is processed. */ beforeAccept?: (connection: Connection) => void; /** * Custom format context parameters associated with this call. */ callParameters?: Record<string, string>; /** * An ordered array of codec names, from most to least preferred. */ codecPreferences?: Codec[]; /** * A DialTone player, to play mock DTMF sounds. */ dialtonePlayer?: DialtonePlayer; /** * Whether or not to enable DSCP. */ dscp?: boolean; /** * Whether to automatically restart ICE when media connection fails */ enableIceRestart?: boolean; /** * Whether the ringing state should be enabled. */ enableRingingState?: boolean; /** * Experimental feature. * Force Chrome's ICE agent to use aggressive nomination when selecting a candidate pair. */ forceAggressiveIceNomination?: boolean; /** * The gateway currently connected to. */ gateway?: string; /** * A method that returns the current input MediaStream set on {@link Device}. */ getInputStream?: () => MediaStream; /** * A method that returns the current SinkIDs set on {@link Device}. */ getSinkIds?: () => string[]; /** * The maximum average audio bitrate to use, in bits per second (bps) based on * [RFC-7587 7.1](https://tools.ietf.org/html/rfc7587#section-7.1). By default, the setting * is not used. If you specify 0, then the setting is not used. Any positive integer is allowed, * but values outside the range 6000 to 510000 are ignored and treated as 0. The recommended * bitrate for speech is between 8000 and 40000 bps as noted in * [RFC-7587 3.1.1](https://tools.ietf.org/html/rfc7587#section-3.1.1). */ maxAverageBitrate?: number; /** * Custom MediaStream (PeerConnection) constructor. Overrides mediaStreamFactory (deprecated). */ MediaStream?: IPeerConnection; /** * Custom MediaStream (PeerConnection) constructor (deprecated) */ mediaStreamFactory?: IPeerConnection; /** * The offer SDP, if this is an incoming call. */ offerSdp?: string | null; /** * Whether this is a preflight call or not */ preflight?: boolean; /** * The Region currently connected to. */ region?: string; /** * An RTCConfiguration to pass to the RTCPeerConnection constructor. */ rtcConfiguration?: RTCConfiguration; /** * RTC Constraints to pass to getUserMedia when making or accepting a Call. * The format of this object depends on browser. */ rtcConstraints?: MediaStreamConstraints; /** * The region passed to {@link Device} on setup. */ selectedRegion?: string; /** * Whether the disconnect sound should be played. */ shouldPlayDisconnect?: () => boolean; /** * An override for the StatsMonitor dependency. */ StatsMonitor?: new () => StatsMonitor; /** * TwiML params for the call. May be set for either outgoing or incoming calls. */ twimlParams?: Record<string, any>; } /** * Call metrics published to Insight Metrics. * This include rtc samples and audio information. * @private */ interface CallMetrics extends RTCSample { /** * Percentage of maximum volume, between 0.0 to 1.0, representing -100 to -30 dB. */ inputVolume: number; /** * Percentage of maximum volume, between 0.0 to 1.0, representing -100 to -30 dB. */ outputVolume: number; } } export default Connection;
the_stack
import {AfterViewInit, ChangeDetectorRef, Component, ElementRef, OnInit, QueryList, ViewChildren} from "@angular/core"; import {ReplaySubject} from "rxjs/ReplaySubject"; import {TabData} from "../../../../electron/src/storage/types/tab-data-interface"; import {AuthService} from "../../auth/auth.service"; import {StatusBarService} from "../../layout/status-bar/status-bar.service"; import {LocalRepositoryService} from "../../repository/local-repository.service"; import {IpcService} from "../../services/ipc.service"; import {MenuItem} from "../../ui/menu/menu-item"; import {ModalService} from "../../ui/modal/modal.service"; import {DirectiveBase} from "../../util/directive-base/directive-base"; import {ClosingDirtyAppsModalComponent} from "../modals/closing-dirty-apps/closing-dirty-apps-modal.component"; import {WorkboxService} from "./workbox.service"; import {startWith, delay, filter, map, switchMap} from "rxjs/operators"; @Component({ selector: "ct-workbox", styleUrls: ["./workbox.component.scss"], template: ` <div class="head"> <ul class="tab-bar inset-panel" tabindex="-1"> <li *ngFor="let tab of tabs; let i = index" [ct-drag-over]="true" (onDragOver)="workbox.openTab(tab)" ct-click (onMouseClick)="onTabClick($event, tab)" [class.active]="tab === (workbox.activeTab | async)" [class.isDirty]="tabComponents[i]?.isDirty" [ct-context]="createContextMenu(tab)" class="tab"> <!-- Tab label and title --> <ng-container [ngSwitch]="tab?.type"> <!-- Welcome tab--> <ng-template ngSwitchCase="Welcome"> <div class="tab-icon"> <i class="fa fa-home"></i> </div> <div class="title" data-test="tab-title" [ct-tooltip]="ctt" [tooltipPlacement]="'bottom'"> {{tab.label}} </div> </ng-template> <!-- Code tab--> <ng-template ngSwitchCase="Code"> <div class="tab-icon"> <i class="fa fa-file"></i> </div> <div class="title" [ct-tooltip]="ctt" [tooltipPlacement]="'bottom'" data-test="tab-title"> {{tab.label}} </div> </ng-template> <!-- Workflow tab--> <ng-template ngSwitchCase="Workflow"> <div class="tab-icon"> <i class="fa fa-share-alt"></i> </div> <div class="title" [ct-tooltip]="ctt" [tooltipPlacement]="'bottom'" data-test="tab-title"> {{tabComponents[i]?.dataModel?.label || tab.label}} </div> </ng-template> <!-- Command Line Tool tab--> <ng-template ngSwitchCase="CommandLineTool"> <div class="tab-icon"> <i class="fa fa-terminal"></i> </div> <div class="title" [ct-tooltip]="ctt" [tooltipPlacement]="'bottom'" data-test="tab-title"> {{tabComponents[i]?.dataModel?.label || tab.label}} </div> </ng-template> <!-- New File tab--> <ng-template ngSwitchCase="NewFile"> <div class="tab-icon"> <i class="fa fa-home"></i> </div> <div class="title" data-test="tab-title" [ct-tooltip]="ctt" [tooltipPlacement]="'bottom'"> {{tab.label}} </div> </ng-template> <!-- Settings tab--> <ng-template ngSwitchCase="Settings"> <div class="tab-icon"> <i class="fa fa-cog"></i> </div> <div class="title" data-test="tab-title" [ct-tooltip]="ctt" [tooltipPlacement]="'bottom'"> {{tab.label}} </div> </ng-template> </ng-container> <div class="close-icon"> <i class="fa fa-times clickable" data-test="tab-close-button" [attr.data-label]="tab.label" (click)="workbox.closeTab(tab)"></i> </div> <!--Tooltip content--> <ct-tooltip-content [maxWidth]="500" #ctt> {{ tab.data?.id || tab.label}} </ct-tooltip-content> </li> <li class="ct-workbox-add-tab-icon clickable" (click)="openNewFileTab()"> <i class="fa fa-plus"></i> </li> </ul> <ct-settings-menu></ct-settings-menu> </div> <div class="body"> <div class="component-container" *ngFor="let tab of tabs" [class.hidden]="tab !== activeTab"> <ct-workbox-tab #tabComponentContainer [tab]="tab" [isActive]="activeTab === tab"> </ct-workbox-tab> </div> </div> ` }) export class WorkBoxComponent extends DirectiveBase implements OnInit, AfterViewInit { /** List of tab data objects */ tabs: TabData<any>[] = []; /** Reference to an active tab object */ activeTab: TabData<any>; private el: Element; @ViewChildren("tabComponentContainer") private tabComponentContainers: QueryList<any>; /** True if prompt closing modal is open */ private promptClosingModalOpen = false; /** Components that are shown in tab */ tabComponents = []; constructor(private ipc: IpcService, public workbox: WorkboxService, private auth: AuthService, private local: LocalRepositoryService, private statusBar: StatusBarService, private cdr: ChangeDetectorRef, private modal: ModalService, el: ElementRef) { super(); this.el = el.nativeElement; } ngOnInit() { // FIXME: this needs to be handled in a system-specific way // Listen for a shortcut that should close the active tab this.ipc.watch("accelerator", "CmdOrCtrl+W").pipe( filter(() => !this.promptClosingModalOpen) ).subscribeTracked(this, () => { this.workbox.closeTab(); }); // Switch to the tab on the right this.ipc.watch("accelerator", "CmdOrCtrl+Shift+]").pipe( filter(_ => this.activeTab && this.tabs.length > 1 && !this.promptClosingModalOpen) ).subscribeTracked(this, () => { this.workbox.activateNext(); }); // Switch to the tab on the left this.ipc.watch("accelerator", "CmdOrCtrl+Shift+[").pipe( filter(_ => this.activeTab && this.tabs.length > 1 && !this.promptClosingModalOpen) ).subscribeTracked(this, () => this.workbox.activatePrevious()); this.ipc.watch("accelerator", "CmdOrCtrl+S").pipe( filter(() => this.activeTab !== undefined && !this.promptClosingModalOpen), map(() => { const activeTabIndex = this.tabs.indexOf(this.activeTab); return this.tabComponents[activeTabIndex]; }), filter(Boolean) ).subscribeTracked(this, (component) => { if (typeof component.save === "function") { try { component.save(); } catch (ex) { console.warn("Unable to save.", ex); } } }); this.workbox.tabs.subscribeTracked(this, tabs => { this.tabs = tabs; }); this.workbox.closeTabStream.subscribeTracked(this, tab => { this.closeTab(tab); }); this.workbox.closeAllTabsStream.subscribeTracked(this, tabs => { this.closeAllTabs(tabs); }); } ngAfterViewInit() { const replayComponents = new ReplaySubject(1); this.tabComponentContainers.changes.subscribeTracked(this, replayComponents); this.workbox.activeTab.subscribeTracked(this, () => { this.statusBar.removeControls(); }); this.workbox.activeTab.pipe( delay(1), switchMap(tab => replayComponents.pipe( filter((list: QueryList<any>) => list.find((item) => item.tab === tab)) ), tab => tab) ).subscribeTracked(this, (tab) => { // activeTab has to be set in the next tick, otherwise we will have ExpressionChangedAfterItHadBeenCheckedError in some cases setTimeout(() => this.activeTab = tab); const idx = this.tabs.findIndex(t => t === tab); const component = this.tabComponentContainers.find((item, index) => index === idx); if (component) { this.statusBar.setControls(component.provideStatusControls()); setTimeout(() => { component.onTabActivation(); }); } }); this.tabComponentContainers.changes.pipe( startWith(this.tabComponentContainers), delay(1) ).subscribeTracked(this, components => { this.tabComponents = components.toArray().map((c) => c.tabComponent); }); } getTabComponent(tab) { const idx = this.tabs.findIndex(t => t === tab); return this.tabComponentContainers.find((item, index) => index === idx); } /** * When you click on a tab */ onTabClick(event: MouseEvent, tab) { // Middle click if (event.button === 0) { this.workbox.openTab(tab); } else if (event.button === 1) { this.workbox.closeTab(tab); } } /** * Closes a tab */ closeTab(tab: TabData<any>) { if (this.promptClosingModalOpen) { return; } const index = this.tabs.findIndex((t) => t === tab); if (index === -1) { return; } const tabComponent = this.tabComponents[index]; if (tabComponent.isDirty) { this.modal.wrapPromise(() => { this.promptClosingModalOpen = true; const modalComponent = this.modal.fromComponent(ClosingDirtyAppsModalComponent, "Save changes?", { confirmationLabel: "Save", discardLabel: "Close without saving", onDiscard: () => this.workbox.closeTab(tab, true), inAnyCase: () => { this.modal.close(modalComponent); this.promptClosingModalOpen = false; }, onConfirm: () => { const save = tabComponent.save(); if (save instanceof Promise) { save.then(isSaved => { if (isSaved) { this.workbox.closeTab(tab, true) } }); } }, }); }).catch(() => { this.modal.close(); this.promptClosingModalOpen = false; }); } else { this.workbox.closeTab(tab, true); } } /** * Opens a new file tab */ openNewFileTab() { this.workbox.openTab(this.workbox.homeTabData, false); } createContextMenu(tab): MenuItem[] { const closeOthers = new MenuItem("Close Others", { click: () => this.closeAllTabs([tab]) }); const closeAll = new MenuItem("Close All", { click: () => this.closeAllTabs() }); return [closeOthers, closeAll]; } /** * Closes all tabs except ones that should be preserved */ private closeAllTabs(preserve: TabData<any>[] = []) { if (this.promptClosingModalOpen) { return; } const components = preserve.map((tab) => this.getTabComponent(tab).tabComponent); const hasDirtyTabs = this.tabComponents.find((tabComponent) => { return tabComponent.isDirty && !components.includes(tabComponent); }); const modalTitle = `Close ${components.length ? "other" : "all"} tabs`; if (hasDirtyTabs) { this.promptClosingModalOpen = true; // If there are apps that are Dirty show modal const modal = this.modal.confirm({ title: modalTitle, content: "Some documents are modified\nYour changes will be lost if you don't save them.", confirmationLabel: modalTitle, }); modal.then(() => { this.workbox.closeAllTabs(preserve, true); this.promptClosingModalOpen = false; }, () => { this.promptClosingModalOpen = false; }); } else { this.workbox.closeAllTabs(preserve, true); } } }
the_stack
import Client from '../Client'; import { NONE } from './Constants'; import MaxXmlRequest, { get, load } from './MaxXmlRequest'; /** * Implements internationalization. You can provide any number of * resource files on the server using the following format for the * filename: name[-en].properties. The en stands for any lowercase * 2-character language shortcut (eg. de for german, fr for french). * * If the optional language extension is omitted, then the file is used as a * default resource which is loaded in all cases. If a properties file for a * specific language exists, then it is used to override the settings in the * default resource. All entries in the file are of the form key=value. The * values may then be accessed in code via <get>. Lines without * equal signs in the properties files are ignored. * * Resource files may either be added programmatically using * <add> or via a resource tag in the UI section of the * editor configuration file, eg: * * ```javascript * <Editor> * <ui> * <resource basename="examples/resources/mxWorkflow"/> * ``` * * The above element will load examples/resources/mxWorkflow.properties as well * as the language specific file for the current language, if it exists. * * Values may contain placeholders of the form {1}...{n} where each placeholder * is replaced with the value of the corresponding array element in the params * argument passed to {@link Resources#get}. The placeholder {1} maps to the first * element in the array (at index 0). * * See <Client.language> for more information on specifying the default * language or disabling all loading of resources. * * Lines that start with a # sign will be ignored. * * Special characters * * To use unicode characters, use the standard notation (eg. \u8fd1) or %u as a * prefix (eg. %u20AC will display a Euro sign). For normal hex encoded strings, * use % as a prefix, eg. %F6 will display a "o umlaut" (&ouml;). * * See <resourcesEncoded> to disable this. If you disable this, make sure that * your files are UTF-8 encoded. * * Asynchronous loading * * By default, the core adds two resource files synchronously at load time. * To load these files asynchronously, set {@link LoadResources} to false * before loading Client.js and use {@link Resources#loadResources} instead. */ class Translations { /* * Object that maps from keys to values. */ static resources: { [key: string]: string } = {}; /** * Specifies the extension used for language files. Default is {@link ResourceExtension}. */ static extension = '.txt'; /** * Specifies whether or not values in resource files are encoded with \u or * percentage. Default is false. */ static resourcesEncoded = false; /** * Specifies if the default file for a given basename should be loaded. * Default is true. */ static loadDefaultBundle = true; /** * Specifies if the specific language file file for a given basename should * be loaded. Default is true. */ static loadSpecialBundle = true; /** * Hook for subclassers to disable support for a given language. This * implementation returns true if lan is in <Client.languages>. * * @param lan The current language. */ static isLanguageSupported = (lan: string): boolean => { if (Client.languages != null) { return Client.languages.indexOf(lan) >= 0; } return true; }; /** * Hook for subclassers to return the URL for the special bundle. This * implementation returns basename + <extension> or null if * <loadDefaultBundle> is false. * * @param basename The basename for which the file should be loaded. * @param lan The current language. */ static getDefaultBundle = (basename: string, lan: string): string | null => { if ( Translations.loadDefaultBundle || !Translations.isLanguageSupported(lan) ) { return basename + (Translations.extension ?? Client.mxResourceExtension); } return null; }; /** * Hook for subclassers to return the URL for the special bundle. This * implementation returns basename + '_' + lan + <extension> or null if * <loadSpecialBundle> is false or lan equals <Client.defaultLanguage>. * * If {@link Resources#languages} is not null and <Client.language> contains * a dash, then this method checks if <isLanguageSupported> returns true * for the full language (including the dash). If that returns false the * first part of the language (up to the dash) will be tried as an extension. * * If {@link Resources#language} is null then the first part of the language is * used to maintain backwards compatibility. * * @param basename The basename for which the file should be loaded. * @param lan The language for which the file should be loaded. */ static getSpecialBundle = (basename: string, lan: string): string | null => { if (Client.languages == null || !Translations.isLanguageSupported(lan)) { const dash = lan.indexOf('-'); if (dash > 0) { lan = lan.substring(0, dash); } } if ( Translations.loadSpecialBundle && Translations.isLanguageSupported(lan) && lan != Client.defaultLanguage ) { return `${basename}_${lan}${ Translations.extension ?? Client.mxResourceExtension }`; } return null; }; /** * Adds the default and current language properties file for the specified * basename. Existing keys are overridden as new files are added. If no * callback is used then the request is synchronous. * * Example: * * At application startup, additional resources may be * added using the following code: * * ```javascript * mxResources.add('resources/editor'); * ``` * * @param basename The basename for which the file should be loaded. * @param lan The language for which the file should be loaded. * @param callback Optional callback for asynchronous loading. */ static add = (basename: string, lan: string | null=null, callback: Function | null=null): void => { lan = lan != null ? lan : Client.language != null ? Client.language.toLowerCase() : NONE; if (lan !== NONE) { const defaultBundle = Translations.getDefaultBundle(basename, lan); const specialBundle = Translations.getSpecialBundle(basename, lan); const loadSpecialBundle = () => { if (specialBundle != null) { if (callback) { get( specialBundle, (req: MaxXmlRequest) => { Translations.parse(req.getText()); callback(); }, () => { callback(); } ); } else { try { const req = load(specialBundle); if (req.isReady()) { Translations.parse(req.getText()); } } catch (e) { // ignore } } } else if (callback != null) { callback(); } }; if (defaultBundle != null) { if (callback) { get( defaultBundle, (req: MaxXmlRequest) => { Translations.parse(req.getText()); loadSpecialBundle(); }, () => { loadSpecialBundle(); } ); } else { try { const req = load(defaultBundle); if (req.isReady()) { Translations.parse(req.getText()); } loadSpecialBundle(); } catch (e) { // ignore } } } else { // Overlays the language specific file (_lan-extension) loadSpecialBundle(); } } }; /** * Parses the key, value pairs in the specified * text and stores them as local resources. */ static parse = (text: string): void => { if (text != null) { const lines = text.split('\n'); for (let i = 0; i < lines.length; i += 1) { if (lines[i].charAt(0) !== '#') { const index = lines[i].indexOf('='); if (index > 0) { const key = lines[i].substring(0, index); let idx = lines[i].length; if (lines[i].charCodeAt(idx - 1) === 13) { idx--; } let value = lines[i].substring(index + 1, idx); if (Translations.resourcesEncoded) { value = value.replace(/\\(?=u[a-fA-F\d]{4})/g, '%'); Translations.resources[key] = unescape(value); } else { Translations.resources[key] = value; } } } } } }; /** * Returns the value for the specified resource key. * * Example: * To read the value for 'welomeMessage', use the following: * ```javascript * let result = mxResources.get('welcomeMessage') || ''; * ``` * * This would require an entry of the following form in * one of the English language resource files: * ```javascript * welcomeMessage=Welcome to mxGraph! * ``` * * The part behind the || is the string value to be used if the given * resource is not available. * * @param key String that represents the key of the resource to be returned. * @param params Array of the values for the placeholders of the form {1}...{n} * to be replaced with in the resulting string. * @param defaultValue Optional string that specifies the default return value. */ static get = (key: string, params: any[] | null=null, defaultValue: string | null=null): string | null => { let value: string | null = Translations.resources[key]; // Applies the default value if no resource was found if (value == null) { value = defaultValue; } // Replaces the placeholders with the values in the array if (value != null && params != null) { value = Translations.replacePlaceholders(value, params); } return value; }; /** * Replaces the given placeholders with the given parameters. * * @param value String that contains the placeholders. * @param params Array of the values for the placeholders of the form {1}...{n} * to be replaced with in the resulting string. */ static replacePlaceholders = (value: string, params: string[]): string => { const result = []; let index = null; for (let i = 0; i < value.length; i += 1) { const c = value.charAt(i); if (c === '{') { index = ''; } else if (index != null && c === '}') { index = parseInt(index) - 1; if (index >= 0 && index < params.length) { result.push(params[index]); } index = null; } else if (index != null) { index += c; } else { result.push(c); } } return result.join(''); }; /** * Loads all required resources asynchronously. Use this to load the graph and * editor resources if {@link LoadResources} is false. * * @param callback Callback function for asynchronous loading. */ static loadResources = (callback: Function): void => { Translations.add(`${Client.basePath}/resources/editor`, null, () => { Translations.add(`${Client.basePath}/resources/graph`, null, callback); }); }; }; export default Translations;
the_stack
import { ProvideClient, authenticate, authenticateStub, restore, restoreStub } from "../client/provide-client"; // eslint-disable-next-line no-unused-vars import { Application, Mapping, MappingField, MappingModel, Workflow, Workstep } from "@provide/types"; import { alerts, spinnerOff, spinnerOn } from "../common/alerts"; import { LoginFormData } from "../models/login-form-data"; import { onError } from "../common/common"; import { excelWorker } from "./excel-worker"; import { mappingForm, MappingForm } from "./mappingForm"; import { store } from "../settings/store"; import { TokenStr } from "../models/common"; import { User } from "../models/user"; import { showJwtInputDialog } from "../dialogs/dialogs-helpers"; import { myWorkflow } from "./workflow"; import { myWorkstep } from "./workstep"; import * as $ from "jquery"; // images references in the manifest import "../../assets/icon-16.png"; import "../../assets/icon-32.png"; import "../../assets/icon-80.png"; import "../../assets/logo-filled.png"; import "bootstrap/dist/css/bootstrap.min.css"; import "@fortawesome/fontawesome-free/js/fontawesome"; import "@fortawesome/fontawesome-free/js/solid"; import "@fortawesome/fontawesome-free/js/regular"; import "@fortawesome/fontawesome-free/js/brands"; import "./taskpane.css"; const stubAuth = false; // eslint-disable-next-line no-unused-vars /* global Excel, OfficeExtension, Office */ let identClient: ProvideClient | null; let currentWorkgroupId: string | null; let currentWorkflowId: string | null; Office.onReady((info) => { if (info.host === Office.HostType.Excel) { $(function () { initUi(); tryRestoreAutorization(); }); } }); // eslint-disable-next-line no-unused-vars function tryRestoreAutorization() { return Promise.all([store.getRefreshToken(), store.getUser()]).then(([refreshToken, user]) => { if (!refreshToken || !user) { setUiForLogin(); spinnerOff(); return; } const restoreFn = stubAuth ? restoreStub : restore; spinnerOn(); return restoreFn(refreshToken, user).then( (client) => { identClient = client; setUiAfterLogin(); spinnerOff(); }, (reason) => { store.removeTokenAndUser(); setUiForLogin(); onError(reason); } ); }); } function initUi() { $("#login-btn").on("click", onLogin); $("#logout-btn").on("click", onLogout); $("#refresh-workgroups-btn").on("click", onFillWorkgroups); $("#refresh-workflows-btn").on("click", onFillWorkflows); $("#refresh-worksteps-btn").on("click", onFillWorksteps); $("#show-jwt-input-btn").on("click", onGetJwtokenDialog); $("#mapping-form-btn").on("click", onSubmitMappingForm); $("#workflow-form-btn").on("click", onSubmitCreateWorkflowForm); $("#workstep-form-btn").on("click", onSubmitCreateWorkstepForm); } function setUiForLogin() { $("#sideload-msg").hide(); $("#login-ui").show(); $("#workgroup-ui").hide(); $("#mapping-ui").hide(); $("#app-body").show(); } function setUiAfterLogin() { $("#sideload-msg").hide(); let $workUi = $("#workgroup-ui"); const userName = (identClient.user || {}).name || "unknown"; $("#user-name", $workUi).text(userName); $("#login-ui").hide(); $workUi.show(); $("#mapping-ui").hide(); $("#workflow-ui").hide(); $("#workflow-create-ui").hide(); $("#workstep-ui").hide(); $("#workstep-create-ui").hide(); $("#workstep-details-ui").hide(); $("#app-body").show(); } function setUiForMapping() { $("#sideload-msg").hide(); $("#login-ui").hide(); let $workUi = $("#workgroup-ui"); const userName = (identClient.user || {}).name || "unknown"; $("#user-name", $workUi).text(userName); $("#workgroup-ui").hide(); $("#mapping-ui").show(); $("#workflow-ui").hide(); $("#workflow-create-ui").hide(); $("#workstep-ui").hide(); $("#workstep-create-ui").hide(); $("#workstep-details-ui").hide(); $("#app-body").show(); } function setUiForWorkflows() { $("#sideload-msg").hide(); $("#login-ui").hide(); let $workUi = $("#workgroup-ui"); const userName = (identClient.user || {}).name || "unknown"; $("#user-name", $workUi).text(userName); $("#workgroup-ui").hide(); $("#workflow-ui").show(); $("#mapping-ui").hide(); $("#workflow-create-ui").hide(); $("#workstep-ui").hide(); $("#workstep-create-ui").hide(); $("#workstep-details-ui").hide(); $("#app-body").show(); } function setUiForCreateWorkflow() { $("#sideload-msg").hide(); $("#login-ui").hide(); let $workUi = $("#workgroup-ui"); const userName = (identClient.user || {}).name || "unknown"; $("#user-name", $workUi).text(userName); $("#workgroup-ui").hide(); $("#mapping-ui").hide(); $("#workflow-ui").hide(); $("#workflow-create-ui").show(); $("#workstep-ui").hide(); $("#workstep-create-ui").hide(); $("#workstep-details-ui").hide(); $("#app-body").show(); } function setUiForWorksteps() { $("#sideload-msg").hide(); $("#login-ui").hide(); let $workUi = $("#workgroup-ui"); const userName = (identClient.user || {}).name || "unknown"; $("#user-name", $workUi).text(userName); $("#workgroup-ui").hide(); $("#mapping-ui").hide(); $("#workflow-ui").hide(); $("#workflow-create-ui").hide(); $("#workstep-ui").show(); $("#workstep-create-ui").hide(); $("#workstep-details-ui").hide(); $("#app-body").show(); } function setUiForCreateWorkstep() { $("#sideload-msg").hide(); $("#login-ui").hide(); let $workUi = $("#workgroup-ui"); const userName = (identClient.user || {}).name || "unknown"; $("#user-name", $workUi).text(userName); $("#workgroup-ui").hide(); $("#mapping-ui").hide(); $("#workflow-ui").hide(); $("#workflow-create-ui").hide(); $("#workstep-ui").hide(); $("#workstep-create-ui").show(); $("#workstep-details-ui").hide(); $("#app-body").show(); } function setUiForWorkStepDetails() { $("#sideload-msg").hide(); $("#login-ui").hide(); let $workUi = $("#workgroup-ui"); const userName = (identClient.user || {}).name || "unknown"; $("#user-name", $workUi).text(userName); $("#workgroup-ui").hide(); $("#mapping-ui").hide(); $("#workflow-ui").hide(); $("#workflow-create-ui").hide(); $("#workstep-ui").hide(); $("#workstep-create-ui").hide(); $("#workstep-details-ui").show(); $("#app-body").show(); } async function onLogin(): Promise<void> { await store.open(); const $form = $("#login-ui form"); const loginFormData = new LoginFormData($form); const isValid = loginFormData.isValid(); if (isValid !== true) { alerts.error(<string>isValid); return; } const authenticateFn = stubAuth ? authenticateStub : authenticate; spinnerOn(); return authenticateFn(loginFormData) .then(async (client) => { identClient = client; loginFormData.clean(); setUiAfterLogin(); const token: TokenStr = identClient.userRefreshToken; const user: User = { id: identClient.user.id, name: identClient.user.name, email: identClient.user.email }; await store.removeTokenAndUser(); return store.setTokenAndUser(token, user).then(spinnerOff); }, onError) .then(getMyWorkgroups) .then(startBaselining); } function onLogout() { identClient .logout() .then(async () => { identClient = null; await store.removeTokenAndUser(); return await store.close(); }, onError) .then(() => { setUiForLogin(); spinnerOff(); }, onError); } function onFillWorkgroups(): Promise<unknown> { return getMyWorkgroups(); } function onFillWorkflows(): Promise<unknown> { return getMyWorkflows(currentWorkgroupId); } function onFillWorksteps(): Promise<unknown> { return getMyWorksteps(currentWorkflowId); } // eslint-disable-next-line no-unused-vars function onShowMainPage() { if (!identClient) { setUiForLogin(); return; } setUiAfterLogin(); const token: TokenStr = identClient.userRefreshToken; const user: User = { id: identClient.user.id, name: identClient.user.name, email: identClient.user.email }; return store.setTokenAndUser(token, user).then(spinnerOff).then(getMyWorkgroups, onError); } function onGetJwtokenDialog() { showJwtInputDialog().then( // NOTE: For demo - send data to dialog - part 1 // showJwtInputDialog({ data: "Test JWT" }).then( (jwtInput) => { spinnerOn(); return identClient.acceptWorkgroupInvitation(jwtInput.jwt, jwtInput.orgId).then(() => { spinnerOff(); alerts.success("Invitation completed"); }, onError); }, () => { /* NOTE: On cancel - do nothing */ } ); } function getMyWorkgroups(): Promise<void> { if (!identClient) { setUiForLogin(); return; } setUiAfterLogin(); return identClient.getWorkgroups().then(async (apps) => { await excelWorker.showWorkgroups("My Workgroups", apps); return await activateWorkgroupButtons(apps).then(spinnerOff); }, onError); } async function activateWorkgroupButtons(applications: Application[]): Promise<void> { applications.map((app) => { //Get the buttons elements $("#" + app.id).on("click", function () { getMyWorkflows(app.id); }); //Add Events to it }); } async function getMyWorkflows(appId: string): Promise<void> { if (!identClient) { setUiForLogin(); return; } setUiForWorkflows(); currentWorkgroupId = appId; //Prepare back button $("#workflow-back-btn").on("click", function () { getMyWorkgroups(); }); //Prepare logout button $("#workflow-ui #logout-btn").on("click", onLogout); //Show Mappings excelWorker.showMappingButton(); activateMappingButton(appId); //Create workflow activateWorkflowCreateButton(appId); //Show Workflows return identClient.getWorkflows(appId).then(async (workflows) => { if (workflows.length > 0) { await excelWorker.showWorkflows(workflows); return await activateWorkflowButtons(workflows).then(spinnerOff); } spinnerOff(); return; }, onError); } async function activateWorkflowButtons(workflows: Workflow[]): Promise<void> { workflows.map((workflow) => { //Get the buttons elements $("#" + workflow.id).on("click", function () { getMyWorksteps(workflow.id); }); }); } async function activateWorkflowCreateButton(workgroupId: string): Promise<void> { $("#create-workflow").on("click", function () { createWorkflow(workgroupId); }); } async function activateMappingButton(appId: string): Promise<void> { $("#mapping-btn").on("click", function () { confirmMappings(appId); }); } async function createWorkflow(workgroupId: string): Promise<void> { if (!identClient) { setUiForLogin(); return; } setUiForCreateWorkflow(); //Prepare logout button $("#workflow-create-ui #logout-btn").on("click", onLogout); $("#create-workflow-back-btn").on("click", function () { getMyWorkflows(workgroupId); }); myWorkflow.showCreateWorkflowForm(); } async function onSubmitCreateWorkflowForm(): Promise<unknown> { var workflowName = $("#workflow-create-form #workflow-name").val().toString(); var workgroupId = currentWorkgroupId; var status = "draft"; var version = $("#workflow-create-form #version").val().toString(); var params: Object = { name: workflowName, workgroup_id: workgroupId, status: status, version: version, }; return identClient.createWorkflow(params).then(async () => { return await getMyWorkflows(workgroupId).then(spinnerOff); }, onError); } async function getMyWorksteps(workflowId: string): Promise<void> { if (!identClient) { setUiForLogin(); return; } setUiForWorksteps(); currentWorkflowId = workflowId; $("#workstep-back-btn").on("click", function () { getMyWorkflows(currentWorkgroupId); }); //Prepare logout button $("#workstep-ui #logout-btn").on("click", onLogout); //Create workstep activateWorkstepCreateButton(workflowId); //Show worksteps return identClient.getWorksteps(workflowId).then(async (worksteps) => { if (worksteps && worksteps.length) { await excelWorker.showWorksteps(worksteps); return await activateWorkstepButtons(worksteps).then(spinnerOff); } spinnerOff; return; }, onError); } async function activateWorkstepButtons(worksteps: Workstep[]): Promise<void> { worksteps.map((workstep) => { //Get the buttons elements $("#" + workstep.id).on("click", function () { showWorkstepDetails(workstep.id); }); }); } async function activateWorkstepCreateButton(workflowId: string): Promise<void> { $("#create-workstep").on("click", function () { createWorkstep(workflowId); }); } async function createWorkstep(workflowId: string): Promise<void> { if (!identClient) { setUiForLogin(); return; } setUiForCreateWorkstep(); $("#create-workstep-back-btn").on("click", function () { getMyWorksteps(workflowId); }); //Prepare logout button $("#workstep-create-ui #logout-btn").on("click", onLogout); myWorkstep.showCreateWorkstepForm(); } async function onSubmitCreateWorkstepForm(): Promise<unknown> { var workstepName = $("#workstep-create-form #workstep-name").val().toString(); var params = { name: workstepName, status: "draft", require_finality: true, metadata: { prover: { identifier: "cubic", provider: "gnark", proving_scheme: "groth16", curve: "BN254", }, }, }; return identClient.createWorkstep(currentWorkflowId, params).then(async () => { return await getMyWorksteps(currentWorkflowId).then(spinnerOff); }, onError); } async function showWorkstepDetails(workstepId: string): Promise<void> { if (!identClient) { setUiForLogin(); return; } await identClient.getWorkstepDetails(currentWorkflowId, workstepId).then(async (workstep) => { setUiForWorkStepDetails(); $("#workstep-details-back-btn").on("click", function () { getMyWorksteps(currentWorkgroupId); }); //Prepare logout button $("#workstep-details-ui #logout-btn").on("click", onLogout); await myWorkstep.showWorkstepDetails(workstep); }); } async function confirmMappings(appId: string): Promise<void> { if (!identClient) { setUiForLogin(); return; } setUiForMapping(); //Prepare back button $("#mapping-back-btn").on("click", function () { getMyWorkflows(appId); }); //Prepare logout button $("#mapping-ui #logout-btn").on("click", onLogout); return identClient.getWorkgroupMappings(appId).then(async (mappings) => { if (mappings && mappings.length) { return await mappingForm.showWorkgroupMappings(mappings); } return await mappingForm.showUnmappedColumns(appId); }, onError); } async function onSubmitMappingForm(): Promise<unknown> { return initializeBaselining(mappingForm); } function startBaselining(): Promise<void> { return excelWorker.startBaselineService(identClient); } async function initializeBaselining(mappingForm: MappingForm): Promise<unknown> { spinnerOn(); return excelWorker.createInitialSetup(mappingForm).then(spinnerOff, onError); }
the_stack
import * as backoff from 'backoff'; const fibonacciBackoff = backoff.fibonacci(); fibonacciBackoff; // $ExpectType Backoff backoff.fibonacci({ randomisationFactor: 0, initialDelay: 10, maxDelay: 300 }); backoff.fibonacci({randomisationFactor: 0}); backoff.fibonacci({initialDelay: 10}); backoff.fibonacci({maxDelay: 300}); backoff.exponential(); // $ExpectType Backoff backoff.exponential({ factor: 1, randomisationFactor: 0, initialDelay: 10, maxDelay: 300 }); backoff.exponential({factor: 1}); backoff.exponential({randomisationFactor: 0}); backoff.exponential({initialDelay: 10}); backoff.exponential({maxDelay: 300}); const fibonacciStrategy = new backoff.FibonacciStrategy(); new backoff.FibonacciStrategy({ randomisationFactor: 0, initialDelay: 10, maxDelay: 300 }); new backoff.FibonacciStrategy({randomisationFactor: 0}); new backoff.FibonacciStrategy({initialDelay: 10}); new backoff.FibonacciStrategy({maxDelay: 300}); fibonacciStrategy.next(); // $ExpectType number fibonacciStrategy.reset(); const exponentialStrategy = new backoff.ExponentialStrategy(); new backoff.ExponentialStrategy({ factor: 1, randomisationFactor: 0, initialDelay: 10, maxDelay: 300 }); new backoff.ExponentialStrategy({factor: 1}); new backoff.ExponentialStrategy({randomisationFactor: 0}); new backoff.ExponentialStrategy({initialDelay: 10}); new backoff.ExponentialStrategy({maxDelay: 300}); exponentialStrategy.next(); // $ExpectType number exponentialStrategy.reset(); class MyStrategy extends backoff.BackoffStrategy { constructor() { super({ randomisationFactor: 0, initialDelay: 10, maxDelay: 300 }); } protected next_() { return 1; } protected reset_() { } } const myStrategy = new MyStrategy(); exponentialStrategy.next(); // $ExpectType number exponentialStrategy.reset(); // $ExpectType TypedFunctionCall<undefined[], Error, undefined, undefined, undefined> backoff.call((cb: (err: Error) => void) => {}, (err) => { err; // $ExpectType Error }); // $ExpectType TypedFunctionCall<undefined[], Error, string, undefined, undefined> backoff.call((cb: (err: Error, r1: string) => void) => {}, (err, r1) => { r1; // $ExpectType string err; // $ExpectType Error }); // TypedFunctionCall<undefined[], Error, string, number, undefined> backoff.call((cb: (err: Error, r1: string, r2: number) => void) => {}, (err, r1, r2) => { r1; // $ExpectType string r2; // $ExpectType number err; // $ExpectType Error }); // TypedFunctionCall<undefined[], Error, string, number, boolean> backoff.call((cb: (err: Error, r1: string, r2: number, r3: boolean) => void) => {}, (err, r1, r2, r3) => { r1; // $ExpectType string r2; // $ExpectType number r3; // $ExpectType boolean err; // $ExpectType Error }); // TypedFunctionCall<[number], Error, string, undefined, undefined> backoff.call( (t1: number, cb: (err: Error, r1: string) => void) => { }, 1, (err, r1) => { r1; // $ExpectType string err; // $ExpectType Error }); // TypedFunctionCall<[number], Error, string, number, undefined> backoff.call( (t1: number, cb: (err: Error, r1: string, r2: number) => void) => { }, 1, (err, r1, r2) => { r1; // $ExpectType string r2; // $ExpectType number err; // $ExpectType Error }); // TypedFunctionCall<[number], Error, string, number, boolean> backoff.call( (t1: number, cb: (err: Error, r1: string, r2: number, r3: boolean) => void) => { }, 1, (err, r1, r2, r3) => { r1; // $ExpectType string r2; // $ExpectType number r3; // $ExpectType boolean err; // $ExpectType Error }); // TypedFunctionCall<[number, string], Error, string, undefined, undefined> backoff.call( (t1: number, t2: string, cb: (err: Error, r1: string) => void) => { }, 1, 'foo', (err, r1) => { r1; // $ExpectType string err; // $ExpectType Error }); // TypedFunctionCall<[number, string], Error, string, number, undefined> backoff.call( (t1: number, t2: string, cb: (err: Error, r1: string, r2: number) => void) => { }, 1, 'foo', (err, r1, r2) => { r1; // $ExpectType string r2; // $ExpectType number err; // $ExpectType Error }); // TypedFunctionCall<[number, string], Error, string, number, boolean> backoff.call( (t1: number, t2: string, cb: (err: Error, r1: string, r2: number, r3: boolean) => void) => { }, 1, 'foo', (err, r1, r2, r3) => { r1; // $ExpectType string r2; // $ExpectType number r3; // $ExpectType boolean err; // $ExpectType Error }); // TypedFunctionCall<[number, string, boolean], Error, string, undefined, undefined> backoff.call( (t1: number, t2: string, t3: boolean, cb: (err: Error, r1: string) => void) => { }, 1, 'foo', true, (err, r1) => { r1; // $ExpectType string err; // $ExpectType Error }); // TypedFunctionCall<[number, string, boolean], Error, string, number, undefined> backoff.call( (t1: number, t2: string, t3: boolean, cb: (err: Error, r1: string, r2: number) => void) => { }, 1, 'foo', true, (err, r1, r2) => { r1; // $ExpectType string r2; // $ExpectType number err; // $ExpectType Error }); // TypedFunctionCall<[number, string, boolean], Error, string, number, boolean> backoff.call( (t1: number, t2: string, t3: boolean, cb: (err: Error, r1: string, r2: number, r3: boolean) => void) => { }, 1, 'foo', true, (err, r1, r2, r3) => { r1; // $ExpectType string r2; // $ExpectType number r3; // $ExpectType boolean err; // $ExpectType Error }); // $ExpectType FunctionCallAny backoff.call( (t1: number, t2: string, t3: boolean, t4: string, cb: (err: Error, r1: string, r2: number, r3: boolean) => void) => { }, 1, 'foo', true, 'bar', (err: Error, r1: string, r2: number, r3: boolean) => {}); fibonacciBackoff.failAfter(10); fibonacciBackoff.backoff(new Error('foo')); fibonacciBackoff.reset(); fibonacciBackoff.on('backoff', (number, delay) => { number; // $ExpectType number delay; // $ExpectType number }); fibonacciBackoff.on('ready', (number, delay) => { number; // $ExpectType number delay; // $ExpectType number }); fibonacciBackoff.on('fail', (err) => { err; // $ExpectType any }); // TypedFunctionCall<undefined[], Error, undefined, undefined, undefined> new backoff.FunctionCall((cb: (err: Error) => void) => {}, [], (err) => { err; // $ExpectType Error }); // TypedFunctionCall<undefined[], Error, string, undefined, undefined> new backoff.FunctionCall((cb: (err: Error, r1: string) => void) => {}, [], (err, r1) => { r1; // $ExpectType string err; // $ExpectType Error }); // TypedFunctionCall<undefined[], Error, string, number, undefined> new backoff.FunctionCall((cb: (err: Error, r1: string, r2: number) => void) => {}, [], (err, r1, r2) => { r1; // $ExpectType string r2; // $ExpectType number err; // $ExpectType Error }); // TypedFunctionCall<undefined[], Error, string, number, boolean> new backoff.FunctionCall((cb: (err: Error, r1: string, r2: number, r3: boolean) => void) => {}, [], (err, r1, r2, r3) => { r1; // $ExpectType string r2; // $ExpectType number r3; // $ExpectType boolean err; // $ExpectType Error }); // TypedFunctionCall<[number], Error, string, undefined, undefined> new backoff.FunctionCall( (t1: number, cb: (err: Error, r1: string) => void) => { }, [1], (err, r1) => { r1; // $ExpectType string err; // $ExpectType Error }); // TypedFunctionCall<[number], Error, string, number, undefined> new backoff.FunctionCall( (t1: number, cb: (err: Error, r1: string, r2: number) => void) => { }, [1], (err, r1, r2) => { r1; // $ExpectType string r2; // $ExpectType number err; // $ExpectType Error }); // TypedFunctionCall<[number], Error, string, number, boolean> new backoff.FunctionCall( (t1: number, cb: (err: Error, r1: string, r2: number, r3: boolean) => void) => { }, [1], (err, r1, r2, r3) => { r1; // $ExpectType string r2; // $ExpectType number r3; // $ExpectType boolean err; // $ExpectType Error }); // TypedFunctionCall<[number, string], Error, string, undefined, undefined> new backoff.FunctionCall( (t1: number, t2: string, cb: (err: Error, r1: string) => void) => { }, [1, 'foo'], (err, r1) => { r1; // $ExpectType string err; // $ExpectType Error }); // TypedFunctionCall<[number, string], Error, string, number, undefined> new backoff.FunctionCall( (t1: number, t2: string, cb: (err: Error, r1: string, r2: number) => void) => { }, [1, 'foo'], (err, r1, r2) => { r1; // $ExpectType string r2; // $ExpectType number err; // $ExpectType Error }); // TypedFunctionCall<[number, string], Error, string, number, boolean> new backoff.FunctionCall( (t1: number, t2: string, cb: (err: Error, r1: string, r2: number, r3: boolean) => void) => { }, [1, 'foo'], (err, r1, r2, r3) => { r1; // $ExpectType string r2; // $ExpectType number r3; // $ExpectType boolean err; // $ExpectType Error }); // TypedFunctionCall<[number, string, boolean], Error, string, undefined, undefined> new backoff.FunctionCall( (t1: number, t2: string, t3: boolean, cb: (err: Error, r1: string) => void) => { }, [1, 'foo', true], (err, r1) => { r1; // $ExpectType string err; // $ExpectType Error }); // TypedFunctionCall<[number, string, boolean], Error, string, number, undefined> new backoff.FunctionCall( (t1: number, t2: string, t3: boolean, cb: (err: Error, r1: string, r2: number) => void) => { }, [1, 'foo', true], (err, r1, r2) => { r1; // $ExpectType string r2; // $ExpectType number err; // $ExpectType Error }); const functionCall = new backoff.FunctionCall( (t1: number, t2: string, t3: boolean, cb: (err: Error, r1: string, r2: number, r3: boolean) => void) => { }, [1, 'foo', true], (err, r1, r2, r3) => { r1; // $ExpectType string r2; // $ExpectType number r3; // $ExpectType boolean err; // $ExpectType Error }); functionCall; // TypedFunctionCall<[number, string, boolean], Error, string, number, boolean> // $ExpectType FunctionCallAny new backoff.FunctionCall( (t1: number, t2: string, t3: boolean, t4: string, cb: (err: Error, r1: string, r2: number, r3: boolean) => void) => { }, [1, 'foo', true, 'bar'], (err: Error, r1: string, r2: number, r3: boolean) => {}); functionCall.isPending(); // $ExpectType boolean functionCall.isRunning(); // $ExpectType boolean functionCall.isCompleted(); // $ExpectType boolean functionCall.isAborted(); // $ExpectType boolean functionCall.setStrategy(myStrategy); // $ExpectType TypedFunctionCall<[number, string, boolean], Error, string, number, boolean> functionCall.retryIf(err => err.status === 503); // $ExpectType TypedFunctionCall<[number, string, boolean], Error, string, number, boolean> functionCall.failAfter(10); // $ExpectType TypedFunctionCall<[number, string, boolean], Error, string, number, boolean> functionCall.getLastResult(); // $ExpectType [Error, string, number, boolean] functionCall.getNumRetries(); // $ExpectType number functionCall.start(); functionCall.abort(); functionCall.on('call', args => { args; // $ExpectType [number, string, boolean] }); functionCall.on('callback', args => { args; // $ExpectType [Error, string, number, boolean] }); functionCall.on('backoff', (number, delay, err) => { number; // $ExpectType number delay; // $ExpectType number err; // $ExpectType any }); functionCall.on('abort', () => {});
the_stack
'use strict'; import * as assert from 'assert'; import { before, beforeEach, after } from 'mocha'; import * as fs from 'fs'; import * as vscode from 'vscode'; import * as path from 'path'; import * as extensionFunctions from '../../extensionFunctions'; import {getValue} from '../../utils'; import * as commandHandler from '../../commandHandler'; import { removeFilesAndFolders } from '../../utils'; import { waitUntil } from 'async-wait-until'; import { didactManager } from '../../didactManager'; import { expect } from 'chai'; import { didactTutorialsProvider, revealTreeItem } from '../../extension'; const url = require('url-parse'); const EDITOR_OPENED_TIMEOUT = 5000; const testMD = vscode.Uri.parse('vscode://redhat.vscode-didact?extension=demos/markdown/didact-demo.didact.md'); const testMD3 = vscode.Uri.parse('vscode://redhat.vscode-didact?extension=demos/markdown/validation-test.didact.md'); const testMD4 = vscode.Uri.parse('vscode://redhat.vscode-didact?commandId=vscode.didact.registry.addUri&&https=raw.githubusercontent.com/redhat-developer/vscode-didact/0.4.0/examples/requirements.example.didact.md&&name=Requirements%20Example&&category=Test%20From%20The%20Web'); const testMD5 = vscode.Uri.parse('vscode://redhat.vscode-didact?https=raw.githubusercontent.com/redhat-developer/vscode-didact/0.4.0/examples/terminal.example.didact.md'); const testExt = 'didact://?commandId=vscode.didact.extensionRequirementCheck&text=some-field-to-update$$redhat.vscode-didact'; const testReq = 'didact://?commandId=vscode.didact.requirementCheck&text=uname-requirements-status$$uname$$Linux'; const testReqMac = 'didact://?commandId=vscode.didact.requirementCheck&text=uname-requirements-status$$uname$$Darwin'; const testReqWin = 'didact://?commandId=vscode.didact.requirementCheck&text=echo-requirements-status$$echo%20test$$test'; const testReqCli = 'didact://?commandId=vscode.didact.cliCommandSuccessful&text=echo-cli-return-status$$echo%20test'; const testWS = 'didact://?commandId=vscode.didact.workspaceFolderExistsCheck&text=workspace-folder-status'; const testScaffold = 'didact://?commandId=vscode.didact.scaffoldProject&extFilePath=redhat.vscode-didact/demos/projectwithdidactfile.json'; const testScaffoldOpen = 'didact://?commandId=vscode.didact.scaffoldProject&extFilePath=redhat.vscode-didact/src/test/data/scaffoldOpen.json'; const OS_WINDOWS = "win32"; const OS_LINUX = "linux"; const OS_MACOS = "darwin"; suite('Didact test suite', () => { const extensionId = 'redhat.vscode-didact'; const testWorkspace = path.resolve(__dirname, '..', '..', '..', './test Fixture with speci@l chars'); const foldersAndFilesToRemove: string[] = [ 'anotherProject', 'root', ]; after( async () => { await removeFilesAndFolders(testWorkspace, foldersAndFilesToRemove); }); beforeEach( async () => { await removeFilesAndFolders(testWorkspace, foldersAndFilesToRemove); }); before(async () => { assert.ok(vscode.extensions.getExtension(extensionId)); vscode.window.showInformationMessage('Start all Didact tests.'); const wsCheck : boolean = await extensionFunctions.validWorkspaceCheck('undefined'); console.log('Workspace has a root folder: ' + wsCheck); console.log(`Test workspace: ' + "${testWorkspace}"`); console.log('Test workspace exists: ' + fs.existsSync(`"${testWorkspace}"`)); const extensionDevelopmentPath = path.resolve(__dirname, '../../../'); console.log('extensionDevelopmentPath: ' + extensionDevelopmentPath); const extensionTestsPath = path.resolve(__dirname, './index'); console.log('extensionTestsPath: ' + extensionTestsPath); // this should not fail because runTest is passing in a test workspace, but it is if (!wsCheck) { assert.fail('Workspace does not have a root folder'); } }); test('Scaffold new project', async function () { try { await vscode.commands.executeCommand(extensionFunctions.SCAFFOLD_PROJECT_COMMAND).then( () => { const createdGroovyFileInFolderStructure = path.resolve(testWorkspace, './root/src/simple.groovy'); assert.strictEqual(fs.existsSync(createdGroovyFileInFolderStructure), true); }); } catch (error) { assert.fail(error); } }); test('Scaffold new project, test for open: true file', async function () { try { await commandHandler.processInputs(testScaffoldOpen).then( async () => { try { const predicate = () => findEditorForFile('simple.groovy') != undefined; await waitUntil(predicate, { timeout: EDITOR_OPENED_TIMEOUT, intervalBetweenAttempts: 1000 }); } catch (error) { assert.fail(`simple.groovy has not been opened in editor`); } }); } catch (error) { assert.fail(error); } }); test('Scaffold new project, test for standard file (no open)', async function () { await testScaffoldProjectDoesNotOpenFile(`aThirdFile.txt`); }); test('Scaffold new project, test for open: false file', async function () { await testScaffoldProjectDoesNotOpenFile(`anotherFile.txt`); }); test('Scaffold new project with a uri', async function () { await commandHandler.processInputs(testScaffold).then( () => { const createdDidactFileInFolderStructure = path.resolve(testWorkspace, './anotherProject/src/test.didact.md'); assert.strictEqual(fs.existsSync(createdDidactFileInFolderStructure), true); }).catch( (error) => { assert.fail(error); }); }); test('Test the extension checking', async () => { const href = testExt; const parsedUrl = new url(href, true); const query = parsedUrl.query; assert.notStrictEqual(query.commandId, undefined); if (query.commandId) { const commandId = getValue(query.commandId); const output : any[] = []; if (query.text) { const text = getValue(query.text); if (text) { commandHandler.handleText(text, output); } } assert.strictEqual(output.length, 2); // 3 arguments const extAvailable : boolean = await extensionFunctions.extensionCheck(output[0], output[1]); assert.strictEqual(extAvailable, true, `Found command ${commandId} in Didact file but extension test is not found: ${href}`); } }); test('test the command line requirements checking', async () => { const href = testReqCli; const parsedUrl = new url(href, true); const query = parsedUrl.query; assert.notStrictEqual(query.commandId, undefined); if (query.commandId) { const commandId = getValue(query.commandId); const output : any[] = []; if (query.text) { const text = getValue(query.text); if (text) { commandHandler.handleText(text, output); } } assert.strictEqual(output.length, 2); // 2 arguments const reqAvailable : boolean = await extensionFunctions.cliExecutionCheck(output[0], output[1]); assert.strictEqual(reqAvailable, true, `Found command ${commandId} in Didact file but did not receive 0 as return code: ${href}`); } }); test('test the command line requirement return checking', async () => { let href = ''; const osName = process.platform; if (osName.startsWith(OS_WINDOWS)) { href = testReqWin; } else if (osName.startsWith(OS_LINUX)) { href = testReq; } else if (osName.startsWith(OS_MACOS)) { href = testReqMac; } const parsedUrl = new url(href, true); const query = parsedUrl.query; assert.notStrictEqual(query.commandId, undefined); if (query.commandId) { const commandId = getValue(query.commandId); const output : any[] = []; if (query.text) { const text = getValue(query.text); if (text) { commandHandler.handleText(text, output); } } assert.strictEqual(output.length, 3); // 3 arguments const reqAvailable : boolean = await extensionFunctions.requirementCheck(output[0], output[1], output[2]); assert.strictEqual(reqAvailable, true, `Found command ${commandId} in Didact file but requirement test is not found: ${href}`); } }); test('test the workspace checking', async () => { const href = testWS.toString(); const parsedUrl = new url(href, true); const query = parsedUrl.query; assert.notStrictEqual(query.commandId, undefined); if (query.commandId) { const commandId = getValue(query.commandId); const output : any[] = []; if (query.text) { const text = getValue(query.text); if (text) { commandHandler.handleText(text, output); } } assert.strictEqual(output.length, 1); // 1 argument const wsAvailable : boolean = await extensionFunctions.validWorkspaceCheck(output[0]); // assume that we're in valid workspace when this test runs assert.strictEqual(wsAvailable, true, `Found command ${commandId} in Didact file but workspace test failed: ${href}`); } }); test('Walk through the demo didact file to ensure that all commands exist in the VS Code system', async () => { await vscode.commands.executeCommand(extensionFunctions.START_DIDACT_COMMAND, testMD).then( async () => { if (didactManager.active()) { const commands : any[] = extensionFunctions.gatherAllCommandsLinks(); assert.strictEqual(commands && commands.length > 0, true); const isOk = await extensionFunctions.validateDidactCommands(commands); // if we failed the above, we can do a deeper dive to figure out what command is missing if (!isOk) { const vsCommands : string[] = await vscode.commands.getCommands(true); for (const command of commands) { const commandOk = extensionFunctions.validateCommand(command, vsCommands); if (!commandOk) { console.log(`--Missing Command ID ${command}`); } } } assert.strictEqual(isOk, true, `Missing commands in test file.`); } }); }); test('Verify that validation fails when given a negative case', async () => { await vscode.commands.executeCommand(extensionFunctions.START_DIDACT_COMMAND, testMD3); if (didactManager.active()) { const commands : any[] = extensionFunctions.gatherAllCommandsLinks(); assert.strictEqual(commands && commands.length > 0, true); const isOk = await extensionFunctions.validateDidactCommands(commands); assert.strictEqual(isOk, false, `Invalid file should not have passed validation test`); } }); test('Walk through the demo didact file to ensure that we get all the requirements commands successfully', async () => { await vscode.commands.executeCommand(extensionFunctions.START_DIDACT_COMMAND, testMD).then( async () => { if (didactManager.active()) { const hrefs : any[] = extensionFunctions.gatherAllRequirementsLinks(); console.log('Gathered these requirements URIs: ' + hrefs); // currently there are 5 requirements links in the test assert.strictEqual(hrefs && hrefs.length === 5, true); } }); }); test('make sure we can open a didact file from a vscode extension', async () => { const titleToCheck = 'Didact Terminal Commands'; await extensionFunctions.handleVSCodeUri(testMD5); await waitUntil(() => didactManager.active()?.getCurrentTitle() === titleToCheck, { timeout: EDITOR_OPENED_TIMEOUT, intervalBetweenAttempts: 1000 }); expect(didactManager.active()).to.not.be.undefined; expect(didactManager.active()?.getCurrentTitle()).to.equal(titleToCheck); }); test('make sure we can register a didact file from a vscode extension', async () => { const category = "Test From The Web"; const tutorialName = "Requirements Example"; await extensionFunctions.handleVSCodeUri(testMD4); const catNode = didactTutorialsProvider.findCategoryNode(category); expect(catNode).to.not.be.undefined; await revealTreeItem(catNode); const foundTutorial = await didactTutorialsProvider.findTutorialNode(category, tutorialName); expect(foundTutorial).to.not.be.undefined; }); }); async function testScaffoldProjectDoesNotOpenFile(fileName: string) { try { await commandHandler.processInputs(testScaffoldOpen).then(async () => { try { const predicate = () => findEditorForFile('simple.groovy') != undefined; await waitUntil(predicate, { timeout: EDITOR_OPENED_TIMEOUT, intervalBetweenAttempts: 1000 }).then(() => { assert.fail(`${fileName} was found opened in editor when it should not have been`); }); } catch (error) { assert.ok(error); } }); } catch (error) { assert.fail(error); } } function findEditorForFile(filename: string) : vscode.TextEditor | undefined { if (vscode.window.visibleTextEditors && vscode.window.visibleTextEditors.length > 0) { for (let index = 0; index < vscode.window.visibleTextEditors.length; index++) { const textEditor = vscode.window.visibleTextEditors[index]; if (textEditor?.document?.fileName.endsWith(`${filename}`)){ return textEditor; } } } return undefined; }
the_stack
export function getColumn(matrix: any[][], column: number): any[] { if (!matrix || matrix.length == 0) { return undefined; } if (column < 0) { return undefined; } if (matrix[0].length <= column) { return undefined; } return matrix.map(row => row[column]); } export function getRow(matrix: any[][], row: number): any[] { if (!matrix || matrix.length == 0) { return undefined; } if (row < 0) { return undefined; } return matrix[row] ? matrix[row].concat() : undefined; } export function distinct(list: any[]): any[] { return list ? list.filter((item, index) => index === list.indexOf(item)) : list; } export type Grouped = { _$groupItems: any[], [group: string]: any[][] }; export function group(matrix: any[][], groupBy: number): Grouped { const grouped: Grouped = {_$groupItems: []}; const index = distinct(getColumn(matrix, groupBy)); if (!index) { return undefined; } grouped._$groupItems = index; index.forEach(group => { grouped[group] = matrix.filter(row => row[groupBy] == group); }); return grouped; } export function flat(group: Grouped): string[][] { const result: string[][] = []; group._$groupItems.forEach(item => { result.push(...group[item]); }); return result; } export type ReduceFunction = (previousValue?: number, currentValue?: number, currentIndex?: number, array?: number[]) => number; export type AggregateAlgorithm = 'sum' | 'average' | 'max' | 'min' | 'head' | 'tail' | ReduceFunction; function aggregateAlgorithms2Function(algorithm: AggregateAlgorithm): [ReduceFunction, number] { let func: ReduceFunction, initialValue = 0; if (algorithm == 'sum') { func = (previous, current) => previous + parseFloat(String(current)); } else if (algorithm == 'average') { func = (previous, current, index, array) => parseFloat((previous + parseFloat(String(current)) / array.length).toFixed(2)); } else if (algorithm == 'max') { func = (previous, current) => Math.max(previous, parseFloat(String(current))); } else if (algorithm == 'min') { func = (previous, current) => Math.min(previous, parseFloat(String(current))); initialValue = Infinity; } else if (algorithm == 'head') { func = (previous, current, index, array) => array[0]; } else if (algorithm == 'tail') { func = (previous, current, index, array) => array[array.length - 1]; } else if (typeof algorithm === 'function') { func = algorithm; } else { throw new Error('unsupported aggregate algorithm: ' + algorithm); } return [func, initialValue]; } export function aggregate(matrix: string[][], by: { index: number, algorithm: AggregateAlgorithm }[]): string[] { if (!matrix || matrix.length == 0 || !by) { return []; } by = by.filter(b => b.index != -1); if (by.length == 0) { return []; } const result: string[] = matrix[0].concat(); by.forEach(item => { const [func, initial] = aggregateAlgorithms2Function(item.algorithm); result[item.index] = getColumn(matrix, item.index).reduce(func, initial); }); return result; } /** * we have to implement the `Array<T>` interface due to this breaking change: * <https://github.com/Microsoft/TypeScript/wiki/FAQ#why-doesnt-extending-built-ins-like-error-array-and-map-work> * <https://github.com/Microsoft/TypeScript/issues/14869> */ export class JigsawArray<T> implements Array<T> { private _agent: T[] = []; /** * 将位置`index`处的数据更新为`value`。`JigsawArray`不支持采用方括号表达式设置一个值,因此必须通过这个方法来替代。 * * ``` * const a = new ArrayCollection<any>(); * a[0] = 123; // compile error! * a.set(0, 123); // everything is fine. * ``` * * @param index * @param value */ public set(index: number, value: T): void { this._length = this._length > index ? this._length : index + 1; const thiz: any = this; thiz[index] = value; } /** * 获取`index`位置处的数据,和数组的方括号表达式的作用一样。 * * ``` * const a = new ArrayCollection<any>([{}]); * a.get(0) === a[0] // true * ``` * * @param index */ public get(index: number): T { return this[index]; } private _length: number = 0; /** * 参考这里 <https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/length> * */ public get length(): number { return this._length; } public set length(value: number) { this._length = value; } readonly [n: number]: T; /** * 参考这里 <https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/includes> * * @param searchElement * @param fromIndex */ public includes(searchElement: T, fromIndex?: number): boolean { return this._agent.includes.apply(this, arguments); } /** * 参考这里 <https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/toString> * */ public toString(): string { return this._agent.toString.apply(this, arguments); } /** * 参考这里 <https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/toLocaleString> * */ public toLocaleString(): string { return this._agent.toLocaleString.apply(this, arguments); } /** * 参考这里 <https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/push> * @param items */ public push(...items: T[]): number { return this._agent.push.apply(this, arguments); } /** * 参考这里 <https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/pop> * */ public pop(): T { return this._agent.pop.apply(this, arguments); } /** * 参考这里 <https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/concat> * @param items * */ public concat(...items: any[]): any { return this._agent.concat.apply(this, arguments); } /** * 参考这里 <https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/join> * @param separator */ public join(separator?: string): string { return this._agent.join.apply(this, arguments); } /** * 参考这里 <https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse> * */ public reverse(): T[] { return this._agent.reverse.apply(this, arguments); } /** * 参考这里 <https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/shift> * */ public shift(): T { return this._agent.shift.apply(this, arguments); } /** * 参考这里 <https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/slice> * @param start * @param end */ public slice(start?: number, end?: number): T[] { return this._agent.slice.apply(this, arguments); } /** * 参考这里 <https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/sort> * @param compareFn */ public sort(compareFn?: (a: T, b: T) => number): any { return this._agent.sort.apply(this, arguments); } /** * 参考这里 <https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/splice> * @param start * @param deleteCount * @param rest * */ public splice(start: any, deleteCount?: any, ...rest: any[]): T[] { return this._agent.splice.apply(this, arguments); } /** * 参考这里 <https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift> * @param items * */ public unshift(...items: T[]): number { return this._agent.unshift.apply(this, arguments); } /** * 参考这里 <https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf> * @param searchElement * @param fromIndex * */ public indexOf(searchElement: T, fromIndex?: number): number { return this._agent.indexOf.apply(this, arguments); } /** * 参考这里 <https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf> * @param searchElement * @param fromIndex * */ public lastIndexOf(searchElement: T, fromIndex?: number): number { return this._agent.lastIndexOf.apply(this, arguments); } /** * 参考这里 <https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/every> * @param callbackfn * @param thisArg * */ public every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean { return this._agent.every.apply(this, arguments); } /** * 参考这里 <https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/some> * @param callbackfn * @param thisArg * */ public some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean { return this._agent.some.apply(this, arguments); } /** * 参考这里 <https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach> * @param callbackfn * @param thisArg */ public forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void { return this._agent.forEach.apply(this, arguments); } /** * 参考这里 <https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/map> * @param callbackfn * @param thisArg * */ public map(callbackfn: any, thisArg?: any): [any, any, any, any, any] { return this._agent.map.apply(this, arguments); } /** * 参考这里 <https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/filter> * @param callback * @param thisArg * */ public filter(callback: (value: T, index: number, array: T[]) => any, thisArg?: any): T[] { return this._agent.filter.apply(this, arguments); } /** * 参考这里 <https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce> * @param callbackfn * @param initialValue * */ public reduce(callbackfn: any, initialValue?: any): T { return this._agent.reduce.apply(this, arguments); } /** * 参考这里 <https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight> * @param callbackfn * @param initialValue * */ public reduceRight(callbackfn: any, initialValue?: any): T { return this._agent.reduceRight.apply(this, arguments); } /** * @internal */ [Symbol.unscopables](): { copyWithin: boolean; entries: boolean; fill: boolean; find: boolean; findIndex: boolean; keys: boolean; values: boolean; } { const iterator = this._agent[Symbol.unscopables]; return iterator.apply(this); } /** * @internal */ [Symbol.iterator](): IterableIterator<T> { const iterator = this._agent[Symbol.iterator]; return iterator.apply(this); } /** * 参考这里 <https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/entries> * */ public entries(): IterableIterator<[number, T]> { return this._agent.entries.apply(this, arguments); } /** * 参考这里 <https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/keys> * */ public keys(): IterableIterator<number> { return this._agent.keys.apply(this, arguments); } /** * 参考这里 <https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/values> * */ public values(): IterableIterator<T> { return this._agent.values.apply(this, arguments); } /** * 参考这里 <https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/find> * @param predicate * @param thisArg * */ public find(predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): T { return this._agent.find.apply(this, arguments); } /** * 参考这里 <https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex> * @param predicate * @param thisArg * */ public findIndex(predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): number { return this._agent.findIndex.apply(this, arguments); } /** * 参考这里 <https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/fill> * @param value * @param start * @param end * */ public fill(value: T, start?: number, end?: number): any { return this._agent.fill.apply(this, arguments); } /** * 参考这里 <https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin> * @param target * @param start * @param end * */ public copyWithin(target: number, start: number, end?: number): any { return this._agent.copyWithin.apply(this, arguments); } }
the_stack
import BN from 'bn.js' import { toWei } from 'web3-utils' import { IChainlinkOracleInstance, IQuoterInstance, PermitERC20UniswapV3PaymasterInstance, PermitInterfaceDAIInstance, PermitInterfaceEIP2612Instance, SampleRecipientInstance, TestHubInstance } from '../types/truffle-contracts' import { RelayRequest } from '@opengsn/common/dist/EIP712/RelayRequest' import { constants } from '@opengsn/common' import { calculatePostGas, deployTestHub, mergeRelayRequest, revertReason } from './TestUtils' import { CHAINLINK_USD_ETH_FEED_CONTRACT_ADDRESS, DAI_CONTRACT_ADDRESS, GSN_FORWARDER_CONTRACT_ADDRESS, PERMIT_SIGNATURE_DAI, PERMIT_SIGNATURE_EIP2612, CHAINLINK_UNI_ETH_FEED_CONTRACT_ADDRESS, SWAP_ROUTER_CONTRACT_ADDRESS, UNISWAP_V3_DAI_WETH_POOL_CONTRACT_ADDRESS, UNISWAP_V3_QUOTER_CONTRACT_ADDRESS, UNI_CONTRACT_ADDRESS, WETH9_CONTRACT_ADDRESS, getDaiDomainSeparator, getUniDomainSeparator, signAndEncodeDaiPermit, signAndEncodeEIP2612Permit } from '../src/PermitPaymasterUtils' import { revert, snapshot } from '@opengsn/dev/dist/test/TestUtils' import { expectEvent } from '@openzeppelin/test-helpers' import { EIP712DomainTypeWithoutVersion } from '@opengsn/common/dist/EIP712/TypedRequestData' const PermitERC20UniswapV3Paymaster = artifacts.require('PermitERC20UniswapV3Paymaster') const PermitInterfaceEIP2612 = artifacts.require('PermitInterfaceEIP2612') const PermitInterfaceDAI = artifacts.require('PermitInterfaceDAI') const IChainlinkOracle = artifacts.require('IChainlinkOracle') const SampleRecipient = artifacts.require('SampleRecipient') const IQuoter = artifacts.require('IQuoter') // as we are using forked mainnet, we will need to impersonate an account with a lot of DAI & UNI const MAJOR_DAI_AND_UNI_HOLDER = '0x47ac0fb4f2d84898e4d9e7b4dab3c24507a6d503' const GAS_USED_BY_POST = 204766 const MAX_POSSIBLE_GAS = 1e6 const PERMIT_DATA_LENGTH = 0 const POOL_FEE = 3000 const TOKEN_PRE_CHARGE = toWei('10', 'ether') const GAS_PRICE = '1000000000' // 1 wei async function detectMainnet (): Promise<boolean> { const code = await web3.eth.getCode(DAI_CONTRACT_ADDRESS) return code !== '0x' } async function skipWithoutFork (test: any): Promise<void> { const isMainnet = await detectMainnet() if (!isMainnet) { test.skip() } } contract('PermitERC20UniswapV3Paymaster', function ([account0, account1, relay]) { let permitPaymaster: PermitERC20UniswapV3PaymasterInstance let daiPermittableToken: PermitInterfaceDAIInstance let chainlinkOracle: IChainlinkOracleInstance let sampleRecipient: SampleRecipientInstance let testRelayHub: TestHubInstance let quoter: IQuoterInstance let relayRequest: RelayRequest let id: string before(async function () { if (!await detectMainnet()) { this.skip() } sampleRecipient = await SampleRecipient.new() await sampleRecipient.setForwarder(GSN_FORWARDER_CONTRACT_ADDRESS) quoter = await IQuoter.at(UNISWAP_V3_QUOTER_CONTRACT_ADDRESS) daiPermittableToken = await PermitInterfaceDAI.at(DAI_CONTRACT_ADDRESS) chainlinkOracle = await IChainlinkOracle.at(CHAINLINK_USD_ETH_FEED_CONTRACT_ADDRESS) testRelayHub = await deployTestHub() as TestHubInstance // in case the MAJOR_DAI_AND_UNI_HOLDER account does not have ETH on actual mainnet await web3.eth.sendTransaction({ from: account0, to: MAJOR_DAI_AND_UNI_HOLDER, value: 1e18 }) // we cannot sign on behalf of an impersonated account - transfer DAI to an account we control await daiPermittableToken.transfer(account0, toWei('100000', 'ether'), { from: MAJOR_DAI_AND_UNI_HOLDER }) permitPaymaster = await PermitERC20UniswapV3Paymaster.new( WETH9_CONTRACT_ADDRESS, DAI_CONTRACT_ADDRESS, testRelayHub.address, SWAP_ROUTER_CONTRACT_ADDRESS, CHAINLINK_USD_ETH_FEED_CONTRACT_ADDRESS, GSN_FORWARDER_CONTRACT_ADDRESS, POOL_FEE, GAS_USED_BY_POST, PERMIT_DATA_LENGTH, PERMIT_SIGNATURE_DAI ) relayRequest = { relayData: { relayWorker: relay, paymaster: permitPaymaster.address, forwarder: GSN_FORWARDER_CONTRACT_ADDRESS, pctRelayFee: '0', baseRelayFee: '0', transactionCalldataGasUsed: '0', maxFeePerGas: GAS_PRICE, maxPriorityFeePerGas: GAS_PRICE, paymasterData: '0x', clientId: '1' }, request: { data: sampleRecipient.contract.methods.something().encodeABI(), nonce: '0', value: '0', validUntilTime: '0', from: account0, to: sampleRecipient.address, gas: 1e6.toString() } } }) beforeEach(async function () { id = (await snapshot()).result }) afterEach(async function () { await revert(id) }) context('#preRelayedCall', function () { context('revert reasons', function () { it('should revert if approval data is provided', async function () { await skipWithoutFork(this) assert.match( await revertReason( testRelayHub.callPreRC( relayRequest, '0x', '0x123', MAX_POSSIBLE_GAS ) ), /approvalData: invalid length/) }) it('should revert if paymasterData is too short', async function () { await skipWithoutFork(this) const modifiedRequest = mergeRelayRequest(relayRequest, { paymasterData: '0x1234' }) assert.match( await revertReason( testRelayHub.callPreRC( modifiedRequest, '0x', '0x', MAX_POSSIBLE_GAS ) ), /paymastaData: missing method sig/) }) it('should revert if paymasterData is not an encoded call to permit method', async function () { await skipWithoutFork(this) const modifiedRequest = mergeRelayRequest(relayRequest, { paymasterData: '0x123456789' }) assert.match( await revertReason( testRelayHub.callPreRC( modifiedRequest, '0x', '0x', MAX_POSSIBLE_GAS ) ), /paymasterData: wrong method sig/) }) it('should revert if permit call reverts', async function () { await skipWithoutFork(this) const incorrectNonce = 777 const domainSeparator = getDaiDomainSeparator() const encodedCallToPermit = await signAndEncodeDaiPermit( account0, permitPaymaster.address, daiPermittableToken.address, constants.MAX_UINT256.toString(), web3, domainSeparator, incorrectNonce, true ) const modifiedRequest = mergeRelayRequest(relayRequest, { paymasterData: encodedCallToPermit }) assert.match( await revertReason( testRelayHub.callPreRC( modifiedRequest, '0x', '0x', MAX_POSSIBLE_GAS ) ), /permit call reverted:/) }) it('should revert if token transferFrom reverts', async function () { await skipWithoutFork(this) await daiPermittableToken.approve(permitPaymaster.address, constants.MAX_UINT256, { from: account1 }) const modifiedRequest = mergeRelayRequest(relayRequest, {}, { from: account1 }) const balance = await daiPermittableToken.balanceOf(account1) assert.equal(balance.toString(), '0') assert.match( await revertReason( testRelayHub.callPreRC( modifiedRequest, '0x', '0x', MAX_POSSIBLE_GAS ) ), /Dai\/insufficient-balance/) }) }) context('with paymasterData', function () { it('should execute permit method on a target DAI token', async function () { await skipWithoutFork(this) const approvalBefore = await daiPermittableToken.allowance(account0, permitPaymaster.address) assert.equal(approvalBefore.toString(), '0', 'unexpected approval') const accountBalanceBefore = await daiPermittableToken.balanceOf(account0) const spenderBalanceBefore = await daiPermittableToken.balanceOf(permitPaymaster.address) assert.equal(spenderBalanceBefore.toString(), '0', 'unexpected balance') const encodedCallToPermit = await signAndEncodeDaiPermit( account0, permitPaymaster.address, daiPermittableToken.address, constants.MAX_UINT256.toString(), web3 ) const modifiedRequest = mergeRelayRequest(relayRequest, { paymasterData: encodedCallToPermit }) await testRelayHub.callPreRC( modifiedRequest, '0x', '0x', MAX_POSSIBLE_GAS ) const paymasterBalanceAfter = await daiPermittableToken.balanceOf(permitPaymaster.address) // it is dependant on actual cost of ether on uniswap, but pre-charge below 10¢ will be unfortunate assert.isAbove(parseInt(paymasterBalanceAfter.toString()), 1e17, 'unexpected balance (real-world price dependant)') const accountBalanceAfter = await daiPermittableToken.balanceOf(account0) const accountDifference = accountBalanceBefore.sub(accountBalanceAfter) // must have charged from this account assert.equal(accountDifference.toString(), paymasterBalanceAfter.toString(), 'unexpected balance') const latestAnswer = await chainlinkOracle.latestAnswer() const maxPossibleEth = await testRelayHub.calculateCharge(MAX_POSSIBLE_GAS, relayRequest.relayData) const expectedCharge = latestAnswer.mul(maxPossibleEth).div(new BN(1e8.toString())) assert.equal(accountDifference.toString(), paymasterBalanceAfter.toString(), 'unexpected balance') assert.equal(accountDifference.toString(), expectedCharge.toString(), 'unexpected charge') const approvalAfter = await daiPermittableToken.allowance(account0, permitPaymaster.address) assert.equal(approvalAfter.toString(), constants.MAX_UINT256.toString(), 'insufficient approval') }) context('with EIP2612-compatible Paymaster', function () { let eip2612PermittableToken: PermitInterfaceEIP2612Instance let permitEIP2612Paymaster: PermitERC20UniswapV3PaymasterInstance before(async function () { if (!await detectMainnet()) { this.skip() } eip2612PermittableToken = await PermitInterfaceEIP2612.at(UNI_CONTRACT_ADDRESS) await eip2612PermittableToken.transfer(account0, toWei('100000', 'ether'), { from: MAJOR_DAI_AND_UNI_HOLDER }) permitEIP2612Paymaster = await PermitERC20UniswapV3Paymaster.new( WETH9_CONTRACT_ADDRESS, UNI_CONTRACT_ADDRESS, testRelayHub.address, SWAP_ROUTER_CONTRACT_ADDRESS, CHAINLINK_UNI_ETH_FEED_CONTRACT_ADDRESS, GSN_FORWARDER_CONTRACT_ADDRESS, POOL_FEE, GAS_USED_BY_POST, PERMIT_DATA_LENGTH, PERMIT_SIGNATURE_EIP2612 ) }) it('should execute permit method on a target EIP2612 token', async function () { await skipWithoutFork(this) const approvalBefore = await eip2612PermittableToken.allowance(account0, permitPaymaster.address) assert.equal(approvalBefore.toString(), '0', 'unexpected approval') const encodedCallToPermit = await signAndEncodeEIP2612Permit( account0, permitEIP2612Paymaster.address, eip2612PermittableToken.address, constants.MAX_UINT256.toString(), constants.MAX_UINT256.toString(), web3, getUniDomainSeparator(), EIP712DomainTypeWithoutVersion ) const modifiedRequest = mergeRelayRequest(relayRequest, { paymaster: permitEIP2612Paymaster.address, paymasterData: encodedCallToPermit }) await testRelayHub.callPreRC( modifiedRequest, '0x', '0x', MAX_POSSIBLE_GAS ) // note that Uni allowance is stored as uint96 const approvalAfter = await eip2612PermittableToken.allowance(account0, permitEIP2612Paymaster.address) assert.equal(approvalAfter.toString(), constants.MAX_UINT96.toString(), 'insufficient approval') }) }) }) }) context('#postRelayedCall', function () { context('revert reasons', function () { it('should revert if actual charge exceeds pre-charge (i.e. bug in RelayHub)', async function () { await skipWithoutFork(this) const gasUseWithoutPost = 1000000 const context = web3.eth.abi.encodeParameters(['address', 'uint256'], [account0, TOKEN_PRE_CHARGE]) // "STF" revert reason is thrown in 'safeTransferFrom' method in Uniswap's 'TransferHelper.sol' library assert.match( await revertReason( testRelayHub.callPostRC(permitPaymaster.address, context, gasUseWithoutPost, relayRequest.relayData) ), /STF/) }) }) context('success flow', function () { before(async function () { if (!await detectMainnet()) { this.skip() } await daiPermittableToken.approve(permitPaymaster.address, constants.MAX_UINT256, { from: account0 }) await daiPermittableToken.transfer(permitPaymaster.address, TOKEN_PRE_CHARGE, { from: account0 }) }) it('should transfer excess tokens back to sender and deposit traded tokens into RelayHub as Ether', async function () { await skipWithoutFork(this) const gasUseWithoutPost = 100000 const context = web3.eth.abi.encodeParameters(['address', 'uint256'], [account0, TOKEN_PRE_CHARGE]) const ethActualCharge = (gasUseWithoutPost + GAS_USED_BY_POST) * parseInt(GAS_PRICE) const expectedDaiTokenCharge = await quoter.contract.methods.quoteExactOutputSingle( DAI_CONTRACT_ADDRESS, WETH9_CONTRACT_ADDRESS, POOL_FEE, ethActualCharge, 0).call() const res = await testRelayHub.callPostRC(permitPaymaster.address, context, gasUseWithoutPost, relayRequest.relayData) const expectedRefund = new BN(TOKEN_PRE_CHARGE).sub(new BN(expectedDaiTokenCharge)) // check correct tokens are transferred assert.equal(res.logs[0].address.toLowerCase(), WETH9_CONTRACT_ADDRESS.toLowerCase()) assert.equal(res.logs[1].address.toLowerCase(), DAI_CONTRACT_ADDRESS.toLowerCase()) assert.equal(res.logs[6].address.toLowerCase(), DAI_CONTRACT_ADDRESS.toLowerCase()) // swap(0): transfer WETH from Pool to Router expectEvent(res, 'Transfer', { from: UNISWAP_V3_DAI_WETH_POOL_CONTRACT_ADDRESS, to: SWAP_ROUTER_CONTRACT_ADDRESS, value: ethActualCharge.toString() }) // swap(1): transfer DAI from Paymaster to Pool expectEvent(res, 'Transfer', { from: permitPaymaster.address, to: UNISWAP_V3_DAI_WETH_POOL_CONTRACT_ADDRESS, value: expectedDaiTokenCharge.toString() }) // swap(2): execute swap; note that WETH remains in a SwapRouter so it unwraps it for us expectEvent(res, 'Swap', { sender: SWAP_ROUTER_CONTRACT_ADDRESS, recipient: SWAP_ROUTER_CONTRACT_ADDRESS }) // swap(3): SwapRouter unwraps ETH and sends it into Paymaster expectEvent(res, 'Withdrawal', { src: SWAP_ROUTER_CONTRACT_ADDRESS, wad: ethActualCharge.toString() }) // swap(4): Paymaster receives ETH expectEvent(res, 'Received', { sender: SWAP_ROUTER_CONTRACT_ADDRESS, eth: ethActualCharge.toString() }) // swap(5): Paymaster deposits all ETH to RelayHub expectEvent(res, 'Deposited', { from: permitPaymaster.address, paymaster: permitPaymaster.address, amount: ethActualCharge.toString() }) // swap(6): Paymaster refunds remaining DAI tokens to sender expectEvent(res, 'Transfer', { from: permitPaymaster.address, to: account0, value: expectedRefund.toString() }) expectEvent(res, 'TokensCharged') }) }) }) context('#transferToken', function () { it('should revert if called not from the trusted forwarder', async function () { await skipWithoutFork(this) }) it('should transfer tokens from sender to recipient', async function () { await skipWithoutFork(this) }) }) context('calculate postRelayCall gas usage', function () { it('calculate', async function () { await skipWithoutFork(this) const permitPaymasterZeroGUBP = await PermitERC20UniswapV3Paymaster.new( WETH9_CONTRACT_ADDRESS, DAI_CONTRACT_ADDRESS, testRelayHub.address, SWAP_ROUTER_CONTRACT_ADDRESS, CHAINLINK_USD_ETH_FEED_CONTRACT_ADDRESS, GSN_FORWARDER_CONTRACT_ADDRESS, POOL_FEE, 0, // do not set 'gasUsedByPost' PERMIT_DATA_LENGTH, PERMIT_SIGNATURE_DAI ) const context = web3.eth.abi.encodeParameters(['address', 'uint256'], [account0, 500]) const postGasUse = await calculatePostGas(daiPermittableToken, permitPaymasterZeroGUBP, account0, context) assert.closeTo(postGasUse.toNumber(), GAS_USED_BY_POST, 5000) }) }) })
the_stack
import * as $ from "../libs/jquery-shim"; import { IDotnetifyImpl } from "./dotnetify"; import { IDotnetifyVM, IConnectOptions, IDotnetifyHub, ExceptionHandlerType, RouteType, OnRouteEnterType } from "../_typings"; // Client-side view model that acts as a proxy of the server view model. export default class DotnetifyVM implements IDotnetifyVM { $vmId: string; $component: any; $options: IConnectOptions; $dotnetify: IDotnetifyImpl; $hub: IDotnetifyHub; $vmArg: any; $headers: any; $requested: boolean; $loaded: boolean; $itemKey: { [key: string]: string }; $serverUpdate: boolean; $exceptionHandler: ExceptionHandlerType; State: (state?: any) => void | any; Props: (prop: any) => any; $routeTo: (route: RouteType) => void; onRouteEnter: OnRouteEnterType = () => true; // iVMId - identifies the view model. // iComponent - component object. // iOptions - Optional configuration options: // getState: state accessor. // setState: state mutator. // vmArg: view model arguments. // headers: request headers, for things like authentication token. // exceptionHandler: called when receiving server-side exception. // iDotNetify - framework-specific dotNetify library. // iHub - hub connection. constructor( iVMId: string, iComponent: any, iOptions: IConnectOptions, iDotNetify: IDotnetifyImpl, iHub: IDotnetifyHub ) { this.$vmId = iVMId; this.$component = iComponent; this.$options = iOptions || {}; this.$vmArg = iOptions && iOptions["vmArg"]; this.$headers = iOptions && iOptions["headers"]; this.$exceptionHandler = iOptions && iOptions["exceptionHandler"]; this.$requested = false; this.$loaded = false; this.$itemKey = {}; this.$dotnetify = iDotNetify; this.$hub = iHub; let getState = iOptions && iOptions["getState"]; let setState = iOptions && iOptions["setState"]; getState = typeof getState === "function" ? getState : () => iComponent.state; setState = typeof setState === "function" ? setState : state => iComponent.setState(state); this.State = state => typeof state === "undefined" ? getState() : setState(state); this.Props = prop => this.$component.props && this.$component.props[prop]; const vmArg = this.Props("vmArg"); if (vmArg) this.$vmArg = $.extend(this.$vmArg, vmArg); // Inject plugin functions into this view model. this.$getPlugins().map(plugin => typeof plugin["$inject"] == "function" ? plugin.$inject(this) : null ); } // Disposes the view model, both here and on the server. $destroy() { // Call any plugin's $destroy function if provided. this.$getPlugins().map(plugin => typeof plugin["$destroy"] == "function" ? plugin.$destroy.apply(this) : null ); if (this.$hub.isConnected) { try { this.$hub.disposeVM(this.$vmId); } catch (ex) { this.$dotnetify.controller.handleConnectionStateChanged( "error", ex, this.$hub ); } } delete (<any>this.$dotnetify).viewModels[this.$vmId]; } // Dispatches a value to the server view model. // iValue - Value to dispatch. $dispatch(iValue: any) { if (this.$hub && this.$hub.isConnected) { const controller = this.$dotnetify.controller; try { this.$hub.updateVM(this.$vmId, iValue); if (controller.debug) { console.log("[" + this.$vmId + "] sent> "); console.log(iValue); controller.debugFn && controller.debugFn(this.$vmId, "sent", iValue); } } catch (ex) { controller.handleConnectionStateChanged("error", ex, this.$hub); } } } // Dispatches a state value to the server view model. // iValue - State value to dispatch. $dispatchListState(iValue: any) { for (const listName in iValue) { const key = this.$itemKey[listName]; if (!key) { console.error( `[${this.$vmId}] missing item key for '${listName}'; decorate '${listName}' with an [ItemKey] attribute.` ); return; } const item = iValue[listName]; if (!item[key]) { console.error( `[${this.$vmId}] couldn't dispatch data from '${listName}' due to missing property '${key}'.` ); console.error(item); return; } Object.keys(item).forEach(prop => { if (prop != key) { let state = {}; state[listName + ".$" + item[key] + "." + prop] = item[prop]; this.$dispatch(state); } }); this.$updateList(listName, item); } } $getPlugins() { return Object.keys(this.$dotnetify.plugins).map( id => this.$dotnetify.plugins[id] ); } // Preprocess view model update from the server before we set the state. $preProcess(iVMUpdate) { const vm = this; for (var prop in iVMUpdate) { // Look for property that end with '_add'. Interpret the value as a list item to be added // to an existing list whose property name precedes that suffix. var match = /(.*)_add/.exec(prop); if (match != null) { var listName = match[1]; if (Array.isArray(this.State()[listName])) vm.$addList(listName, iVMUpdate[prop]); else console.error("unable to resolve " + prop); delete iVMUpdate[prop]; continue; } // Look for property that end with '_update'. Interpret the value as a list item to be updated // to an existing list whose property name precedes that suffix. var match = /(.*)_update/.exec(prop); if (match != null) { var listName = match[1]; if (Array.isArray(this.State()[listName])) vm.$updateList(listName, iVMUpdate[prop]); else console.error( "[" + this.$vmId + "] '" + listName + "' is not found or not an array." ); delete iVMUpdate[prop]; continue; } // Look for property that end with '_remove'. Interpret the value as a list item key to remove // from an existing list whose property name precedes that suffix. var match = /(.*)_remove/.exec(prop); if (match != null) { var listName = match[1]; if (Array.isArray(this.State()[listName])) { var key = this.$itemKey[listName]; if (key != null) { if (Array.isArray(iVMUpdate[prop])) vm.$removeList(listName, i => iVMUpdate[prop].some(x => i[key] == x) ); else vm.$removeList(listName, i => i[key] == iVMUpdate[prop]); } else console.error( `[${this.$vmId}] missing item key for '${listName}'; decorate '${listName}' with an [ItemKey] attribute.` ); } else console.error( `[${this.$vmId}] '${listName}' is not found or not an array.` ); delete iVMUpdate[prop]; continue; } // Look for property that end with '_itemKey'. Interpret the value as the property name that will // uniquely identify items in the list. var match = /(.*)_itemKey/.exec(prop); if (match != null) { var listName = match[1]; var itemKey = {}; itemKey[listName] = iVMUpdate[prop]; vm.$setItemKey(itemKey); delete iVMUpdate[prop]; continue; } } } // Requests state from the server view model. $request() { if (this.$hub.isConnected) this.$hub.requestVM(this.$vmId, { $vmArg: this.$vmArg, $headers: this.$headers }); this.$requested = true; } // Updates state from the server view model to the view. // iVMData - Serialized state from the server. $update(iVMData: any) { const controller = this.$dotnetify.controller; if (controller.debug) { console.log("[" + this.$vmId + "] received> "); console.log(JSON.parse(iVMData)); controller.debugFn && controller.debugFn(this.$vmId, "received", JSON.parse(iVMData)); } let vmData = JSON.parse(iVMData); this.$preProcess(vmData); let state = this.State(); state = $.extend({}, state, vmData); this.State(state); if (!this.$loaded) this.$onLoad(); else this.$onUpdate(vmData); } // Handles initial view model load event. $onLoad() { this.$getPlugins().map(plugin => typeof plugin["$ready"] == "function" ? plugin.$ready.apply(this) : null ); this.$loaded = true; } // Handles view model update event. $onUpdate(vmData) { this.$getPlugins().map(plugin => typeof plugin["$update"] == "function" ? plugin.$update.apply(this, [vmData]) : null ); } // *** CRUD Functions *** // Sets items key to identify individual items in a list. // Accepts object literal: { "<list name>": "<key prop name>", ... } $setItemKey(iItemKey) { Object.assign(this.$itemKey, iItemKey); } //// Adds a new item to a state array. $addList(iListName, iNewItem) { let items = this.State()[iListName]; if (Array.isArray(iNewItem) && !Array.isArray(items[0] || [])) { iNewItem.forEach(item => this.$addList(iListName, item)); return; } // Check if the list already has an item with the same key. If so, replace it. var key = this.$itemKey[iListName]; if (key != null) { if (!iNewItem.hasOwnProperty(key)) { console.error( `[${this.$vmId}] couldn't add item to '${iListName}' due to missing property '${key}'.` ); return; } var match = this.State()[iListName].filter(function (i) { return i[key] == iNewItem[key]; }); if (match.length > 0) { console.error( `[${this.$vmId}] couldn't add item to '${iListName}' because the key already exists.` ); return; } } items.push(iNewItem); let state = {}; state[iListName] = items; this.State(state); } // Removes an item from a state array. $removeList(iListName, iFilter) { let state = {}; state[iListName] = this.State()[iListName].filter(i => !iFilter(i)); this.State(state); } //// Updates existing item to an observable array. $updateList(iListName, iNewItem) { let items = this.State()[iListName]; if (Array.isArray(iNewItem) && !Array.isArray(items[0] || [])) { iNewItem.forEach(item => this.$updateList(iListName, item)); return; } // Check if the list already has an item with the same key. If so, update it. let key = this.$itemKey[iListName]; if (key != null) { if (!iNewItem.hasOwnProperty(key)) { console.error( `[${this.$vmId}] couldn't update item to '${iListName}' due to missing property '${key}'.` ); return; } var state = {}; state[iListName] = items.map(function (i) { return i[key] == iNewItem[key] ? $.extend(i, iNewItem) : i; }); this.State(state); } else console.error( `[${this.$vmId}] missing item key for '${iListName}'; add '${iListName}_itemKey' property to the view model.` ); } }
the_stack
import { createElement } from '@syncfusion/ej2-base'; import { Chart } from '../../../src/chart/chart'; import { LineSeries } from '../../../src/chart/series/line-series'; import { AreaSeries } from '../../../src/chart/series/area-series'; import { ColumnSeries } from '../../../src/chart/series/column-series'; import { BarSeries } from '../../../src/chart/series/bar-series'; import { Logarithmic } from '../../../src/chart/axis/logarithmic-axis'; import { DateTime } from '../../../src/chart/axis/date-time-axis'; import '../../../node_modules/es6-promise/dist/es6-promise'; import { Series, Points } from '../../../src/chart/series/chart-series'; import { unbindResizeEvents } from '../base/data.spec'; import { seriesData1, datetimeData } from '../base/data.spec'; import { EmitType } from '@syncfusion/ej2-base'; import { ILoadedEventArgs, IAxisLabelRenderEventArgs } from '../../../src/chart/model/chart-interface'; import {profile , inMB, getMemoryProfile} from '../../common.spec'; Chart.Inject(LineSeries, Logarithmic, ColumnSeries, AreaSeries, BarSeries, DateTime); let data: any = seriesData1; let datetime: any = datetimeData; export interface Arg { chart: Chart; } describe('Chart Control', () => { beforeAll(() => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } }); describe('Chart Logarithmic axis', () => { let chartObj: Chart; let elem: HTMLElement; let svg: HTMLElement; let text: HTMLElement; let datalabel: HTMLElement; let loaded: EmitType<ILoadedEventArgs>; beforeAll(() => { elem = createElement('div', { id: 'container' }); document.body.appendChild(elem); chartObj = new Chart( { primaryXAxis: { title: 'PrimaryXAxis', valueType: 'Logarithmic' }, primaryYAxis: { title: 'PrimaryYAxis', rangePadding: 'None' }, series: [{ dataSource: [ { y: 18, x: 1 }, { y: 29, x: 2 }, { y: 30, x: 3 }, { y: 41, x: 4 }, { y: 52, x: 5 }, { y: 62, x: 6 }, { y: 74, x: 7 }, { y: 85, x: 8 }, { y: 96, x: 9 }, { y: 102, x: 10 } ], xName: 'x', yName: 'y', animation: { enable: false }, type: 'Line', name: 'ChartSeriesNameGold', fill: 'green', }, ], width: '800', title: 'Chart TS Title', legendSettings: { visible: false } }); }); afterAll((): void => { elem.remove(); chartObj.destroy(); }); it('Checking with labels for primaryXAxis', (done: Function) => { loaded = (args: Object): void => { svg = document.getElementById("containerAxisLabels0"); expect(svg.childNodes.length == 2).toBe(true); done(); }; chartObj.loaded = loaded; chartObj.appendTo('#container'); }); it('Checking with axis labels for primaryXAxis with logBase 2', (done: Function) => { loaded = (args: Object): void => { svg = document.getElementById('containerAxisLabels0'); expect(svg.childNodes.length === 5).toBe(true); done(); }; chartObj.loaded = loaded; chartObj.primaryXAxis.logBase = 2; chartObj.primaryXAxis.interval = null; chartObj.refresh(); }); it('checking axis labels for primaryXAxis with range', (done: Function) => { loaded = (args: Object): void => { svg = document.getElementById('containerAxisLabels0'); expect(svg.childNodes.length === 6).toBe(true); done(); }; chartObj.loaded = loaded; chartObj.primaryXAxis.minimum = 1; chartObj.primaryXAxis.maximum = 20; chartObj.refresh(); }); it('checking axis labels for primaryXAxis', (done: Function) => { loaded = (args: Object): void => { text = document.getElementById("container0_AxisLabel_0"); expect(text.textContent === "1").toBe(true); text = document.getElementById("container0_AxisLabel_1"); expect(text.textContent === "10").toBe(true); done(); }; chartObj.loaded = loaded; chartObj.primaryXAxis.logBase = 10; chartObj.refresh(); }); it('checking axis labels for primaryXAxis with minorGridLine', (done: Function) => { loaded = (args: Object): void => { svg = document.getElementById("container_MinorGridLine_0_1"); expect(svg.getAttribute("stroke") == "#eaeaea").toBe(true); expect(svg.getAttribute("stroke-width") == "2").toBe(true); done(); }; chartObj.loaded = loaded; chartObj.primaryXAxis.minorGridLines.width = 2; chartObj.primaryXAxis.minorTicksPerInterval = 3; chartObj.refresh(); }); it('Checking axis labels for primaryXAxis with interval', (done: Function) => { loaded = (args: Object): void => { text = document.getElementById("container0_AxisLabel_0"); expect(text.textContent == "1").toBe(true); text = document.getElementById("container0_AxisLabel_1"); expect(text.textContent == "100").toBe(true); done(); }; chartObj.loaded = loaded; chartObj.primaryXAxis.minimum = 1; chartObj.primaryXAxis.interval = 2; chartObj.primaryXAxis.maximum = 20; chartObj.refresh(); }); it('Checking axis labels for primary YAxis', (done: Function) => { loaded = (args: Object): void => { svg = document.getElementById("containerAxisLabels1"); expect(svg.childNodes.length == 3).toBe(true); done(); }; chartObj.loaded = loaded; chartObj.primaryYAxis.valueType = 'Logarithmic'; chartObj.refresh(); }); it('Checking with nagative points', (done: Function) => { loaded = (args: Object): void => { svg = document.getElementById("container1_AxisLabel_0"); expect(svg.textContent === '1').toBe(true); done(); }; chartObj.loaded = loaded; chartObj.series[0].dataSource[0].y = -20; chartObj.refresh(); }); it('checking axis labels for primary YAxis with logBase', (done: Function) => { loaded = (args: Object): void => { svg = document.getElementById('containerAxisLabels1'); expect(svg.childNodes.length === 4).toBe(true); svg = document.getElementById('container_Series_0'); expect(svg !== null).toBe(true); done(); }; chartObj.loaded = loaded; chartObj.primaryYAxis.logBase = 2; chartObj.series[0].dataSource[0].y = 18; chartObj.refresh(); }); it('checking axis labels for primary YAxis with range', (done: Function) => { loaded = (args: Object): void => { text = document.getElementById("container1_AxisLabel_0"); expect(text.textContent == "1").toBe(true); text = document.getElementById("container1_AxisLabel_1"); expect(text.textContent == "2").toBe(true); done(); }; chartObj.loaded = loaded; chartObj.primaryYAxis.minimum = 1; chartObj.primaryYAxis.maximum = 260; chartObj.primaryYAxis.logBase = 2; chartObj.refresh(); }); it('checking axis labels for primary YAxis with label', (done: Function) => { loaded = (args: Object): void => { text = document.getElementById("container1_AxisLabel_0"); expect(text.textContent == "1").toBe(true); text = document.getElementById("container1_AxisLabel_1"); expect(text.textContent == "10").toBe(true); done(); }; chartObj.loaded = loaded; chartObj.primaryYAxis.logBase = 10; chartObj.refresh(); }); it('checking axis labels for primary YAxis with minorGridLine', (done: Function) => { loaded = (args: Object): void => { svg = document.getElementById("container_MinorGridLine_1_1"); expect(svg.getAttribute("stroke") == "#eaeaea").toBe(true); expect(svg.getAttribute("stroke-width") == "2").toBe(true); done(); }; chartObj.loaded = loaded; chartObj.primaryYAxis.minorGridLines.width = 2; chartObj.primaryYAxis.minorTicksPerInterval = 3; chartObj.refresh(); }); it('checking axis labels for primary YAxis with interval', (done: Function) => { loaded = (args: Object): void => { text = document.getElementById("container1_AxisLabel_0"); expect(text.textContent == "1").toBe(true); text = document.getElementById("container1_AxisLabel_1"); expect(text.textContent == "4").toBe(true); done(); }; chartObj.loaded = loaded; chartObj.primaryYAxis.interval = 2; chartObj.primaryYAxis.logBase = 2; chartObj.refresh(); }); it('checking with bar Series', (done: Function) => { loaded = (args: Object): void => { svg = document.getElementById('containerSeriesGroup0'); expect(svg.childElementCount - 1 == 10).toBe(true); done(); }; chartObj.loaded = loaded; chartObj.series[0].type = 'Bar'; chartObj.refresh(); }); it('checking with bar Series with datetime and logarithmic', (done: Function) => { loaded = (args: Arg): void => { svg = document.getElementById('container_Series_0_Point_0'); let value: number = Math.round((<Series>args.chart.series[0]).points[1].regions[0].y); expect(value == 253 || value == 248).toBe(true); done(); }; chartObj.loaded = loaded; chartObj.series[0].type = 'Bar'; chartObj.primaryXAxis.valueType = 'DateTime'; chartObj.primaryXAxis.minimum = null; chartObj.primaryXAxis.interval = null; chartObj.primaryXAxis.maximum = null; chartObj.series[0].dataSource = datetime; chartObj.primaryYAxis.interval = 1; chartObj.primaryYAxis.logBase = 10; chartObj.refresh(); }); it('checking with Column Series', (done: Function) => { loaded = (args: Object): void => { svg = document.getElementById('containerSeriesGroup0'); expect(svg.childElementCount - 1 == 10).toBe(true); done(); }; chartObj.loaded = loaded; chartObj.primaryXAxis.valueType = 'Logarithmic'; chartObj.primaryXAxis.minimum = 1; chartObj.primaryXAxis.interval = 2; chartObj.primaryXAxis.maximum = 20; chartObj.primaryYAxis.interval = 2; chartObj.primaryYAxis.logBase = 2; chartObj.series[0].dataSource = [ { y: 18, x: 1 }, { y: 29, x: 2 }, { y: 30, x: 3 }, { y: 41, x: 4 }, { y: 52, x: 5 }, { y: 62, x: 6 }, { y: 74, x: 7 }, { y: 85, x: 8 }, { y: 96, x: 9 }, { y: 102, x: 10 }]; chartObj.series[0].type = 'Column'; chartObj.refresh(); }); it('checking with Area Series', (done: Function) => { loaded = (args: Object): void => { svg = document.getElementById('containerSeriesGroup0'); expect(svg !== null).toBe(true); done(); }; chartObj.loaded = loaded; chartObj.series[0].type = 'Area'; chartObj.refresh(); }); it('checking with range', (done: Function) => { loaded = (args: Object): void => { text = document.getElementById("container0_AxisLabel_0"); expect(text.textContent == "0.1").toBe(true); text = document.getElementById("container0_AxisLabel_1"); expect(text.textContent == "10").toBe(true); done(); }; chartObj.loaded = loaded; chartObj.series[0].type = 'Line'; chartObj.primaryXAxis.minimum = 0.2; chartObj.refresh(); }); it('checking with large data', (done: Function) => { loaded = (args: Object): void => { svg = document.getElementById('containerSeriesGroup0'); expect(svg !== null).toBe(true); done(); }; chartObj.loaded = loaded; chartObj.series = [ { dataSource: [{ x: 1, y: 8 }, { x: 2, y: 10000 }, { x: 3, y: 400 }, { x: 4, y: 600 }, { x: 5, y: 900 }, { x: 6, y: 1400 }, { x: 7, y: 2000 }, { x: 8, y: 4000 }, { x: 9, y: 6000 }, { x: 10, y: 8000 }, { x: 10, y: 9000 }], name: 'Gold', xName: 'x', yName: 'y', fill: 'rgba(135,206,235,1)', type: 'Line', animation: { enable: false } }]; chartObj.primaryXAxis.minorGridLines.width = 0; chartObj.primaryYAxis.minorGridLines.width = 0; chartObj.primaryXAxis.minorTickLines.width = 0; chartObj.primaryYAxis.minorTickLines.width = 0; chartObj.primaryXAxis.valueType = 'Double'; chartObj.primaryYAxis.logBase = 10; chartObj.primaryYAxis.minimum = 1; chartObj.primaryXAxis.interval = 1; chartObj.primaryXAxis.minimum = 1; chartObj.primaryYAxis.maximum = null; chartObj.refresh(); }); it('checking with edgelabelplacement', (done: Function) => { loaded = (args: Object): void => { text = document.getElementById("container0_AxisLabel_0"); expect(text === null).toBe(true); let chartArea: HTMLElement = document.getElementById('container_ChartAreaBorder'); text = document.getElementById('container1_AxisLabel_0'); expect(parseFloat(text.getAttribute('y')) === parseFloat(chartArea.getAttribute('y')) + parseFloat(chartArea.getAttribute('height'))).toBe(true); done(); }; chartObj.loaded = loaded; chartObj.primaryXAxis.interval = null; chartObj.primaryXAxis.edgeLabelPlacement = 'Hide'; chartObj.primaryYAxis.edgeLabelPlacement = 'Shift'; chartObj.refresh(); }); it('checking with edgelabelplacement Hide', (done: Function) => { loaded = (args: Object): void => { let chartArea: HTMLElement = document.getElementById('container_ChartAreaBorder'); text = document.getElementById('container1_AxisLabel_0'); expect(text.textContent === '').toBe(true); done(); }; chartObj.loaded = loaded; chartObj.primaryXAxis.interval = null; chartObj.primaryYAxis.edgeLabelPlacement = 'Hide'; chartObj.refresh(); }); it('checking with labelFormat', (done: Function) => { loaded = (args: Object): void => { text = document.getElementById("container0_AxisLabel_0"); expect(text.textContent === '$1.00').toBe(true); done(); }; chartObj.loaded = loaded; chartObj.primaryXAxis.edgeLabelPlacement = 'None'; chartObj.primaryYAxis.edgeLabelPlacement = 'None'; chartObj.primaryXAxis.valueType = 'Logarithmic'; chartObj.series[0].dataSource = data; chartObj.primaryXAxis.labelFormat = 'C'; chartObj.refresh(); }); it('Checking the zoomFactor and zoomPosition', (done: Function) => { loaded = (args: Object): void => { text = document.getElementById("container0_AxisLabel_0"); expect(text !== null).toBe(true); text = document.getElementById("container1_AxisLabel_1"); expect(text !== null).toBe(true); done(); }; chartObj.loaded = loaded; chartObj.primaryXAxis.labelFormat = ''; chartObj.primaryXAxis.zoomFactor = 0.5; chartObj.primaryXAxis.zoomPosition = 0.5; chartObj.refresh(); }); it('Checking the enableAutoIntervalOnZooming false', (done: Function) => { loaded = (args: Object): void => { text = document.getElementById("container0_AxisLabel_0"); expect(text !== null).toBe(true); text = document.getElementById("container1_AxisLabel_1"); expect(text !== null).toBe(true); done(); }; chartObj.loaded = loaded; chartObj.primaryXAxis.enableAutoIntervalOnZooming = false; chartObj.refresh(); }); it('checking with multiple axes', (done: Function) => { loaded = (args: Object): void => { svg = document.getElementById('container2_AxisLabel_0'); expect(svg.textContent === '10@').toBe(true); done(); }; chartObj.loaded = loaded; chartObj.series = [{ dataSource: data, name: 'Gold', xName: 'x', yName: 'y', fill: 'red', type: 'Line', animation: { enable: false } }, { dataSource: data, name: 'Gold', xName: 'x', yName: 'y', fill: 'rgba(135,206,235,1)', type: 'Line', animation: { enable: false } }]; chartObj.axes = [{ rowIndex: 1, name: 'yAxis1', valueType: 'Logarithmic', labelFormat: '{value}@', titleStyle: { size: '14px', fontWeight: 'Regular', color: '#282828', fontStyle: 'Normal', fontFamily: 'Segoe UI' }, labelStyle: { size: '12px', fontWeight: 'Regular', color: '#282828', fontStyle: 'Normal', fontFamily: 'Segoe UI' } }]; chartObj.series[0].yAxisName = 'yAxis1'; chartObj.rows = [{ border: { width: 4, color: 'red' }, height: '300', }, { border: { width: 4, color: 'blue' } }]; chartObj.primaryXAxis.zoomFactor = 1; chartObj.primaryXAxis.enableAutoIntervalOnZooming = true; chartObj.primaryXAxis.zoomPosition = 0; chartObj.refresh(); }); it('Checking the Labels with empty data', () => { chartObj.series = []; chartObj.primaryXAxis.zoomFactor = 0.7; chartObj.primaryXAxis.zoomPosition = 0.2; chartObj.axisLabelRender = (args: IAxisLabelRenderEventArgs) => { args.text = args.text + 'cus'; } chartObj.loaded = null; chartObj.refresh(); svg = document.getElementById('containerAxisLabels0'); expect(svg.childNodes.length == 1).toBe(true); expect(svg.childNodes[0].textContent.indexOf('cus') > -1).toBe(true); }); it('checking x axis as inversed axis', (done: Function) => { loaded = (args: Object): void => { let firstLabel: HTMLElement = document.getElementById('container0_AxisLabel_0'); expect(firstLabel.textContent).toEqual('1'); let secondLabel = document.getElementById('container0_AxisLabel_2'); expect(secondLabel.textContent).toEqual('100'); expect(+firstLabel.getAttribute('x') > (+secondLabel.getAttribute('x'))).toBe(true); done(); }; chartObj.loaded = loaded; chartObj.primaryXAxis.isInversed = true; chartObj.primaryXAxis.zoomFactor = 1; chartObj.primaryXAxis.zoomPosition = 0; chartObj.axisLabelRender = null; chartObj.primaryXAxis.desiredIntervals = null; chartObj.refresh(); }); }); describe('Checking line break labels with logarithmic axis', () => { let chart: Chart; let elem: HTMLElement; let svg: HTMLElement; let text: HTMLElement; let datalabel: HTMLElement; let loaded: EmitType<ILoadedEventArgs>; beforeAll(() => { elem = createElement('div', { id: 'container' }); document.body.appendChild(elem); chart = new Chart( { primaryXAxis: { valueType: 'Logarithmic', labelFormat: '{value}<br>text', }, primaryYAxis: {}, series: [{ dataSource: [{ x: 10, y: 7 }, { x: 100, y: 1 }, { x: 1000, y: 1 }, { x: 10000, y: 14 }, { x: 100000, y: 1 }, { x: 1000000, y: 10 },], xName: 'x', yName: 'y', animation: { enable: false }, type: 'Line', }, ], legendSettings: { visible: false } }, '#container'); }); afterAll((): void => { elem.remove(); chart.destroy(); }); it('default line break checking with log axis', (done: Function) => { loaded = (args: Object): void => { let label: HTMLElement = document.getElementById('containerAxisLabels0'); expect(label.childElementCount == 6).toBe(true); label = document.getElementById('container0_AxisLabel_1'); expect(label.childNodes[0].textContent == '100').toBe(true); expect(label.childNodes[1].textContent == 'text').toBe(true); done(); }; chart.loaded = loaded; chart.refresh(); }); it('Checking line break labels with inversed axis', (done: Function) => { loaded = (args: Object): void => { let label: HTMLElement = document.getElementById('containerAxisLabels0'); expect(label.childElementCount == 6).toBe(true); label= document.getElementById('container0_AxisLabel_1'); expect(label.childNodes[0].textContent == '100').toBe(true); expect(label.childNodes[1].textContent == 'text').toBe(true); done(); }; chart.loaded = loaded; chart.primaryXAxis.isInversed = true; chart.refresh(); }); it('Checking line break labels with opposed position true', (done: Function) => { loaded = (args: Object): void => { let label: HTMLElement = document.getElementById('containerAxisLabels0'); expect(label.childElementCount == 6).toBe(true); label= document.getElementById('container0_AxisLabel_0'); expect(label.childNodes[0].textContent == 'text').toBe(true); expect(label.childNodes[1].textContent == '10').toBe(true); done(); }; chart.loaded = loaded; chart.primaryXAxis.isInversed = false; chart.primaryXAxis.opposedPosition = true; chart.refresh(); }); }); it('memory leak', () => { profile.sample(); let average: any = inMB(profile.averageChange) //Check average change in memory samples to not be over 10MB expect(average).toBeLessThan(10); let memory: any = inMB(getMemoryProfile()) //Check the final memory usage against the first usage, there should be little change if everything was properly deallocated expect(memory).toBeLessThan(profile.samples[0] + 0.25); }) });
the_stack
import type {Mutable, Proto, AnyTiming} from "@swim/util"; import {FastenerContext, FastenerOwner, FastenerInit, FastenerClass, Fastener} from "@swim/component"; import type { AnyConstraintExpression, ConstraintVariable, ConstraintProperty, ConstraintRelation, AnyConstraintStrength, Constraint, ConstraintScope, } from "@swim/constraint"; import {Look, Feel, MoodVector, ThemeMatrix, ThemeContext} from "@swim/theme"; import {CssContext} from "./CssContext"; /** @public */ export interface CssRuleInit extends FastenerInit { extends?: {prototype: CssRule<any>} | string | boolean | null; css?: string | (() => string); initRule?(rule: CSSRule): void; } /** @public */ export type CssRuleDescriptor<O = unknown, I = {}> = ThisType<CssRule<O> & I> & CssRuleInit & Partial<I>; /** @public */ export interface CssRuleClass<F extends CssRule<any> = CssRule<any>> extends FastenerClass<F> { } /** @public */ export interface CssRuleFactory<F extends CssRule<any> = CssRule<any>> extends CssRuleClass<F> { extend<I = {}>(className: string, classMembers?: Partial<I> | null): CssRuleFactory<F> & I; define<O>(className: string, descriptor: CssRuleDescriptor<O>): CssRuleFactory<CssRule<any>>; define<O, I = {}>(className: string, descriptor: {implements: unknown} & CssRuleDescriptor<O, I>): CssRuleFactory<CssRule<any> & I>; <O>(descriptor: CssRuleDescriptor<O>): PropertyDecorator; <O, I = {}>(descriptor: {implements: unknown} & CssRuleDescriptor<O, I>): PropertyDecorator; } /** @public */ export interface CssRule<O = unknown> extends Fastener<O>, FastenerContext, ConstraintScope, ThemeContext { /** @override */ get fastenerType(): Proto<CssRule<any>>; readonly rule: CSSRule; /** @internal */ readonly fasteners: {[fastenerName: string]: Fastener | undefined} | null; /** @override */ hasFastener(fastenerName: string, fastenerBound?: Proto<Fastener> | null): boolean; /** @override */ getFastener<F extends Fastener<any>>(fastenerName: string, fastenerBound: Proto<F>): F | null; /** @override */ getFastener(fastenerName: string, fastenerBound?: Proto<Fastener> | null): Fastener | null; /** @override */ setFastener(fastenerName: string, fastener: Fastener | null): void; /** @override */ getLazyFastener<F extends Fastener<any>>(fastenerName: string, fastenerBound: Proto<F>): F | null; /** @override */ getLazyFastener(fastenerName: string, fastenerBound?: Proto<Fastener> | null): Fastener | null; /** @override */ getSuperFastener<F extends Fastener<any>>(fastenerName: string, fastenerBound: Proto<F>): F | null; /** @override */ getSuperFastener(fastenerName: string, fastenerBound?: Proto<Fastener> | null): Fastener | null; /** @internal @override */ getSuperFastener(): Fastener | null; /** @internal @protected */ mountFasteners(): void; /** @internal @protected */ unmountFasteners(): void; /** @override */ requireUpdate(updateFlags: number): void; /** @internal */ readonly decoherent: ReadonlyArray<Fastener> | null; /** @override */ decohereFastener(fastener: Fastener): void; /** @override */ recohere(t: number): void /** @internal @protected */ recohereFasteners(t: number): void /** @override */ constraint(lhs: AnyConstraintExpression, relation: ConstraintRelation, rhs?: AnyConstraintExpression, strength?: AnyConstraintStrength): Constraint; /** @override */ hasConstraint(constraint: Constraint): boolean; /** @override */ addConstraint(constraint: Constraint): void; /** @override */ removeConstraint(constraint: Constraint): void; /** @override */ constraintVariable(name: string, value?: number, strength?: AnyConstraintStrength): ConstraintProperty<unknown, number>; /** @override */ hasConstraintVariable(variable: ConstraintVariable): boolean; /** @override */ addConstraintVariable(variable: ConstraintVariable): void; /** @override */ removeConstraintVariable(variable: ConstraintVariable): void; /** @internal @override */ setConstraintVariable(constraintVariable: ConstraintVariable, state: number): void; /** @override */ getLook<T>(look: Look<T, unknown>, mood?: MoodVector<Feel> | null): T | undefined; /** @override */ getLookOr<T, E>(look: Look<T, unknown>, elseValue: E): T | E; /** @override */ getLookOr<T, E>(look: Look<T, unknown>, mood: MoodVector<Feel> | null, elseValue: E): T | E; applyTheme(theme: ThemeMatrix, mood: MoodVector, timing?: AnyTiming | boolean): void; /** @protected @override */ onMount(): void; /** @protected @override */ onUnmount(): void; /** @internal */ createRule(cssText: string): CSSRule; /** @internal */ initRule?(rule: CSSRule): void; /** @internal */ initCss?(): string; } /** @public */ export const CssRule = (function (_super: typeof Fastener) { const CssRule: CssRuleFactory = _super.extend("CssRule"); Object.defineProperty(CssRule.prototype, "fastenerType", { get: function (this: CssRule): Proto<CssRule<any>> { return CssRule; }, configurable: true, }); CssRule.prototype.hasFastener = function (this: CssRule, fastenerName: string, fastenerBound?: Proto<Fastener> | null): boolean { const fasteners = this.fasteners; if (fasteners !== null) { const fastener = fasteners[fastenerName]; if (fastener !== void 0 && (fastenerBound === void 0 || fastenerBound === null || fastener instanceof fastenerBound)) { return true; } } return false; }; CssRule.prototype.getFastener = function (this: CssRule, fastenerName: string, fastenerBound?: Proto<Fastener> | null): Fastener | null { const fasteners = this.fasteners; if (fasteners !== null) { const fastener = fasteners[fastenerName]; if (fastener !== void 0 && (fastenerBound === void 0 || fastenerBound === null || fastener instanceof fastenerBound)) { return fastener; } } return null; }; CssRule.prototype.setFastener = function (this: CssRule, fastenerName: string, newFastener: Fastener | null): void { let fasteners = this.fasteners; if (fasteners === null) { fasteners = {}; (this as Mutable<typeof this>).fasteners = fasteners; } const oldFastener = fasteners[fastenerName]; if (oldFastener !== void 0 && this.mounted) { oldFastener.unmount(); } if (newFastener !== null) { fasteners[fastenerName] = newFastener; if (this.mounted) { newFastener.mount(); } } else { delete fasteners[fastenerName]; } }; CssRule.prototype.getLazyFastener = function (this: CssRule, fastenerName: string, fastenerBound?: Proto<Fastener> | null): Fastener | null { return FastenerContext.getLazyFastener(this, fastenerName, fastenerBound); }; CssRule.prototype.getSuperFastener = function (this: CssRule, fastenerName?: string, fastenerBound?: Proto<Fastener> | null): Fastener | null { if (arguments.length === 0) { return _super.prototype.getSuperFastener.call(this); } else { return null; } }; CssRule.prototype.mountFasteners = function (this: CssRule): void { const fasteners = this.fasteners; for (const fastenerName in fasteners) { const fastener = fasteners[fastenerName]!; fastener.mount(); } }; CssRule.prototype.unmountFasteners = function (this: CssRule): void { const fasteners = this.fasteners; for (const fastenerName in fasteners) { const fastener = fasteners[fastenerName]!; fastener.unmount(); } }; CssRule.prototype.requireUpdate = function (this: CssRule, updateFlags: number): void { const propertyContext = this.owner; if (FastenerContext.has(propertyContext, "requireUpdate")) { propertyContext.requireUpdate(updateFlags); } }; CssRule.prototype.decohereFastener = function (this: CssRule, fastener: Fastener): void { let decoherent = this.decoherent as Fastener[]; if (decoherent === null) { decoherent = []; (this as Mutable<typeof this>).decoherent = decoherent; } decoherent.push(fastener); if ((this.flags & Fastener.DecoherentFlag) === 0) { this.setCoherent(false); this.decohere(); } }; CssRule.prototype.recohereFasteners = function (this: CssRule, t: number): void { const decoherent = this.decoherent; if (decoherent !== null) { const decoherentCount = decoherent.length; if (decoherentCount !== 0) { (this as Mutable<typeof this>).decoherent = null; for (let i = 0; i < decoherentCount; i += 1) { const fastener = decoherent[i]!; fastener.recohere(t); } } } }; CssRule.prototype.recohere = function (this: CssRule, t: number): void { this.recohereFasteners(t); if (this.decoherent === null || this.decoherent.length === 0) { this.setCoherent(true); } else { this.setCoherent(false); this.decohere(); } }; CssRule.prototype.constraint = function (this: CssRule<ConstraintScope>, lhs: AnyConstraintExpression, relation: ConstraintRelation, rhs?: AnyConstraintExpression, strength?: AnyConstraintStrength): Constraint { return this.owner.constraint(lhs, relation, rhs, strength); }; CssRule.prototype.hasConstraint = function (this: CssRule<ConstraintScope>, constraint: Constraint): boolean { return this.owner.hasConstraint(constraint); }; CssRule.prototype.addConstraint = function (this: CssRule<ConstraintScope>, constraint: Constraint): void { this.owner.addConstraint(constraint); }; CssRule.prototype.removeConstraint = function (this: CssRule<ConstraintScope>, constraint: Constraint): void { this.owner.removeConstraint(constraint); }; CssRule.prototype.constraintVariable = function (this: CssRule<ConstraintScope>, name: string, value?: number, strength?: AnyConstraintStrength): ConstraintProperty<unknown, number> { return this.owner.constraintVariable(name, value, strength); }; CssRule.prototype.hasConstraintVariable = function (this: CssRule<ConstraintScope>, constraintVariable: ConstraintVariable): boolean { return this.owner.hasConstraintVariable(constraintVariable); }; CssRule.prototype.addConstraintVariable = function (this: CssRule<ConstraintScope>, constraintVariable: ConstraintVariable): void { this.owner.addConstraintVariable(constraintVariable); }; CssRule.prototype.removeConstraintVariable = function (this: CssRule<ConstraintScope>, constraintVariable: ConstraintVariable): void { this.owner.removeConstraintVariable(constraintVariable); }; CssRule.prototype.setConstraintVariable = function (this: CssRule<ConstraintScope>, constraintVariable: ConstraintVariable, state: number): void { this.owner.setConstraintVariable(constraintVariable, state); }; CssRule.prototype.getLook = function <T>(this: CssRule, look: Look<T, unknown>, mood?: MoodVector<Feel> | null): T | undefined { const themeContext = this.owner; if (ThemeContext.is(themeContext)) { return themeContext.getLook(look, mood); } else { return void 0; } }; CssRule.prototype.getLookOr = function <T, E>(this: CssRule, look: Look<T, unknown>, mood: MoodVector<Feel> | null | E, elseValue?: E): T | E { const themeContext = this.owner; if (ThemeContext.is(themeContext)) { if (arguments.length === 2) { return themeContext.getLookOr(look, mood as E); } else { return themeContext.getLookOr(look, mood as MoodVector<Feel> | null, elseValue!); } } else if (arguments.length === 2) { return mood as E; } else { return elseValue!; } }; CssRule.prototype.applyTheme = function (this: CssRule, theme: ThemeMatrix, mood: MoodVector, timing?: AnyTiming | boolean | null): void { // hook }; CssRule.prototype.onMount = function (this: CssRule): void { _super.prototype.onMount.call(this); this.mountFasteners(); }; CssRule.prototype.onUnmount = function (this: CssRule): void { this.unmountFasteners(); _super.prototype.onUnmount.call(this); }; CssRule.prototype.createRule = function (this: CssRule, cssText: string): CSSRule { const cssContext = this.owner; if (CssContext.is(cssContext)) { const index = cssContext.insertRule(cssText); const rule = cssContext.getRule(index); if (rule instanceof CSSRule) { return rule; } else { throw new TypeError("" + rule); } } else { throw new Error("no css context"); } }; CssRule.construct = function <F extends CssRule<any>>(ruleClass: {prototype: F}, rule: F | null, owner: FastenerOwner<F>): F { rule = _super.construct(ruleClass, rule, owner) as F; (rule as Mutable<typeof rule>).fasteners = null; (rule as Mutable<typeof rule>).decoherent = null; (rule as Mutable<typeof rule>).rule = null as unknown as CSSRule; FastenerContext.init(rule); return rule; }; CssRule.define = function <O>(className: string, descriptor: CssRuleDescriptor<O>): CssRuleFactory<CssRule<any>> { let superClass = descriptor.extends as CssRuleFactory | null | undefined; const affinity = descriptor.affinity; const inherits = descriptor.inherits; let css = descriptor.css; delete descriptor.extends; delete descriptor.implements; delete descriptor.affinity; delete descriptor.inherits; delete descriptor.css; if (superClass === void 0 || superClass === null) { superClass = this; } const ruleClass = superClass.extend(className, descriptor); if (typeof css === "function") { ruleClass.prototype.initCss = css; css = void 0; } ruleClass.construct = function (ruleClass: {prototype: CssRule<any>}, rule: CssRule<O> | null, owner: O): CssRule<O> { rule = superClass!.construct(ruleClass, rule, owner); if (affinity !== void 0) { rule.initAffinity(affinity); } if (inherits !== void 0) { rule.initInherits(inherits); } let cssText: string | undefined; if (css !== void 0) { cssText = css as string; } else if (rule.initCss !== void 0) { cssText = rule.initCss(); } else { throw new Error("undefined css"); } (rule as Mutable<typeof rule>).rule = rule.createRule(cssText); if (rule.initRule !== void 0) { rule.initRule(rule.rule); } return rule; }; return ruleClass; }; return CssRule; })(Fastener);
the_stack
import * as d3Color from 'd3-color'; import * as d3Selection from 'd3-selection'; const d3 = { ...d3Color, ...d3Selection, }; import {CSS_PREFIX} from '../const'; import * as utils from '../utils/utils'; import * as utilsDraw from '../utils/utils-draw'; import {BasePath} from './element.path.base'; import {getLineClassesByCount} from '../utils/css-class-map'; import {GrammarRegistry} from '../grammar-registry'; import {d3_createPathTween} from '../utils/d3-decorators'; import {getInterpolatorSplineType} from '../utils/path/interpolators/interpolators-registry'; import {getAreaPolygon, getSmoothAreaPath} from '../utils/path/svg/area-path'; import {getClosestPointInfo} from '../utils/utils-position'; import {useFillGapsRule} from '../utils/utils-grammar'; import { GrammarElement } from '../definitions'; const Area = { draw: BasePath.draw, highlight: BasePath.highlight, highlightDataPoints: BasePath.highlightDataPoints, addInteraction: BasePath.addInteraction, _sortElements: BasePath._sortElements, init(xConfig) { const config = BasePath.init(xConfig); const enableStack = config.stack; config.transformRules = [ config.flip && GrammarRegistry.get('flip'), config.guide.obsoleteVerticalStackOrder && GrammarRegistry.get('obsoleteVerticalStackOrder'), !enableStack && GrammarRegistry.get('groupOrderByAvg'), useFillGapsRule(config), enableStack && GrammarRegistry.get('stack') ]; config.adjustRules = [ ((prevModel, args) => { const isEmptySize = prevModel.scaleSize.isEmptyScale(); const sizeCfg = utils.defaults( (config.guide.size || {}), { defMinSize: 2, defMaxSize: (isEmptySize ? 6 : 40) }); const params = Object.assign( {}, args, { defMin: sizeCfg.defMinSize, defMax: sizeCfg.defMaxSize, minLimit: sizeCfg.minSize, maxLimit: sizeCfg.maxSize }); return GrammarRegistry.get('adjustStaticSizeScale')(prevModel, params); }) ]; return config; }, buildModel(screenModel) { const baseModel = BasePath.baseModel(screenModel); const guide = this.node().config.guide; const countCss = getLineClassesByCount(screenModel.model.scaleColor.domain().length); const groupPref = `${CSS_PREFIX}area area i-role-path ${countCss} ${guide.cssClass} `; baseModel.groupAttributes = { class: (fiber) => `${groupPref} ${baseModel.class(fiber[0])} frame` }; const toDirPoint = (d) => ({ id: screenModel.id(d), x: baseModel.x(d), y: baseModel.y(d) }); const toRevPoint = (d) => ({ id: screenModel.id(d), x: baseModel.x0(d), y: baseModel.y0(d) }); const pathAttributes = { fill: (fiber) => baseModel.color(fiber[0]), stroke: (fiber) => { var colorStr = baseModel.color(fiber[0]); if (colorStr.length > 0) { colorStr = d3.rgb(colorStr).darker(1); } return colorStr; } }; baseModel.pathAttributesEnterInit = pathAttributes; baseModel.pathAttributesUpdateDone = pathAttributes; const isPolygon = (getInterpolatorSplineType(guide.interpolate) === 'polyline'); baseModel.pathElement = (isPolygon ? 'polygon' : 'path'); baseModel.anchorShape = 'vertical-stick'; baseModel.pathTween = { attr: (isPolygon ? 'points' : 'd'), fn: d3_createPathTween( (isPolygon ? 'points' : 'd'), (isPolygon ? getAreaPolygon : getSmoothAreaPath), [toDirPoint, toRevPoint], screenModel.id, guide.interpolate ) }; return baseModel; }, _getBoundsInfo(this: GrammarElement, dots: Element[]) { if (dots.length === 0) { return null; } const screenModel = this.node().screenModel; const {flip} = this.node().config; const items = dots .map((node) => { const data = d3.select(node).data()[0]; const x = screenModel.x(data); const y = screenModel.y(data); const y0 = screenModel.y0(data); const group = screenModel.group(data); const item = {node, data, x, y, y0, group}; return item; }); const bounds = items.reduce( (bounds, {x, y, y0}) => { bounds.left = Math.min(x, bounds.left); bounds.right = Math.max(x, bounds.right); bounds.top = Math.min(y, y0, bounds.top); bounds.bottom = Math.max(y, y0, bounds.bottom); return bounds; }, { left: Number.MAX_VALUE, right: Number.MIN_VALUE, top: Number.MAX_VALUE, bottom: Number.MIN_VALUE }); const ticks = utils.unique(items.map(flip ? ((item) => item.y) : ((item) => item.x))).sort((a, b) => a - b); const groups = ticks.reduce(((obj, value) => (obj[value] = [], obj)), {} as {[x: number]: ElementInfo[]}); items.forEach((item) => { const tick = ticks.find(flip ? ((value) => item.y === value) : ((value) => item.x === value)); groups[tick].push(item); }); // Put placeholders for missing groups at some ticks (() => { const groupNames = Object.keys(items.reduce((map, item) => { map[item.group] = true; return map; }, {})); // Todo: sort groups by Y (consider missing groups at some ticks) const groupIndex = groupNames.reduce((map, g, i) => { map[g] = i; return map; }, {} as {[group: string]: number}); ticks.forEach((tick) => { const current = groups[tick]; current.sort((a, b) => groupIndex[a.group] - groupIndex[b.group]); if (current.length < groupNames.length) { for (var i = 0; i < groupNames.length; i++) { let shouldInsert = false; let y, y0; if (i === current.length) { if (i === 0) { y = y0 = 0; } else { y = y0 = current[i - 1].y; } shouldInsert = true; } else if (current[i].group !== groupNames[i]) { y = y0 = current[i].y0; shouldInsert = true; } if (shouldInsert) { let placeholder: ElementInfo = { x: tick, y, y0, data: null, // Placeholer should not have any data node: null, group: groupNames[i] }; current.splice(i, 0, placeholder); } } } }); })(); if (ticks.length === 1) { const tree: TreeNode = { start: ticks[0], end: ticks[0], isLeaf: true, items: { start: groups[ticks[0]], end: groups[ticks[0]] } }; return {bounds, tree}; } const split = (values: number[]): TreeNode => { if (values.length === 2) { let [start, end] = values; return { start, end, isLeaf: true, items: { start: groups[start], end: groups[end] } }; } const midIndex = ((values.length % 2 === 0) ? (values.length / 2) : ((values.length - 1) / 2)); const middle = values[midIndex]; return { start: values[0], end: values[values.length - 1], isLeaf: false, left: split(values.slice(0, midIndex + 1)), right: split(values.slice(midIndex)) }; }; const tree = split(ticks); return {bounds, tree}; }, getClosestElement(cursorX: number, cursorY: number) { if (!this._boundsInfo) { return null; } const {bounds, tree} = this._boundsInfo as BoundsInfo; const container = this.node().config.options.container; const {flip} = this.node().config; const translate = utilsDraw.getDeepTransformTranslate(container.node()); const {maxHighlightDistance} = this.node().config.guide; if ((cursorX < bounds.left + translate.x - maxHighlightDistance) || (cursorX > bounds.right + translate.x + maxHighlightDistance) || (cursorY < bounds.top + translate.y - maxHighlightDistance) || (cursorY > bounds.bottom + translate.y + maxHighlightDistance) ) { return null; } const cursor = (flip ? (cursorY - translate.y) : (cursorX - translate.x)); const closestSpan = (function getClosestSpan(span): TreeNode { if (span.isLeaf) { return span; } const mid = span.left.end; return getClosestSpan(cursor < mid ? span.left : span.right); })(tree); var kx = (closestSpan.end === closestSpan.start ? 0 : ((cursor - closestSpan.start) / (closestSpan.end - closestSpan.start))); if (kx < 0) { kx = 0; } if (kx > 1) { kx = 1; } const interpolated = (() => { interface Pair { start: ElementInfo; end: ElementInfo; y: number; y0: number; } const groups = closestSpan.items.start.reduce((map, el) => { map[el.group] = { start: el, end: null, y: null, y0: null }; return map; }, {} as {[group: string]: Pair}); closestSpan.items.end.forEach((el) => { if (groups[el.group] === undefined) { delete groups[el.group]; return; } groups[el.group].end = el; }); Object.keys(groups).forEach((key) => { const g = groups[key]; if (!g.end) { delete groups[key]; return; } g.y = (g.start.y + kx * (g.end.y - g.start.y)); g.y0 = (g.start.y0 + kx * (g.end.y0 - g.start.y0)); }); return Object.keys(groups).map((g) => groups[g]) .map((d) => ({ y: d.y, y0: d.y0, el: (kx < 0.5 ? d.start : d.end) })) .filter((d) => d.el.data != null); // Filter-out missing groups placeholders })(); const cy = (cursorY - translate.y); const cursorOverItems = interpolated .filter((d) => (cy >= d.y && cy <= d.y0)); const bestMatchItems = (cursorOverItems.length > 0 ? cursorOverItems : interpolated); const bestElements = bestMatchItems.map((d) => d.el) .map((el) => { const x = (el.x + translate.x); const y = (el.y + translate.y); const distance = Math.abs(flip ? (cursorY - y) : (cursorX - x)); const secondaryDistance = Math.abs(flip ? (cursorX - x) : (cursorY - y)); return {node: el.node, data: el.data, distance, secondaryDistance, x, y}; }); return getClosestPointInfo(cursorX, cursorY, bestElements); } }; interface BoundsInfo { bounds: {left; right; top; bottom;}; tree: TreeNode; } interface ElementInfo { x: number; y: number; y0: number; data: any; group: string; node: Element; } interface TreeNode { start: number; end: number; isLeaf: boolean; left?: TreeNode; right?: TreeNode; items?: { start: ElementInfo[]; end: ElementInfo[]; }; } export {Area};
the_stack
import React, { ChangeEvent } from 'react'; import _ from 'lodash' import { isNullOrUndefined } from 'util'; import { withStyles, WithStyles } from '@material-ui/core/styles' import { FormControlLabel, FormHelperText, Checkbox, Typography, Input } from '@material-ui/core'; import { Table, TableBody, TableCell, TableRow } from '@material-ui/core'; import { ExpansionPanel, ExpansionPanelSummary, ExpansionPanelDetails } from '@material-ui/core'; import ExpandMoreIcon from '@material-ui/icons/ExpandMore'; import {KubeComponent} from "../k8s/k8sObjectTypes"; import {filter} from '../util/filterUtil' import styles from './selectionTable.styles' interface ItemsListProps extends WithStyles<typeof styles> { title: string list: KubeComponent[] newSelections: Map<string, KubeComponent> disbleSelection: boolean handleChange: (KubeComponent) => any } const JumpingItemsList = ({title, classes, list, newSelections, handleChange, disbleSelection} : ItemsListProps) => { const selectedList = list.filter(item => !isNullOrUndefined(newSelections.get(item.text()))) const unselectedList = list.filter(item => isNullOrUndefined(newSelections.get(item.text()))) return (list.length === 0 ? <FormHelperText>No {title} found</FormHelperText> : <Table className={classes.table} aria-labelledby="tableTitle"> <TableBody> {selectedList.map((item, index) => ( <TableRow key={index} hover> <TableCell className={classes.tableCell}> <FormControlLabel control={ <Checkbox checked={true} value={item.text()} onChange={() => handleChange(item)} /> } label={item.name} /> </TableCell> </TableRow> ))} {unselectedList.map((item, index) => ( <TableRow key={index} hover> <TableCell className={classes.tableCell}> <FormControlLabel control={ <Checkbox checked={false} value={item.text()} disabled={disbleSelection} indeterminate={disbleSelection} onChange={() => handleChange(item)} /> } label={item.name} /> </TableCell> </TableRow> ))} </TableBody> </Table> ) } const ItemsList = ({title, classes, list, newSelections, handleChange, disbleSelection} : ItemsListProps) => { return (list.length === 0 ? <FormHelperText>No {title} found</FormHelperText> : <Table className={classes.table} aria-labelledby="tableTitle"> <TableBody> {list.map((item, index) => { const selected = !isNullOrUndefined(newSelections.get(item.text())) return ( <TableRow key={index} hover> <TableCell className={classes.tableCell}> <FormControlLabel control={ <Checkbox checked={selected} value={item.text()} disabled={!selected && disbleSelection} indeterminate={!selected && disbleSelection} onChange={() => handleChange(item)} /> } label={item.name} /> </TableCell> </TableRow> ) }) } </TableBody> </Table> ) } const getGroupedItemsList = (title, group, classes, list, newSelections, selectedCount, disbleSelection, handleChange) => ( [ <ExpansionPanelSummary key="1" expandIcon={<ExpandMoreIcon />}> <Typography className={classes.heading}>{group}</Typography> <Typography className={classes.secondaryHeading}>({list.length} items, {selectedCount} selected)</Typography> </ExpansionPanelSummary>, <ExpansionPanelDetails key="2"> <ItemsList title={title} classes={classes} newSelections={newSelections} list={list} disbleSelection={disbleSelection} handleChange={handleChange} /> </ExpansionPanelDetails> ] ) const CollapsedGroupedItemsList = ({title, group, classes, list, newSelections, selectedCount, disbleSelection, handleChange}) => ( <ExpansionPanel defaultExpanded={false}> {...getGroupedItemsList(title, group, classes, list, newSelections, selectedCount, disbleSelection, handleChange)} </ExpansionPanel> ) const ExpandedGroupedItemsList = ({title, group, classes, list, newSelections, selectedCount, disbleSelection, handleChange}) => ( <ExpansionPanel defaultExpanded={true}> {...getGroupedItemsList(title, group, classes, list, newSelections, selectedCount, disbleSelection, handleChange)} </ExpansionPanel> ) interface SelectionTableProps extends WithStyles<typeof styles> { table: {[group: string]: KubeComponent[]} selections: Map<string, KubeComponent> title: string maxSelect: number grouped: boolean onSelection: (KubeComponent) => void } interface SelectionTableState { table: {[group: string]: KubeComponent[]} filteredTable: {[group: string]: KubeComponent[]} newSelections: Map<string, KubeComponent> collapsedGroups: {} countSelected: number, } class SelectionTable extends React.Component<SelectionTableProps, SelectionTableState> { static defaultProps = { maxSelect: -1 } state: SelectionTableState = { table: {}, filteredTable: {}, newSelections: new Map(), collapsedGroups: {}, countSelected: 0, } filterText: string = '' componentDidMount() { this.handleChange = this.handleChange.bind(this) this.componentWillReceiveProps(this.props) } componentWillReceiveProps(nextProps: SelectionTableProps) { const {table, selections} = nextProps const newSelections = new Map(); Array.from(selections.values()).forEach(item => newSelections.set(item.text(), item)) this.setState({ newSelections: newSelections, countSelected: selections.size, table, }) } getSelections() : Array<KubeComponent> { const {newSelections} = this.state return Array.from(newSelections.values()) } handleChange(item: KubeComponent) { const {newSelections} = this.state; const {maxSelect, onSelection} = this.props let countSelected : number = newSelections.size const exists = newSelections.get(item.text()) if(exists) { newSelections.delete(item.text()) countSelected-- } else if(maxSelect > 0 && countSelected < maxSelect) { newSelections.set(item.text(), item) countSelected++ } this.setState({newSelections, countSelected}); onSelection(item) }; handleCollapse(group: string) { const {collapsedGroups} = this.state collapsedGroups[group] = !collapsedGroups[group] this.setState({collapsedGroups}); } onFilterChange = (event) => { const {table, newSelections} = this.state const filteredTable = {} let text = event.target.value if(text && text.length > 0) { this.filterText = text if(text.length > 0) { Object.keys(table).forEach(group => { const list = table[group] let filteredList = filter(text, list, "name") list.filter(item => !isNullOrUndefined(newSelections.get(item.text()))) .forEach(item => { if(filteredList.includes(item)) { filteredList = filteredList.filter(i => i !== item) } filteredList.unshift(item) }) filteredTable[group] = filteredList }) this.setState({filteredTable}) } } else { this.clearFilter() } this.forceUpdate() } clearFilter() { this.filterText = '' this.setState({filteredTable: {}}) } onKeyDown = (event) => { if(event.which === 27 /*Esc*/) { this.clearFilter() } } render() { const {filteredTable, table, newSelections, countSelected, collapsedGroups} = this.state; const {title, classes, maxSelect, grouped} = this.props; const isFiltered = Object.keys(filteredTable).length > 0 const dataTable = isFiltered ? filteredTable : table const groups = Object.keys(dataTable) const hasData = _.flatten(_.values(dataTable)).length > 0 const disbleSelection = maxSelect > 0 && countSelected >= maxSelect let heading = '' if(hasData) { if(maxSelect > 0) { heading = "Select up to " + maxSelect + " " + title + " " } else { heading = "Select " + title + " " } let totalItems = 0 Object.values(dataTable).forEach(list => totalItems += list.length) heading += "(" + totalItems + " items, " + newSelections.size + " selected)" } return ( <div> <Input fullWidth autoFocus placeholder="Type here to search" value={this.filterText} onChange={this.onFilterChange} onKeyDown={this.onKeyDown} className={classes.filterInput} /> {!hasData && <FormHelperText>No {title} found</FormHelperText>} {hasData && <FormHelperText>{heading}</FormHelperText>} {hasData && grouped && groups.map((group, index) => { const list = dataTable[group] const selectedCount = list.filter(item => !isNullOrUndefined(newSelections.get(item.text()))).length return ( isFiltered || groups.length===1 ? <ExpandedGroupedItemsList key={index} title={title} group={group} classes={classes} list={list} newSelections={newSelections} selectedCount={selectedCount} disbleSelection={disbleSelection} handleChange={this.handleChange} /> : <CollapsedGroupedItemsList key={index} title={title} group={group} classes={classes} list={list} newSelections={newSelections} selectedCount={selectedCount} disbleSelection={disbleSelection} handleChange={this.handleChange} /> ) }) } {hasData && !grouped && <ItemsList title={title} classes={classes} newSelections={newSelections} list={dataTable[groups[0]]} disbleSelection={disbleSelection} handleChange={this.handleChange} /> } </div> ) } } export default withStyles(styles)(SelectionTable);
the_stack
import {Remote} from '../remotes/remotebase'; import * as util from 'util'; import {Utility} from '../misc/utility'; import {Labels} from '../labels/labels'; import {MetaBlock} from '../misc/memorydump'; import {Settings} from '../settings'; import {MemoryDumpView} from './memorydumpview'; import {BaseView} from './baseview'; /// The number of word columns shown in one line. const MEM_COLUMNS = 8; /** * A Webview that shows a memory dump. * The memory dump can also be edited. * There is a rather complex messaging between the webview's html javascript (the webview * panel) and the extension (the typescript code): * - Display: * - Register coloring: If the address of a value is the same as a register value it is colored * differently. 'setColorsForRegisterPointers' calls 'setAddressColor' in the webview. This is done * when the panel is created or updated (each step) or when the webview becomes visible (e.g. if * it was hidden). * - The dump contents is updated on every step ('update'). * - The hovering text (labels etc.): When the mouse is over a value or address the webview asks for the hovering text ('getValueInfoText/getAddressInfoText'. * This way the calculation of all labels is delayed. A message with the info is sent to the webview ('valueInfoText/addressInfoText'). * - Editing: * - On double click the webview turns the cell in editable mode. * - When the user presses enter the new value is sent from the webview('valueChanged'). * - The value is then changed in the remote and the real value (from the remote) is sent to * to the webview. The webview will then update all cells with the same address. I.e. if there * are 2 same cells both are updated. * - If there are several memory views all are informed about the new value to update their display. * * See design.md for a sequence chart. */ export class MemoryDumpViewWord extends MemoryDumpView { /// true if little endian is used. protected littleEndian: boolean; /** * Creates the basic panel. */ constructor(littleEndian: boolean) { super(); this.littleEndian = littleEndian; // Title prefix depends on endianess if (!littleEndian) this.titlePrefix += "(big endian) "; } /** * Adds a new memory block to display. * Memory blocks are ordered, i.e. the 'memDumps' array is ordered from * low to high (the start addresses). * @param startAddress The address of the memory block in words. * @param size The size of the memory block in words. */ public addBlock(startAddress: number, size: number, title: string) { this.memDump.addBlockWithoutBoundary(startAddress, 2*size, title); } /** * The user just changed a cell in the dump view table. * The value is written to memory. Either little or big endian. * @param address The address to change. * @param value The new word value. */ protected async changeMemory(address: number, value: number) { // Get bytes dependent on endianness let lowByte = value & 0xFF; let highByte = value >> 8; if (!this.littleEndian) { const tmp = lowByte; lowByte = highByte; highByte = tmp; } // Prepare data const data = new Uint8Array([lowByte, highByte]); await Remote.writeMemoryDump(address, data); const realData = await Remote.readMemoryDump(address, 2); const realValue = realData[0] + 256 * realData[1]; // In little endian for (const mdvb of MemoryDumpView.MemoryViews) { const mdv = mdvb as MemoryDumpViewWord; // To gain access // Check first if address included at all if (!isNaN(mdv.memDump.getWordValueFor(address, this.littleEndian))) { // Update value mdv.memDump.setWordValueFor(address, realValue, true); // Also write as little endian } }; // Update html without getting data from remote BaseView.staticCallUpdateWithoutRemote(); // Inform vscode BaseView.sendChangeEvent(); } /** * Retrieves the value info text (that is the hover text). * @param address The address for which the info should be shown. */ protected async getValueInfoText(address: number) { // Value const value = this.memDump.getWordValueFor(address, this.littleEndian); const valFormattedString = await Utility.numberFormatted('', value, 1, Settings.launch.memoryViewer.valueHoverFormat, undefined); let text = valFormattedString + '\n'; // Address const addrFormattedString = await Utility.numberFormatted('', address, 2, Settings.launch.memoryViewer.addressHoverFormat, undefined); text += '@\n' + addrFormattedString; // Check for last value const prevValue = this.memDump.getPrevWordValueFor(address, this.littleEndian); if (!isNaN(prevValue)) { if (prevValue != value) { // has changed so add the last value to the hover text text += '\nPrevious value: ' + Utility.getHexString(prevValue, 2) + 'h'; } } // Now send the formatted text to the web view for display. const msg = { command: 'valueInfoText', address: address.toString(), text: text }; this.sendMessageToWebView(msg); } /** * Creates one html table out of a meta block. * @param index The number of the memory block, starting at 0. * Used for the id. * @param metaBlock The block to convert. */ protected createHtmlTable(metaBlock: MetaBlock): string { if (!metaBlock.data) return ''; const format= ` <table style=""> <colgroup> <col> <col width="10em"> <col span="%d" width="20em"> </colgroup> %s </table> `; // Create a string with the table itself. let table = ''; let address=metaBlock.address; let i = 0; const data = metaBlock.data; const len=data.length; const addressColor = Settings.launch.memoryViewer.addressColor; const bytesColor = Settings.launch.memoryViewer.bytesColor; // Table column headers table += '<tr>\n<th>Address:</th> <th></th>'; for(let k=0; k<MEM_COLUMNS; k++) { table += '<th>+' + (2*k).toString(16).toUpperCase() + '</th>'; } table += '\n</tr>'; // Table contents const littleEndian = this.littleEndian; let firstAddress; let secondAddress; for (let k = 0; k < len - 1; k += 2) { // Address but bound to 64k to forecome wrap arounds const addr64k=address&0xFFFF; // Check start of line if(i == 0) { // start of a new line let addrText=Utility.getHexString(addr64k,4) + ':'; table+='<tr>\n<td addressLine="'+addr64k + '" style="color:' + addressColor + '; border-radius:3px; cursor: pointer" onmouseover="mouseOverAddress(this)">' + addrText + '</td>\n'; table += '<td> </td>\n'; } // Print value const value = Utility.getUintFromMemory(data, k, 2, this.littleEndian); let valueText = Utility.getHexString(value, 4); // Split the text in 2 parts const addr64k2 = (addr64k + 1) & 0xFFFF; if (littleEndian) { firstAddress = addr64k; secondAddress = addr64k2; } else { firstAddress = addr64k2; secondAddress = addr64k; } valueText = '<span address="' + secondAddress + '">' + valueText.substr(0, 2) + '</span><span address="' + firstAddress + '">' + valueText.substr(2, 2) + '</span>'; // Check if in address range if(metaBlock.isInRange(address)) valueText = this.addEmphasizeInRange(valueText); else valueText = this.addDeemphasizeNotInRange(valueText); // Check if label points directly to this address if (Labels.getLabelsForNumber64k(addr64k).length > 0) valueText = this.addEmphasizeLabelled(valueText); // Compare with prev value. const prevData=metaBlock.prevData; if (prevData) { if (prevData.length > 0) { const prevValue = Utility.getUintFromMemory(prevData, k, 2, this.littleEndian); if (value != prevValue) { // Change html emphasizes valueText = this.addEmphasizeChanged(valueText); } } } // Create html cell table += '<td address="' + addr64k + '" ondblclick="makeEditable(this)" onmouseover="mouseOverValue(this)" style="color:' + bytesColor + '">' + valueText +'</td>\n'; // Check end of line if (i == MEM_COLUMNS-1) { // end of a new line table += '</tr>\n'; } // Next column address += 2; i++; if(i >= MEM_COLUMNS) i = 0; } const html = util.format(format, MEM_COLUMNS, table); return html; } /** * Creates the script (i.e. functions) for all blocks (html tables). */ protected createHtmlScript(): string { // The html script const html = ` <script> const vscode = acquireVsCodeApi(); //---- Handle Mouse Over, Calculation of hover text ------- function mouseOverValue(obj) { const address = obj.getAttribute("address"); // Send request to vscode to calculate the hover text vscode.postMessage({ command: 'getValueInfoText', address: address }); } function mouseOverAddress(obj) { // Send request to vscode to calculate the hover text const address = obj.getAttribute("addressLine"); vscode.postMessage({ command: 'getAddressInfoText', address: address }); } //---- Handle Editing Cells -------- let prevValue = ''; // Used to restore the value if ESC is pressed. let curObj = null; // The currently used object (the tabbed cell) function keyPress(e) { let key = e.keyCode; if(key == 13) { // ENTER key const value = curObj.innerText; prevValue = value; // To prevent that the old value is shown in 'focusLost' const address = curObj.getAttribute("address"); e.preventDefault(); curObj.blur(); // Send new value for address to vscode vscode.postMessage({ command: 'valueChanged', address: address, value: value }); } else if(key == 27) { // ESC key, does not work in vscode // Use previous value e.preventDefault(); curObj.blur(); } } function focusLost(e) { // = "blur" // Undo: Use previous value if(prevValue.length > 0) curObj.innerText = prevValue; curObj.contentEditable = false; curObj.removeEventListener("blur", focusLost); curObj.removeEventListener("keypress", keyPress); curObj = null; } function makeEditable(obj) { // makes the object editable on double click. curObj = obj; // store object for use in other functions prevValue = curObj.innerText; // store for undo if(!curObj.innerText.endsWith('h')) curObj.innerText += 'h'; curObj.contentEditable = true; curObj.focus(); selection = window.getSelection(); // Save the selection. // Select the text range = document.createRange(); range.selectNodeContents(curObj); selection.removeAllRanges(); // Remove all ranges from the selection. selection.addRange(range); // Add listeners curObj.addEventListener("blur", focusLost, true); curObj.addEventListener("keypress", keyPress, true); } //---- Handle Messages from vscode extension -------- window.addEventListener('message', event => { const message = event.data; switch (message.command) { case 'valueInfoText': { const objs = document.querySelectorAll("td[address='"+message.address+"']"); for(let obj of objs) { obj.title = message.text; } } break; case 'addressInfoText': { const objs = document.querySelectorAll("td[addressLine='"+message.address+"']"); for(let obj of objs) { obj.title = message.text; } } break; case 'setAddressColor': { const objs = document.querySelectorAll("span[address='"+message.address+"']"); for(let obj of objs) { obj.style.backgroundColor = message.color; obj.style.borderRadius = '3px'; } } break; case 'setMemoryTable': { // Set table as html string const tableDiv=document.getElementById("mem_table_"+message.index); tableDiv.innerHTML=message.html; } break; } }); //# sourceURL=memorydumpviewword.js </script> `; return html; } }
the_stack
import { Graphics, WebGL } from "./graphics"; import * as shaders from "./shaders"; // JFA + 1 is good enough quality for most things (altohugh none of these // are as high quality as some other distance field generation methods). // // You can think of these are low, medium and high respectively. Each one // requires an extra run of JFA. type JumpFloodQuality = "JFA" | "JFA+1" | "JFA+2"; type Options = { outputCanvas?: HTMLCanvasElement; sizeHint?: [number, number]; }; export class DistanceFieldGenerator { private _gl: WebGL.Context; // The output canvas we're rendering to, passed in at construction-time. // When you generate a distance field this is resized to match the // size of the input canvas. private _outputCanvas: HTMLCanvasElement; // Used to transform input data (seeds drawn onto a canvas) into information // that's ready to be processed by JFA (a texture of pixels where each red-green // and blue-alpha pair specifies a grid location). private _prepJumpFloodData: Graphics.Material; // Programs that run jump-flood algorithm, ping-ponging data // between _sourceTexture and _destTexture. One outputs seed // positions which are used for another iteration of jump flood // and the other outputs distances. private _jumpFloodOutputSeedPosition: Graphics.Material; private _jumpFloodOutputDistance: Graphics.Material; // All programs render a single quad whose data is stored here. private _quadBuffer: Graphics.VertexBuffer; // WebGL doesn't let you write to the texture you're reading from. // So we ping-pong data back and forth between these two textures. private _sourceTexture: Graphics.Texture | null = null; private _destTexture: Graphics.Texture | null = null; private _sourceTextureTarget: Graphics.RenderTarget | null = null; private _destTextureTarget: Graphics.RenderTarget | null = null; private _seedInputTexture: Graphics.Texture | null = null; constructor(options: Options = {}) { if (options.outputCanvas != null) { this._outputCanvas = options.outputCanvas; } else { this._outputCanvas = document.createElement( "canvas" ) as HTMLCanvasElement; } const sizeHint = options.outputCanvas != null ? [options.outputCanvas.width, options.outputCanvas.height] : options.sizeHint != null ? options.sizeHint : [100, 100]; this._gl = new WebGL.Context(this._outputCanvas); this._resizeOutputCanvasAndTextures( sizeHint[0], sizeHint[1], "force-update" ); const gl = this._gl; // Disable all blending this._gl.setCopyBlendState(); const vertexFormat = new Graphics.VertexFormat(); vertexFormat.add( shaders.GLSLX_NAME_A_QUAD, Graphics.AttributeType.FLOAT, 2 ); // Create programs this._prepJumpFloodData = gl.createMaterial( vertexFormat, shaders.GLSLX_SOURCE_V_COPY_POSITION, shaders.GLSLX_SOURCE_F_PREP_FOR_JFA ); this._jumpFloodOutputSeedPosition = gl.createMaterial( vertexFormat, shaders.GLSLX_SOURCE_V_COPY_POSITION, shaders.GLSLX_SOURCE_F_JUMP_FLOOD_OUTPUT_SEED_POSITION ); this._jumpFloodOutputDistance = gl.createMaterial( vertexFormat, shaders.GLSLX_SOURCE_V_COPY_POSITION, shaders.GLSLX_SOURCE_F_JUMP_FLOOD_OUTPUT_DISTANCE ); // All draw calls use a single quad const QUAD = new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]); this._quadBuffer = gl.createVertexBuffer(vertexFormat.stride * QUAD.length); this._quadBuffer.upload(new Uint8Array(QUAD.buffer)); } destroy() { // Delete WebGL resources. These would eventually be garbage collected, but this // can take a while as explained here: https://stackoverflow.com/a/58505477 if (this._sourceTexture) { this._sourceTexture.free(); } if (this._destTexture) { this._destTexture.free(); } if (this._seedInputTexture) { this._seedInputTexture.free(); } // Delete buffers this._quadBuffer.free(); // Delete programs this._prepJumpFloodData.free(); this._jumpFloodOutputDistance.free(); this._jumpFloodOutputSeedPosition.free(); } public outputCanvas() { return this._outputCanvas; } private _resizeTextureIfNecessary( texture: Graphics.Texture, newWidth: number, newHeight: number, forceUpdate: "force-update" | "dont-force" = "dont-force" ) { if ( texture.width === newWidth && texture.height === newHeight && forceUpdate !== "force-update" ) { return; } texture.resize(newWidth, newHeight); } private _resizeOutputCanvasAndTextures( newWidth: number, newHeight: number, forceUpdate: "force-update" | "dont-force" = "dont-force" ) { const gl = this._gl; const outputCanvas = this._outputCanvas; const outputCanvasSizeNeedsUpdate = outputCanvas.width !== newWidth || outputCanvas.height !== newHeight || forceUpdate === "force-update"; if (outputCanvasSizeNeedsUpdate) { gl.resize(newWidth, newHeight, newWidth, newHeight); } // Resize or create textures if necessary if (this._sourceTexture == null) { this._sourceTexture = gl.createTexture( Graphics.TextureFormat.NEAREST_CLAMP, newWidth, newHeight ); this._sourceTextureTarget = gl.createRenderTarget(this._sourceTexture); } else { this._resizeTextureIfNecessary(this._sourceTexture, newWidth, newHeight); } if (this._destTexture == null) { this._destTexture = gl.createTexture( Graphics.TextureFormat.NEAREST_CLAMP, newWidth, newHeight ); this._destTextureTarget = gl.createRenderTarget(this._destTexture); } else { this._resizeTextureIfNecessary(this._destTexture, newWidth, newHeight); } if (this._seedInputTexture == null) { this._seedInputTexture = gl.createTexture( Graphics.TextureFormat.NEAREST_CLAMP, newWidth, newHeight ); } else { this._resizeTextureIfNecessary( this._seedInputTexture, newWidth, newHeight ); } } // Generates an SDF for antialiased black shapes drawn on a // white canvas (e.g. drawn by the Canvas2D API). public generateSDF( inputCanvas: HTMLCanvasElement, quality: JumpFloodQuality = "JFA" ) { const width = inputCanvas.width; const height = inputCanvas.height; this._resizeOutputCanvasAndTextures(width, height); this._setSeedsFromCanvas(inputCanvas); const maxDimension = Math.max(width, height); let stepSize = nextPowerOfTwo(maxDimension) / 2; while (stepSize >= 1) { const isLastStep = stepSize / 2 < 1 && quality == "JFA"; const output = isLastStep ? JumpFloodOutput.FOR_SCREEN : JumpFloodOutput.FOR_ANOTHER_STEP; this._runJumpFloodStep(stepSize, output); stepSize /= 2; } switch (quality) { case "JFA": { // We're done break; } case "JFA+1": { // Run the last step again this._runJumpFloodStep(1, JumpFloodOutput.FOR_SCREEN); break; } case "JFA+2": { // Run the last two steps again this._runJumpFloodStep(4, JumpFloodOutput.FOR_ANOTHER_STEP); this._runJumpFloodStep(3, JumpFloodOutput.FOR_ANOTHER_STEP); this._runJumpFloodStep(2, JumpFloodOutput.FOR_ANOTHER_STEP); this._runJumpFloodStep(1, JumpFloodOutput.FOR_SCREEN); break; } } } public getPixels(): Uint8Array { const gl = this._gl.gl; const pixels = new Uint8Array( gl.drawingBufferWidth * gl.drawingBufferHeight * 4 ); gl.readPixels( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, gl.RGBA, gl.UNSIGNED_BYTE, pixels ); return pixels; } // Move seed data from _seedInputTexture into _sourceTexture so that it // can be used for our jump flood algorithm. // // We could build this into the first step of the algorithm but it's // cleaner as a separate step and when I attempted to remove it it only // gave a 2fps improvement on large canvasses. private _setSeedsFromCanvas(inputCanvas: HTMLCanvasElement) { if (!this._seedInputTexture) { throw new Error( `Expected _seedInputTexture to be set before calling setSeedsFromCanvas` ); } const width = inputCanvas.width; const height = inputCanvas.height; this._seedInputTexture.resize(width, height, inputCanvas); const material = this._prepJumpFloodData; material.setUniformSampler( shaders.GLSLX_NAME_U_SEED_INPUT_TEXTURE, this._seedInputTexture, 0 ); material.setUniformVec2(shaders.GLSLX_NAME_U_RESOLUTION, width, height); this._gl.setRenderTarget(this._sourceTextureTarget); this._gl.setViewport(0, 0, width, height); this._gl.draw( Graphics.Primitive.TRIANGLE_STRIP, material, this._quadBuffer ); } // Run an iteration of the jump flood algorithm, using the suggested // output format. // // The current simulation state is always in _sourceTexture // and we draw onto _destTexture. private _runJumpFloodStep(stepSize: number, output: JumpFloodOutput) { if (!this._sourceTexture || !this._seedInputTexture) { throw new Error( `Expected textures to be set before calling setSeedsFromCanvas` ); } const { width, height } = this._outputCanvas; const material = output.format === "seed-position" ? this._jumpFloodOutputSeedPosition : this._jumpFloodOutputDistance; material.setUniformSampler( shaders.GLSLX_NAME_U_INPUT_TEXTURE, this._sourceTexture, 0 ); material.setUniformInt(shaders.GLSLX_NAME_U_STEP_SIZE, stepSize); material.setUniformVec2(shaders.GLSLX_NAME_U_RESOLUTION, width, height); if (output.format === "distance") { material.setUniformSampler( shaders.GLSLX_NAME_U_SEED_INPUT_TEXTURE, this._seedInputTexture, 1 ); } this._gl.setRenderTarget( output.renderTarget === "texture" ? this._destTextureTarget : null ); this._gl.setViewport(0, 0, width, height); this._gl.draw( Graphics.Primitive.TRIANGLE_STRIP, material, this._quadBuffer ); this._swapBuffers(); } private _swapBuffers() { const tmp = this._sourceTexture; const tmpTarget = this._sourceTextureTarget; this._sourceTexture = this._destTexture; this._sourceTextureTarget = this._destTextureTarget; this._destTexture = tmp; this._destTextureTarget = tmpTarget; } } function nextPowerOfTwo(n: number) { n--; n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; n++; return n; } // All values are between 0 and 1 type Color = { r: number; g: number; b: number; a: number; }; type JumpFloodOutput = { format: "distance" | "seed-position"; renderTarget: "texture" | "screen"; }; namespace JumpFloodOutput { export const FOR_ANOTHER_STEP: JumpFloodOutput = { format: "seed-position", renderTarget: "texture", }; export const FOR_SCREEN: JumpFloodOutput = { format: "distance", renderTarget: "screen", }; }
the_stack
import { INodeProperties, } from 'n8n-workflow'; export const documentOperations: INodeProperties[] = [ { displayName: 'Operation', name: 'operation', type: 'options', displayOptions: { show: { resource: [ 'document', ], }, }, options: [ { name: 'Create', value: 'create', }, { name: 'Get', value: 'get', }, { name: 'Update', value: 'update', }, ], default: 'create', description: 'The operation to perform.', }, ]; export const documentFields: INodeProperties[] = [ /* -------------------------------------------------------------------------- */ /* document: create */ /* -------------------------------------------------------------------------- */ { displayName: 'Drive', name: 'driveId', type: 'options', typeOptions: { loadOptionsMethod: 'getDrives', }, default: 'myDrive', required: true, displayOptions: { show: { operation: [ 'create', ], resource: [ 'document', ], }, }, }, { displayName: 'Folder', name: 'folderId', type: 'options', typeOptions: { loadOptionsDependsOn: [ 'driveId', ], loadOptionsMethod: 'getFolders', }, default: '', required: true, displayOptions: { show: { operation: [ 'create', ], resource: [ 'document', ], }, }, }, { displayName: 'Title', name: 'title', type: 'string', default: '', required: true, displayOptions: { show: { operation: [ 'create', ], resource: [ 'document', ], }, }, }, /* -------------------------------------------------------------------------- */ /* document: get */ /* -------------------------------------------------------------------------- */ { displayName: 'Doc ID or URL', name: 'documentURL', type: 'string', required: true, displayOptions: { show: { operation: [ 'get', ], resource: [ 'document', ], }, }, default: '', description: 'The ID in the document URL (or just paste the whole URL).', }, { displayName: 'Simple', name: 'simple', type: 'boolean', displayOptions: { show: { operation: [ 'get', ], resource: [ 'document', ], }, }, default: true, description: 'When set to true the document text content will be used else the raw data.', }, /* -------------------------------------------------------------------------- */ /* document: update */ /* -------------------------------------------------------------------------- */ { displayName: 'Doc ID or URL', name: 'documentURL', type: 'string', required: true, displayOptions: { show: { operation: [ 'update', ], resource: [ 'document', ], }, }, default: '', description: 'The ID in the document URL (or just paste the whole URL).', }, { displayName: 'Simple', name: 'simple', type: 'boolean', displayOptions: { show: { operation: [ 'update', ], resource: [ 'document', ], }, }, default: true, description: 'When set to true a simplified version of the response will be used else the raw data.', }, { displayName: 'Actions', name: 'actionsUi', description: 'Actions applied to update the document.', type: 'fixedCollection', placeholder: 'Add Action', typeOptions: { multipleValues: true, }, default: { actionFields: [ { object: 'text', action: 'insert', locationChoice: 'endOfSegmentLocation', index: 0, text: '', }, ], }, displayOptions: { show: { operation: [ 'update', ], resource: [ 'document', ], }, }, options: [ { name: 'actionFields', displayName: 'Action Fields', values: [ // Object field { displayName: 'Object', name: 'object', type: 'options', options: [ { name: 'Footer', value: 'footer', }, { name: 'Header', value: 'header', }, { name: 'Named Range', value: 'namedRange', }, { name: 'Page Break', value: 'pageBreak', }, { name: 'Paragraph Bullets', value: 'paragraphBullets', }, { name: 'Positioned Object', value: 'positionedObject', }, { name: 'Table', value: 'table', }, { name: 'Table Column', value: 'tableColumn', }, { name: 'Table Row', value: 'tableRow', }, { name: 'Text', value: 'text', }, ], description: 'The update object.', default: 'text', }, // Action fields (depend on the Object field) { displayName: 'Action', name: 'action', type: 'options', options: [ { name: 'Find and replace text', value: 'replaceAll', }, { name: 'Insert', value: 'insert', }, ], displayOptions: { show: { object: [ 'text', ], }, }, description: 'The update action.', default: '', }, { displayName: 'Action', name: 'action', type: 'options', options: [ { name: 'Create', value: 'create', }, { name: 'Delete', value: 'delete', }, ], displayOptions: { show: { object: [ 'footer', 'header', 'namedRange', 'paragraphBullets', ], }, }, description: 'The update action.', default: '', }, { displayName: 'Action', name: 'action', type: 'options', options: [ { name: 'Delete', value: 'delete', }, { name: 'Insert', value: 'insert', }, ], displayOptions: { show: { object: [ 'tableColumn', 'tableRow', ], }, }, description: 'The update action.', default: '', }, { displayName: 'Action', name: 'action', type: 'options', options: [ { name: 'Insert', value: 'insert', }, ], displayOptions: { show: { object: [ 'pageBreak', 'table', ], }, }, description: 'The update action.', default: '', }, { displayName: 'Action', name: 'action', type: 'options', options: [ { name: 'Delete', value: 'delete', }, ], displayOptions: { show: { object: [ 'positionedObject', ], }, }, description: 'The update action.', default: '', }, // Shared Segment inputs for Create action (moved up for display purposes) { displayName: 'Insert Segment', name: 'insertSegment', type: 'options', options: [ { name: 'Header', value: 'header', }, { name: 'Body', value: 'body', }, { name: 'Footer', value: 'footer', }, ], description: 'The location where to create the object.', default: 'body', displayOptions: { show: { object: [ 'footer', 'header', 'paragraphBullets', 'namedRange', ], action: [ 'create', ], }, }, }, { displayName: 'Segment ID', name: 'segmentId', type: 'string', description: 'The ID of the header, footer or footnote. The <code>Document → Get</code> operation lists all segment IDs (make sure you disable the <code>simple</code> toggle).', default: '', displayOptions: { show: { object: [ 'footer', 'header', 'paragraphBullets', 'namedRange', ], action: [ 'create', ], }, hide: { insertSegment: [ 'body', ], }, }, }, // Inputs fields // create footer // create header { displayName: 'Index', name: 'index', type: 'number', description: 'The zero-based index, relative to the beginning of the specified segment.', default: 0, displayOptions: { show: { object: [ 'footer', 'header', ], action: [ 'create', ], }, }, }, // create named range { displayName: 'Name', name: 'name', type: 'string', description: 'The name of the Named Range. Names do not need to be unique.', default: '', displayOptions: { show: { object: [ 'namedRange', ], action: [ 'create', ], }, }, }, { displayName: 'Start Index', name: 'startIndex', type: 'number', description: 'The zero-based start index of this range.', default: 0, displayOptions: { show: { object: [ 'namedRange', ], action: [ 'create', ], }, }, }, { displayName: 'End Index', name: 'endIndex', type: 'number', description: 'The zero-based end index of this range.', default: 0, displayOptions: { show: { object: [ 'namedRange', ], action: [ 'create', ], }, }, }, // create bullets { displayName: 'Style', name: 'bulletPreset', type: 'options', options: [ { name: 'Bullet List', value: 'BULLET_DISC_CIRCLE_SQUARE', description: 'A bulleted list with a <code>DISC</code>, <code>CIRCLE</code> and <code>SQUARE</code> bullet glyph for the first 3 list nesting levels.', }, { name: 'Checkbox List', value: 'BULLET_CHECKBOX', description: 'A bulleted list with CHECKBOX bullet glyphs for all list nesting levels.', }, { name: 'Numbered List', value: 'NUMBERED_DECIMAL_NESTED', description: 'A numbered list with <code>DECIMAL</code> numeric glyphs separated by periods, where each nesting level uses the previous nesting level\'s glyph as a prefix. For example: 1., 1.1., 2., 2.2 .', }, ], description: 'The Preset pattern of bullet glyphs for list.', default: 'BULLET_DISC_CIRCLE_SQUARE', displayOptions: { show: { object: [ 'paragraphBullets', ], action: [ 'create', ], }, }, }, // delete footer { displayName: 'Footer ID', name: 'footerId', type: 'string', description: 'The ID of the footer to delete. To retrieve it, use the <code>get document</code> where you can find under <code>footers</code> attribute.', default: '', displayOptions: { show: { object: [ 'footer', ], action: [ 'delete', ], }, }, }, // delete header { displayName: 'Header ID', name: 'headerId', type: 'string', description: 'The ID of the header to delete. To retrieve it, use the <code>get document</code> where you can find under <code>headers</code> attribute.', default: '', displayOptions: { show: { object: [ 'header', ], action: [ 'delete', ], }, }, }, // delete named range { displayName: 'Specify range by', name: 'namedRangeReference', type: 'options', options: [ { name: 'ID', value: 'namedRangeId', }, { name: 'Name', value: 'name', }, ], description: 'The value determines which range or ranges to delete.', default: 'namedRangeId', displayOptions: { show: { object: [ 'namedRange', ], action: [ 'delete', ], }, }, }, { displayName: 'ID', name: 'value', type: 'string', description: 'The ID of the range.', default: '', displayOptions: { show: { object: [ 'namedRange', ], action: [ 'delete', ], namedRangeReference: [ 'namedRangeId', ], }, }, }, { displayName: 'Name', name: 'value', type: 'string', description: 'The name of the range.', default: '', displayOptions: { show: { object: [ 'namedRange', ], action: [ 'delete', ], namedRangeReference: [ 'name', ], }, }, }, // delete bullets (shared inputs added below) // delete positioned object { displayName: 'Object ID', name: 'objectId', type: 'string', description: 'The ID of the positioned object to delete (An object that is tied to a paragraph and positioned relative to its beginning), See the Google <a href="https://developers.google.com/docs/api/reference/rest/v1/PositionedObject">documentation</a>.', default: '', displayOptions: { show: { object: [ 'positionedObject', ], action: [ 'delete', ], }, }, }, // insert table column/row (shared inputs added below) // delete table column/row (shared inputs added below) // Shared Segment inputs for Insert action (moved up for display purposes) { displayName: 'Insert Segment', name: 'insertSegment', type: 'options', options: [ { name: 'Header', value: 'header', }, { name: 'Body', value: 'body', }, { name: 'Footer', value: 'footer', }, ], description: 'The location where to create the object.', default: 'body', displayOptions: { show: { object: [ 'pageBreak', 'table', 'tableColumn', 'tableRow', 'text', ], action: [ 'insert', ], }, }, }, { displayName: 'Segment ID', name: 'segmentId', type: 'string', description: 'The ID of the header, footer or footnote. The <code>Document → Get</code> operation lists all segment IDs (make sure you disable the <code>simple</code> toggle).', default: '', displayOptions: { show: { object: [ 'pageBreak', 'table', 'tableColumn', 'tableRow', 'text', ], action: [ 'insert', ], }, hide: { insertSegment: [ 'body', ], }, }, }, // insert page break { displayName: 'Insert Location', name: 'locationChoice', type: 'options', options: [ { name: 'At end of specific position', value: 'endOfSegmentLocation', description: 'Inserts the text at the end of a header, footer, footnote, or document body.', }, { name: 'At index', value: 'location', }, ], description: 'The location where the text will be inserted.', default: 'endOfSegmentLocation', displayOptions: { show: { object: [ 'pageBreak', ], action: [ 'insert', ], }, }, }, { displayName: 'Index', name: 'index', type: 'number', description: 'The zero-based index, relative to the beginning of the specified segment.', displayOptions: { show: { locationChoice: [ 'location', ], object: [ 'pageBreak', ], action: [ 'insert', ], }, }, typeOptions: { minValue: 1, }, default: 1, }, // insert table { displayName: 'Insert Location', name: 'locationChoice', type: 'options', options: [ { name: 'At end of specific position', value: 'endOfSegmentLocation', description: 'Inserts the text at the end of a header, footer, footnote, or document body.', }, { name: 'At index', value: 'location', }, ], description: 'The location where the text will be inserted.', default: 'endOfSegmentLocation', displayOptions: { show: { object: [ 'table', ], action: [ 'insert', ], }, }, }, { displayName: 'Index', name: 'index', type: 'number', description: 'The zero-based index, relative to the beginning of the specified segment (use index + 1 to refer to a table).', displayOptions: { show: { locationChoice: [ 'location', ], object: [ 'table', ], action: [ 'insert', ], }, }, default: 1, typeOptions: { minValue: 1, }, }, { displayName: 'Rows', name: 'rows', type: 'number', description: 'The number of rows in the table.', default: 0, displayOptions: { show: { object: [ 'table', ], action: [ 'insert', ], }, }, }, { displayName: 'Columns', name: 'columns', type: 'number', description: 'The number of columns in the table.', default: 0, displayOptions: { show: { object: [ 'table', ], action: [ 'insert', ], }, }, }, // insert text { displayName: 'Insert Location', name: 'locationChoice', type: 'options', options: [ { name: 'At end of specific position', value: 'endOfSegmentLocation', description: 'Inserts the text at the end of a header, footer, footnote, or document body.', }, { name: 'At index', value: 'location', }, ], description: 'The location where the text will be inserted.', default: 'endOfSegmentLocation', displayOptions: { show: { object: [ 'text', ], action: [ 'insert', ], }, }, }, { displayName: 'Index', name: 'index', type: 'number', typeOptions: { minValue: 1, }, description: 'The zero-based index, relative to the beginning of the specified segment.', displayOptions: { show: { locationChoice: [ 'location', ], object: [ 'text', ], action: [ 'insert', ], }, }, default: 1, }, { displayName: 'Text', name: 'text', type: 'string', description: 'The text to insert in the document.', default: '', displayOptions: { show: { object: [ 'text', ], action: [ 'insert', ], }, }, }, // replace all text { displayName: 'Old Text', name: 'text', type: 'string', description: 'The text to search for in the document.', default: '', displayOptions: { show: { object: [ 'text', ], action: [ 'replaceAll', ], }, }, }, { displayName: 'New Text', name: 'replaceText', type: 'string', description: 'The text that will replace the matched text.', default: '', displayOptions: { show: { object: [ 'text', ], action: [ 'replaceAll', ], }, }, }, { displayName: 'Match Case', name: 'matchCase', type: 'boolean', description: 'Indicates whether the search should respect case sensitivity.', default: false, displayOptions: { show: { object: [ 'text', ], action: [ 'replaceAll', ], }, }, }, // Shared Segment inputs for Delete action { displayName: 'Insert Segment', name: 'insertSegment', type: 'options', options: [ { name: 'Header', value: 'header', }, { name: 'Body', value: 'body', }, { name: 'Footer', value: 'footer', }, ], description: 'The location where to create the object.', default: 'body', displayOptions: { show: { object: [ 'paragraphBullets', 'tableColumn', 'tableRow', ], action: [ 'delete', ], }, }, }, { displayName: 'Segment ID', name: 'segmentId', type: 'string', description: 'The ID of the header, footer or footnote. The <code>Document → Get</code> operation lists all segment IDs (make sure you disable the <code>simple</code> toggle).', default: '', displayOptions: { show: { object: [ 'paragraphBullets', 'tableColumn', 'tableRow', ], action: [ 'delete', ], }, hide: { insertSegment: [ 'body', ], }, }, }, // Shared inputs for paragraph bullets { displayName: 'Start Index', name: 'startIndex', type: 'number', description: 'The zero-based start index of this range.', default: 0, displayOptions: { show: { object: [ 'paragraphBullets', ], }, }, }, { displayName: 'End Index', name: 'endIndex', type: 'number', description: 'The zero-based end index of this range.', default: 0, displayOptions: { show: { object: [ 'paragraphBullets', ], }, }, }, // Shared inputs for table column/row { displayName: 'Insert Position', name: 'insertPosition', type: 'options', options: [ { name: 'Before content at index', value: false, }, { name: 'After content at index', value: true, }, ], default: true, displayOptions: { show: { object: [ 'tableColumn', 'tableRow', ], action: [ 'insert', ], }, }, }, { displayName: 'Index', name: 'index', type: 'number', description: 'The zero-based index, relative to the beginning of the specified segment (use index + 1 to refer to a table).', default: 1, typeOptions: { minValue: 1, }, displayOptions: { show: { object: [ 'tableColumn', 'tableRow', ], }, }, }, { displayName: 'Row Index', name: 'rowIndex', type: 'number', description: 'The zero-based row index.', default: 0, displayOptions: { show: { object: [ 'tableColumn', 'tableRow', ], }, }, }, { displayName: 'Column Index', name: 'columnIndex', type: 'number', description: 'The zero-based column index.', default: 0, displayOptions: { show: { object: [ 'tableColumn', 'tableRow', ], }, }, }, ], }, ], }, { displayName: 'Update Fields', name: 'updateFields', type: 'fixedCollection', placeholder: 'Add Field', default: {}, displayOptions: { show: { operation: [ 'update', ], resource: [ 'document', ], }, }, options: [ { displayName: 'Write Control Object', name: 'writeControlObject', values: [ { displayName: 'Revision mode', name: 'control', type: 'options', options: [ { name: 'Target', value: 'targetRevisionId', description: 'Apply changes to the latest revision. Otherwise changes will not be processed.', }, { name: 'Required', value: 'requiredRevisionId', description: 'Apply changes to the provided revision while incorporating other collaborators\' changes. This mode is used for the recent revision, Otherwise changes will not be processed.', }, ], default: 'requiredRevisionId', description: 'Determines how the changes are applied to the revision.', }, { displayName: 'Revision ID', name: 'value', type: 'string', default: '', }, ], }, ], }, ];
the_stack
"use strict"; import * as proto from "./protocol"; import * as strings from "./base/common/strings"; import { ClientCapabilities, createConnection, Diagnostic, DidChangeConfigurationParams, DidChangeWatchedFilesParams, Files, IConnection, InitializeParams, InitializeResult, IPCMessageReader, IPCMessageWriter, Proposed, ProposedFeatures, PublishDiagnosticsParams, TextDocument, TextDocumentChangeEvent, TextDocumentIdentifier, TextDocuments } from 'vscode-languageserver'; import { PhpcsLinter } from "./linter"; import { PhpcsSettings } from "./settings"; import { StringResources as SR } from "./strings"; class PhpcsServer { private connection: IConnection; private documents: TextDocuments; private validating: Map<string, TextDocument>; // Cache the settings of all open documents private hasConfigurationCapability: boolean = false; private hasWorkspaceFolderCapability: boolean = false; private globalSettings: PhpcsSettings; private defaultSettings: PhpcsSettings = { enable: true, workspaceRoot: null, executablePath: null, composerJsonPath: null, standard: null, autoConfigSearch: true, showSources: false, showWarnings: true, ignorePatterns: [], warningSeverity: 5, errorSeverity: 5, }; private documentSettings: Map<string, Promise<PhpcsSettings>> = new Map(); /** * Class constructor. * * @return A new instance of the server. */ constructor() { this.validating = new Map(); this.connection = createConnection(ProposedFeatures.all, new IPCMessageReader(process), new IPCMessageWriter(process)); this.documents = new TextDocuments(); this.documents.listen(this.connection); this.connection.onInitialize(this.safeEventHandler(this.onInitialize)); this.connection.onInitialized(this.safeEventHandler(this.onDidInitialize)); this.connection.onDidChangeConfiguration(this.safeEventHandler(this.onDidChangeConfiguration)); this.connection.onDidChangeWatchedFiles(this.safeEventHandler(this.onDidChangeWatchedFiles)); this.documents.onDidChangeContent(this.safeEventHandler(this.onDidChangeDocument)); this.documents.onDidOpen(this.safeEventHandler(this.onDidOpenDocument)); this.documents.onDidSave(this.safeEventHandler(this.onDidSaveDocument)); this.documents.onDidClose(this.safeEventHandler(this.onDidCloseDocument)); } /** * Safely handle event notifications. * @param callback An event handler. */ private safeEventHandler(callback: (...args: any[]) => Promise<any>): (...args: any[]) => Promise<any> { return (...args: any[]): Promise<any> => { return callback.apply(this, args).catch((error: Error) => { this.connection.window.showErrorMessage(`phpcs: ${error.message}`); }); }; } /** * Handles server initialization. * * @param params The initialization parameters. * @return A promise of initialization result or initialization error. */ private async onInitialize(params: InitializeParams & Proposed.WorkspaceFoldersInitializeParams): Promise<InitializeResult> { let capabilities = params.capabilities as ClientCapabilities & Proposed.WorkspaceFoldersClientCapabilities & Proposed.ConfigurationClientCapabilities; this.hasWorkspaceFolderCapability = capabilities.workspace && !!capabilities.workspace.workspaceFolders; this.hasConfigurationCapability = capabilities.workspace && !!capabilities.workspace.configuration; return Promise.resolve<InitializeResult>({ capabilities: { textDocumentSync: this.documents.syncKind } }); } /** * Handles connection initialization completion. */ private async onDidInitialize(): Promise<void> { if (this.hasWorkspaceFolderCapability) { (this.connection.workspace as any).onDidChangeWorkspaceFolders((_event: Proposed.WorkspaceFoldersChangeEvent) => { this.connection.tracer.log('Workspace folder change event received'); }); } } /** * Handles configuration changes. * * @param params The changed configuration parameters. * @return void */ private async onDidChangeConfiguration(params: DidChangeConfigurationParams): Promise<void> { if (this.hasConfigurationCapability) { this.documentSettings.clear(); } else { this.globalSettings = { ...this.defaultSettings, ...params.settings.phpcs }; } await this.validateMany(this.documents.all()); } /** * Handles watched files changes. * * @param params The changed watched files parameters. * @return void */ private async onDidChangeWatchedFiles(_params: DidChangeWatchedFilesParams): Promise<void> { await this.validateMany(this.documents.all()); } /** * Handles opening of text documents. * * @param event The text document change event. * @return void */ private async onDidOpenDocument({ document }: TextDocumentChangeEvent): Promise<void> { await this.validateSingle(document); } /** * Handles saving of text documents. * * @param event The text document change event. * @return void */ private async onDidSaveDocument({ document }: TextDocumentChangeEvent): Promise<void> { await this.validateSingle(document); } /** * Handles closing of text documents. * * @param event The text document change event. * @return void */ private async onDidCloseDocument({ document }: TextDocumentChangeEvent): Promise<void> { const uri = document.uri; // Clear cached document settings. if (this.documentSettings.has(uri)) { this.documentSettings.delete(uri); } // Clear validating status. if (this.validating.has(uri)) { this.validating.delete(uri); } this.clearDiagnostics(uri); } /** * Handles changes of text documents. * * @param event The text document change event. * @return void */ private async onDidChangeDocument({ document }: TextDocumentChangeEvent): Promise<void> { await this.validateSingle(document); } /** * Start listening to requests. * * @return void */ public listen(): void { this.connection.listen(); } /** * Sends diagnostics computed for a given document to VSCode to render them in the * user interface. * * @param params The diagnostic parameters. */ private sendDiagnostics(params: PublishDiagnosticsParams): void { this.connection.sendDiagnostics(params); } /** * Clears the diagnostics computed for a given document. * * @param uri The document uri for which to clear the diagnostics. */ private clearDiagnostics(uri: string): void { this.connection.sendDiagnostics({ uri, diagnostics: [] }); } /** * Sends a notification for starting validation of a document. * * @param document The text document on which validation started. */ private sendStartValidationNotification(document: TextDocument): void { this.validating.set(document.uri, document); this.connection.sendNotification( proto.DidStartValidateTextDocumentNotification.type, { textDocument: TextDocumentIdentifier.create(document.uri) } ); this.connection.tracer.log(strings.format(SR.DidStartValidateTextDocument, document.uri)); } /** * Sends a notification for ending validation of a document. * * @param document The text document on which validation ended. */ private sendEndValidationNotification(document: TextDocument): void { this.validating.delete(document.uri); this.connection.sendNotification( proto.DidEndValidateTextDocumentNotification.type, { textDocument: TextDocumentIdentifier.create(document.uri) } ); this.connection.tracer.log(strings.format(SR.DidEndValidateTextDocument, document.uri)); } /** * Validate a single text document. * * @param document The text document to validate. * @return void */ public async validateSingle(document: TextDocument): Promise<void> { const { uri } = document; if (this.validating.has(uri) === false) { let settings = await this.getDocumentSettings(document); if (settings.enable) { let diagnostics: Diagnostic[] = []; this.sendStartValidationNotification(document); try { const phpcs = await PhpcsLinter.create(settings.executablePath); diagnostics = await phpcs.lint(document, settings); } catch(error) { throw new Error(this.getExceptionMessage(error, document)); } finally { this.sendEndValidationNotification(document); this.sendDiagnostics({ uri, diagnostics }); } } } } /** * Validate a list of text documents. * * @param documents The list of text documents to validate. * @return void */ public async validateMany(documents: TextDocument[]): Promise<void> { for (var i = 0, len = documents.length; i < len; i++) { await this.validateSingle(documents[i]); } } /** * Get the settings for the specified document. * * @param document The text document for which to get the settings. * @return A promise of PhpcsSettings. */ private async getDocumentSettings(document: TextDocument): Promise<PhpcsSettings> { const { uri } = document; let settings: Promise<PhpcsSettings>; if (this.hasConfigurationCapability) { if (this.documentSettings.has(uri)) { settings = this.documentSettings.get(uri); } else { const configurationItem: Proposed.ConfigurationItem = uri.match(/^untitled:/) ? {} : { scopeUri: uri }; settings = (this.connection.workspace as any).getConfiguration(configurationItem); this.documentSettings.set(uri, settings); } } else { settings = Promise.resolve(this.globalSettings); } return settings; } /** * Get the exception message from an exception object. * * @param exception The exception to parse. * @param document The document where the exception occurred. * @return string The exception message. */ private getExceptionMessage(exception: any, document: TextDocument): string { let message: string = null; if (typeof exception.message === 'string' || exception.message instanceof String) { message = <string>exception.message; message = message.replace(/\r?\n/g, ' '); if (/^ERROR: /.test(message)) { message = message.substr(5); } } else { message = strings.format(SR.UnknownErrorWhileValidatingTextDocument, Files.uriToFilePath(document.uri)); } return message; } } let server = new PhpcsServer(); server.listen();
the_stack
import { instantiateScript, createPrimeField } from '../../index'; import { StarkOptions } from '@guildofweavers/genstark'; import { Rescue } from './utils'; import { Logger, inline } from '../../lib/utils'; // RESCUE PARAMETERS // ================================================================================================ const modulus = 2n**64n - 21n * 2n**30n + 1n; const field = createPrimeField(modulus); const steps = 32; const alpha = 3n; const invAlpha = -6148914683720324437n; // MDS matrix and its inverse const mds = [ [18446744051160973310n, 18446744051160973301n], [ 4n, 13n] ]; // Key constant parameters const constants = [ 1908230773479027697n, 11775995824954138427n, 18345613653544031596n, 8765075832563166921n, 10398013025088720944n, 5494050611496560306n, 17002767073604012844n, 4907993559994152336n ]; // create rescue instance, and use it to calculate key constants for every round of computation const rescue = new Rescue(field, alpha, invAlpha, 2, steps, mds, constants); const keyStates = rescue.unrollConstants(); const { initialConstants, roundConstants } = rescue.groupConstants(keyStates); // STARK DEFINITION // ================================================================================================ const options: StarkOptions = { hashAlgorithm : 'blake2s256', extensionFactor : 16, exeQueryCount : 68, friQueryCount : 24, wasm : true }; const rescueStark = instantiateScript(Buffer.from(` define Rescue2x64 over prime field (${modulus}) { const alpha: 3; const inv_alpha: 6148914683720324437; const mds: [ [18446744051160973310, 18446744051160973301], [ 4, 13] ]; const inv_mds: [ [ 2049638227906774814, 6148914683720324439], [16397105823254198500, 12297829367440648875] ]; static roundConstants: [ cycle ${inline.vector(roundConstants[0])}, cycle ${inline.vector(roundConstants[1])}, cycle ${inline.vector(roundConstants[2])}, cycle ${inline.vector(roundConstants[3])} ]; secret input value1: element[1]; secret input value2: element[1]; transition 2 registers { for each (value1, value2) { init { yield [value1, value2]; } for steps [1..31] { S <- mds # $r^alpha + roundConstants[0..1]; yield mds # (/S)^(inv_alpha) + roundConstants[2..3]; } } } enforce 2 constraints { for each (value1, value2) { init { enforce [value1, value2] = $n; } for steps [1..31] { S <- mds # $r^alpha + roundConstants[0..1]; N <- (inv_mds # ($n - roundConstants[2..3]))^alpha; enforce S = N; } } } }`), options, new Logger(false)); // TESTING // ================================================================================================ // Generate proof that hashing 42 with Rescue results in 14354339131598895532 // set up inputs and assertions const inputs = buildInputs(42n); const assertions = [ { step: steps-1, register: 0, value: 14354339131598895532n } ]; // generate a proof const proof = rescueStark.prove(assertions, inputs); console.log('-'.repeat(20)); // verify that the prover knows the value that hashes to 14354339131598895532 rescueStark.verify(assertions, proof); console.log('-'.repeat(20)); console.log(`Proof size: ${Math.round(rescueStark.sizeOf(proof) / 1024 * 100) / 100} KB`); // HELPER FUNCTIONS // ================================================================================================ /** Pre-computes the first step of Rescue computation */ function buildInputs(value: bigint) { const r = [ field.add(value, initialConstants[0]), field.add(0n, initialConstants[1]) ]; // first step of round 1 let a0 = field.exp(r[0], invAlpha); let a1 = field.exp(r[1], invAlpha); return [ [field.add(field.add(field.mul(mds[0][0], a0), field.mul(mds[0][1], a1)), initialConstants[2])], [field.add(field.add(field.mul(mds[1][0], a0), field.mul(mds[1][1], a1)), initialConstants[3])] ]; } /* EXECUTION TRACES * ================================================================================================ * Execution traces of Rescue computation are shown below: * - on the left: the execution trace of running Sponge() method with input [42]; in this case, * a state is recorded after each step (2 per round). * - on the right: the execution trace from STARK computation; in this case, step 2 in a given round * is combined with step 1 from the following round as described in the whitepaper. So, the trace * can skip every other step. Also, the execution trace terminates after 1st step of round 32. * * ╒═══════════ Original Function ═════════════╕ ╒═════════════════ STARK ═══════════════════╕ * round step r0 r1 | r0 r1 * 0 1 42 0 | * 0 2 1908230773479027739 11775995824954138427 | * 1 1 6192394074115262567 6362103795149910654 | 6192394074115262567 6362103795149910654 <- STARK starts out with these inputs * 1 2 14235436695667447389 10212112854719144682 | * 2 1 4443483495863871585 18213808804803479104 | 4443483495863871585 18213808804803479104 * 2 2 7741183469403798391 6347331225803919751 | * 3 1 12298482428329212698 17330962085246333408 | 12298482428329212698 17330962085246333408 * 4 2 5625787762739911842 7298309140415770238 | * 5 1 8313646796226318584 11641010825224956624 | 8313646796226318584 11641010825224956624 * 5 2 3536971337043492177 6199877634490347893 | * 6 1 978482924564259844 1504772570823547853 | 978482924564259844 1504772570823547853 * 6 2 9587772738143780865 593371534470436793 | * 7 1 5186520612742714234 12963908037192828019 | 5186520612742714234 12963908037192828019 * 7 2 14958006020707970142 5812678940633129397 | * 8 1 13556844045322480200 9370255526245022324 | 13556844045322480200 9370255526245022324 * 8 2 5209123743309416556 3421448805653717044 | * 9 1 6826812100069596115 3767734035057720904 | 6826812100069596115 3767734035057720904 * 9 2 7004361282643535514 13669693348850263283 | * 10 1 9188856226247543083 3351687690081566017 | 9188856226247543083 3351687690081566017 * 10 2 7323944770063389994 12223102134895448980 | * 11 1 4083560747908219027 18221171377692901817 | 4083560747908219027 18221171377692901817 * 11 2 7318846094432971572 12454705956386970160 | * 12 1 15718390384883760212 12316572311146424020 | 15718390384883760212 12316572311146424020 * 12 2 1352768701059281571 3678128971630195068 | * 13 1 1125051307685663609 10573679192340848849 | 1125051307685663609 10573679192340848849 * 13 2 3918655941418559040 11114931694193189358 | * 14 1 17514012653621998088 16649558855481918050 | 17514012653621998088 16649558855481918050 * 14 2 15319837560709914379 9705703502808935406 | * 15 1 9391214203397792708 8948807049610907051 | 9391214203397792708 8948807049610907051 * 15 2 17039140040797699685 5648355597923301468 | * 16 1 11869417477045016900 16125602680661515208 | 11869417477045016900 16125602680661515208 * 16 2 10879959665900478916 9788819506433475326 | * 17 1 15622260264780797563 17676602026916942111 | 15622260264780797563 17676602026916942111 * 17 2 9970875907496364816 4018854804967493775 | * 18 1 11263866506403296395 3395909349124497933 | 11263866506403296395 3395909349124497933 * 18 2 12206504669047766550 2737018831357445192 | * 19 1 7436209647172616652 11095546667438737832 | 7436209647172616652 11095546667438737832 * 19 2 12951191624543726317 11756918128517485528 | * 20 1 13977911137029292561 7123382562034869052 | 13977911137029292561 7123382562034869052 * 20 2 10196137702945530755 16530008975547478480 | * 21 1 12765915320184852297 18222710437499261781 | 12765915320184852297 18222710437499261781 * 21 2 3510101432442295756 7047970939047430590 | * 22 1 4203432975434035702 17217054318931531174 | 4203432975434035702 17217054318931531174 * 22 2 6919336185017279297 10751714047033011969 | * 23 1 9513331167665760302 6625246843962557911 | 9513331167665760302 6625246843962557911 * 23 2 8322671683267467626 4448047256709285629 | * 24 1 700236991263439132 7713484789770087182 | 700236991263439132 7713484789770087182 * 24 2 10793159502592859380 3678186958707583345 | * 25 1 2053364846065995957 10256034168563840023 | 2053364846065995957 10256034168563840023 * 25 2 5936500212438068751 1562077346057657164 | * 26 1 790388693683446933 13255618738266494252 | 790388693683446933 13255618738266494252 * 26 2 15285257528619465884 12449196848526946550 | * 27 1 12872121840946251064 16031903000986157337 | 12872121840946251064 16031903000986157337 * 27 2 14878452572381778262 8518840370028919097 | * 28 1 17025530959440937859 17460181414067351157 | 17025530959440937859 17460181414067351157 * 28 2 1714977379946141684 14870879752778004505 | * 29 1 15097183929335660856 8195117861635325551 | 15097183929335660856 8195117861635325551 * 29 2 79198607169113554 6547868967680134508 | * 30 1 11005033986037753086 8639151511101212086 | 11005033986037753086 8639151511101212086 * 30 2 13306767687057932694 2408861729904106632 | * 31 1 427504626455762595 15713595349449078118 | 427504626455762595 15713595349449078118 * 31 2 893215822675986474 16013196806403095800 | * 32 1 14354339131598895532 13089448190414768876 | 14354339131598895532 13089448190414768876 <- STARK terminates 1 step earlier * 32 2 18174939043219985060 17194445737515289373 | */
the_stack
import { join } from 'path'; import { OutputtingProcess } from '../../OutputtingProcess'; import { Toolchain } from '../../Toolchain'; import { FileSystem } from '../file_system/FileSystem'; import { ChildLogger } from '../logging/child_logger'; import * as OutputChannelProcess from '../../OutputChannelProcess'; import { Configuration } from './Configuration'; /** * Configuration of Rust installed via Rustup */ export class Rustup { /** * A logger to log messages */ private logger: ChildLogger; /** * A path to Rust's installation root. * It is what `rustc --print=sysroot` returns. */ private pathToRustcSysRoot: string | undefined; /** * A path to Rust's source code. * It can be undefined if the component "rust-src" is not installed */ private pathToRustSourceCode: string | undefined; /** * Components received by invoking rustup */ private components: { [toolchain: string]: string[] | undefined }; /** * Toolchains received by invoking rustup */ private toolchains: Toolchain[]; /** * The toolchain chosen by the user */ private _userToolchain: Toolchain | undefined; /** * The nightly toolchain chosen by the user */ private _userNightlyToolchain: Toolchain | undefined; /** * Returns the executable of Rustup */ public static getRustupExecutable(): string { return 'rustup'; } /** * Creates a new instance of the class. * The method is asynchronous because it tries to find Rust's source code * @param pathToRustcSysRoot A path to Rust's installation root */ public static async create(logger: ChildLogger): Promise<Rustup | undefined> { const rustupExe = await FileSystem.findExecutablePath(Rustup.getRustupExecutable()); if (!rustupExe) { return undefined; } const rustup = new Rustup(logger); return rustup; } /** * Returns either the default toolchain or undefined if there are no installed toolchains */ public getDefaultToolchain(): Toolchain | undefined { const logger = this.logger.createChildLogger('getDefaultToolchain: '); const toolchain = this.toolchains.find(t => t.isDefault); if (!toolchain && this.toolchains.length !== 0) { logger.error(`no default toolchain; this.toolchains=${this.toolchains}`); } return toolchain; } /** * Returns the toolchains received from the last rustup invocation */ public getToolchains(): Toolchain[] { return this.toolchains; } public getNightlyToolchains(): Toolchain[] { return this.toolchains.filter(t => t.channel === 'nightly'); } /** * Checks if the toolchain is installed * @param toolchain The toolchain to check */ public isToolchainInstalled(toolchain: Toolchain): boolean { return this.toolchains.find(t => t.equals(toolchain)) !== undefined; } /** * Returns the path to Rust's source code */ public getPathToRustSourceCode(): string | undefined { return this.pathToRustSourceCode; } /** * Returns either the nightly toolchain chosen by the user or undefined */ public getUserNightlyToolchain(): Toolchain | undefined { if (this._userNightlyToolchain) { return this._userNightlyToolchain; } const defaultToolchain = this.getDefaultToolchain(); if (defaultToolchain && defaultToolchain.channel === 'nightly') { return defaultToolchain; } return undefined; } /** * Sets the new value of the nightly toolchain in the object and in the configuration * @param toolchain The new value */ public setUserNightlyToolchain(toolchain: Toolchain | undefined): void { if (this._userNightlyToolchain === toolchain) { return; } this._userNightlyToolchain = toolchain; updateUserConfigurationParameter(c => { c.nightlyToolchain = toolchain ? toolchain.toString(true, false) : null; }); } /** * Returns either the toolchain chosen by the user or the default or undefined */ public getUserToolchain(): Toolchain | undefined { return this._userToolchain || this.getDefaultToolchain(); } public setUserToolchain(toolchain: Toolchain | undefined): void { if (this._userToolchain === toolchain) { return; } this._userToolchain = toolchain; updateUserConfigurationParameter(c => { c.toolchain = toolchain ? toolchain.toString(true, false) : null; }); } /** * Requests rustup to install the specified toolchain * @param toolchain The toolchain to install * @return true if no error occurred and the toolchain has been installed otherwise false */ public async installToolchain(toolchain: string): Promise<boolean> { const logger = this.logger.createChildLogger(`installToolchain(toolchain=${toolchain}): `); const args = ['toolchain', 'install', toolchain]; const outputChannelName = `Rustup: Installing ${toolchain} toolchain`; const output = await Rustup.invokeWithOutputChannel(args, logger, outputChannelName); if (output === undefined) { logger.error(`output=${output}`); return false; } logger.debug(`output=${output}`); await this.updateToolchains(); if (this.toolchains.length === 0) { logger.error('this.toolchains.length === 0'); return false; } return true; } /** * Requests Rustup to install rust-src for the chosen toolchain * @return true if the installing succeeded, otherwise false */ public async installRustSrc(): Promise<boolean> { const logger = this.logger.createChildLogger('installRustSrc: '); if (!this._userToolchain) { logger.error('no toolchain has been chosen'); return false; } return await this.installComponent(this._userToolchain, 'rust-src'); } /** * Requests Rustup install RLS * @return true if no error occurred and RLS has been installed otherwise false */ public async installRls(): Promise<boolean> { const logger = this.logger.createChildLogger('installRls: '); const nightlyToolchain = this.getUserNightlyToolchain(); if (!nightlyToolchain) { logger.error('no nightly toolchain'); return false; } const isComponentInstalled: boolean = await this.installComponent( nightlyToolchain, Rustup.getRlsComponentName() ); return isComponentInstalled; } /** * Requests Rustup install rust-analysis * @return true if no error occurred and rust-analysis has been installed otherwise false */ public async installRustAnalysis(): Promise<boolean> { const logger = this.logger.createChildLogger('installRustAnalysis: '); const nightlyToolchain = this.getUserNightlyToolchain(); if (!nightlyToolchain) { logger.error('no nightly toolchain'); return false; } return await this.installComponent( nightlyToolchain, Rustup.getRustAnalysisComponentName() ); } /** * Requests rustup to give components list and saves them in the field `components` */ public async updateComponents(toolchain: Toolchain): Promise<void> { const logger = this.logger.createChildLogger(`updateComponents(${toolchain.toString(true, false)}): `); const toolchainAsString = toolchain.toString(true, false); this.components[toolchainAsString] = []; const rustupArgs = ['component', 'list', '--toolchain', toolchainAsString]; const stdoutData: string | undefined = await Rustup.invoke(rustupArgs, logger); if (!stdoutData) { logger.error(`stdoutData=${stdoutData}`); return; } this.components[toolchainAsString] = stdoutData.split('\n'); logger.debug(`components=${JSON.stringify(this.components[toolchainAsString])}`); } /** * Requests rustup to give toolchains list and saves it in the field `toolchains` */ public async updateToolchains(): Promise<void> { const logger = this.logger.createChildLogger('updateToolchains: '); this.toolchains = await Rustup.invokeGettingToolchains(logger); logger.debug(`this.toolchains=${JSON.stringify(this.toolchains)}`); } /** * Requests rustup to give the path to the sysroot of the specified toolchain * @param toolchain The toolchain to get the path to the sysroot for */ public async updateSysrootPath(toolchain: Toolchain): Promise<void> { this.pathToRustcSysRoot = undefined; const logger = this.logger.createChildLogger(`updateSysrootPath: toolchain=${toolchain}: `); if (!this.toolchains.find(t => t.equals(toolchain))) { logger.error('toolchain is not installed'); return; } this.pathToRustcSysRoot = await Rustup.invokeGettingSysrootPath(toolchain, logger); if (!this.pathToRustcSysRoot) { logger.error(`this.pathToRustcSysRoot=${this.pathToRustcSysRoot}`); } } /** * Checks if Rust's source code is installed at the expected path. * This method assigns either the expected path or undefined to the field `pathToRustSourceCode`, depending on if the expected path exists. * The method is asynchronous because it checks if the expected path exists */ public async updatePathToRustSourceCodePath(): Promise<void> { const logger = this.logger.createChildLogger('updatePathToRustSourceCodePath: '); this.pathToRustSourceCode = undefined; if (!this.pathToRustcSysRoot) { logger.error(`this.pathToRustcSysRoot=${this.pathToRustcSysRoot}`); return; } const pathToRustSourceCode = join(this.pathToRustcSysRoot, 'lib', 'rustlib', 'src', 'rust', 'src'); const isRustSourceCodeInstalled: boolean = await FileSystem.doesPathExist(pathToRustSourceCode); if (isRustSourceCodeInstalled) { this.pathToRustSourceCode = pathToRustSourceCode; } else { this.pathToRustSourceCode = undefined; } } /** * Requests Rustup give a list of components, parses it, checks if RLS is present in the list and returns if it is * @returns true if RLS can be installed otherwise false */ public canInstallRls(): boolean { const logger = this.logger.createChildLogger('canInstallRls: '); const nightlyToolchain = this.getUserNightlyToolchain(); if (!nightlyToolchain) { logger.error('no nightly toolchain'); return false; } const components = this.components[nightlyToolchain.toString(true, false)]; if (!components) { logger.error('no components'); return false; } const rlsComponent = components.find(component => component.startsWith(Rustup.getRlsComponentName())); if (!rlsComponent) { return false; } const rlsInstalled = rlsComponent.endsWith(Rustup.getSuffixForInstalledComponent()); if (rlsInstalled) { logger.error('RLS is already installed. The method should not have been called'); return false; } return true; } /** * Returns if RLS is installed * @return true if RLS is installed otherwise false */ public isRlsInstalled(): boolean { const logger = this.logger.createChildLogger('isRlsInstalled: '); const nightlyToolchain = this.getUserNightlyToolchain(); if (!nightlyToolchain) { logger.error('no nightly toolchain'); return false; } return this.isComponentInstalled(nightlyToolchain, Rustup.getRlsComponentName()); } /** * Returns whether "rust-analysis" is installed * @return The flag indicating whether "rust-analysis" is installed */ public isRustAnalysisInstalled(): boolean { const logger = this.logger.createChildLogger('isRustAnalysisInstalled: '); const nightlyToolchain = this.getUserNightlyToolchain(); if (!nightlyToolchain) { logger.error('no nightly toolchain'); return false; } return this.isComponentInstalled(nightlyToolchain, Rustup.getRustAnalysisComponentName()); } /** * Returns true if the component `rust-analysis` can be installed otherwise false. * If the component is already installed, the method returns false */ public canInstallRustAnalysis(): boolean { const logger = this.logger.createChildLogger('canInstallRustAnalysis: '); const nightlyToolchain = this.getUserNightlyToolchain(); if (!nightlyToolchain) { logger.error('no nightly toolchain'); return false; } const components = this.components[nightlyToolchain.toString(true, false)]; if (!components) { logger.error('no components'); return false; } const component: string | undefined = components.find(c => c.startsWith(Rustup.getRustAnalysisComponentName())); if (!component) { return false; } const componentInstalled: boolean = component.endsWith(Rustup.getSuffixForInstalledComponent()); return !componentInstalled; } /** * Returns the name of the component rust-analysis */ private static getRustAnalysisComponentName(): string { return 'rust-analysis'; } /** * Returns the name of the component RLS */ private static getRlsComponentName(): string { return 'rls'; } /** * Returns a suffix which any installed component ends with */ private static getSuffixForInstalledComponent(): string { return ' (installed)'; } /** * Invokes rustup to get the path to the sysroot of the specified toolchain. * Checks if the invocation exited successfully and returns the output of the invocation * @param toolchain The toolchain to get the path to the sysroot for * @param logger The logger to log messages * @return The output of the invocation if the invocation exited successfully otherwise undefined */ private static async invokeGettingSysrootPath( toolchain: Toolchain, logger: ChildLogger ): Promise<string | undefined> { const args = ['run', toolchain.toString(true, false), 'rustc', '--print', 'sysroot']; const output: string | undefined = await this.invoke(args, logger); if (!output) { return undefined; } return output.trim(); } private static async invokeGettingToolchains(logger: ChildLogger): Promise<Toolchain[]> { const functionLogger = logger.createChildLogger('invokeGettingToolchains: '); const output = await this.invoke(['toolchain', 'list'], functionLogger); if (!output) { functionLogger.error(`output=${output}`); return []; } const toolchainsAsStrings = output.trim().split('\n'); const toolchains = []; for (const toolchainAsString of toolchainsAsStrings) { const toolchain = Toolchain.parse(toolchainAsString); if (toolchain) { toolchains.push(toolchain); } } return toolchains; } /** * Invokes Rustup with specified arguments, checks if it exited successfully and returns its output * @param args Arguments to invoke Rustup with * @param logger The logger to log messages * @returns an output if invocation exited successfully otherwise undefined */ private static async invoke(args: string[], logger: ChildLogger): Promise<string | undefined> { const rustupExe = Rustup.getRustupExecutable(); const functionLogger = logger.createChildLogger(`invoke: rustupExe=${rustupExe}, args=${JSON.stringify(args)}: `); const result = await OutputtingProcess.spawn(rustupExe, args, undefined); if (!result.success) { functionLogger.error('failed'); return undefined; } if (result.exitCode !== 0) { functionLogger.error(`exited unexpectedly; exitCode=${result.exitCode}, stderrData=${result.stderrData}`); return undefined; } return result.stdoutData; } /** * Invokes rustup with the specified arguments, creates an output channel with the specified * name, writes output of the invocation and returns the output * @param args The arguments which to invoke rustup with * @param logger The logger to log messages * @param outputChannelName The name which to create an output channel with */ private static async invokeWithOutputChannel(args: string[], logger: ChildLogger, outputChannelName: string): Promise<string | undefined> { const functionLogger = logger.createChildLogger(`invokeWithOutputChannel(args=${JSON.stringify(args)}, outputChannelName=${outputChannelName}): `); const result = await OutputChannelProcess.create(this.getRustupExecutable(), args, undefined, outputChannelName); if (!result.success) { functionLogger.error('failed to start'); return undefined; } if (result.code !== 0) { functionLogger.error(`exited with not zero; code=${result.code}`); functionLogger.error('Beginning of stdout'); functionLogger.error(result.stdout); functionLogger.error('Ending of stdout'); functionLogger.error('Beginning of stderr'); functionLogger.error(result.stderr); functionLogger.error('Ending of stderr'); return undefined; } return result.stdout; } /** * Constructs a new instance of the class. * The constructor is private because creating a new instance should be done via the method `create` * @param logger A value for the field `logger` * @param pathToRustcSysRoot A value for the field `pathToRustcSysRoot` * @param pathToRustSourceCode A value for the field `pathToRustSourceCode` */ private constructor(logger: ChildLogger) { this.logger = logger; this.pathToRustcSysRoot = undefined; this.pathToRustSourceCode = undefined; this.components = {}; this.toolchains = []; this._userToolchain = getUserToolchain(); this._userNightlyToolchain = getUserNightlyToolchain(); } /** * Takes from the field `components` only installed components * @returns a list of installed components */ private getInstalledComponents(toolchain: Toolchain): string[] { const toolchainAsString = toolchain.toString(true, false); const components = this.components[toolchainAsString]; if (!components) { return []; } const installedComponents = components.filter(component => { return component.endsWith(Rustup.getSuffixForInstalledComponent()); }); return installedComponents; } /** * Returns true if the component is installed otherwise false * @param componentName The component's name */ private isComponentInstalled(toolchain: Toolchain, componentName: string): boolean { const installedComponents: string[] = this.getInstalledComponents(toolchain); const component: string | undefined = installedComponents.find(c => c.startsWith(componentName)); const isComponentInstalled = component !== undefined; return isComponentInstalled; } private async installComponent(toolchain: Toolchain, componentName: string): Promise<boolean> { const logger = this.logger.createChildLogger(`installComponent(${toolchain}, ${componentName}: `); if (this.isComponentInstalled(toolchain, componentName)) { logger.error(`${componentName} is already installed. The method should not have been called`); // We return true because the component is installed, but anyway it is an exceptional situation return true; } const args = ['component', 'add', componentName, '--toolchain', toolchain.toString(true, false)]; const stdoutData = await Rustup.invokeWithOutputChannel(args, logger, `Rustup: Installing ${componentName}`); if (stdoutData === undefined) { // Some error occurred. It is already logged // So we just need to notify a caller that the installation failed return false; } await this.updateComponents(toolchain); if (!this.isComponentInstalled(toolchain, componentName)) { logger.error(`${componentName} had been installed successfully, but then Rustup reported that the component was not installed. This should have not happened`); return false; } return true; } } function getUserConfiguration(): any { const configuration = Configuration.getConfiguration(); if (!configuration) { return undefined; } const rustupConfiguration = configuration.get<any>('rustup'); if (!rustupConfiguration) { return undefined; } return rustupConfiguration; } function getToolchainFromConfigurationParameter(parameter: string): Toolchain | undefined { const rustupConfiguration = getUserConfiguration(); if (!rustupConfiguration) { return undefined; } const toolchainAsString = rustupConfiguration[parameter]; if (!toolchainAsString) { return undefined; } const toolchain = Toolchain.parse(toolchainAsString); if (toolchain) { return toolchain; } else { return undefined; } } function getUserNightlyToolchain(): Toolchain | undefined { return getToolchainFromConfigurationParameter('nightlyToolchain'); } function getUserToolchain(): Toolchain | undefined { return getToolchainFromConfigurationParameter('toolchain'); } function updateUserConfigurationParameter(updateParameter: (c: any) => void): void { let configuration = getUserConfiguration(); if (!configuration) { configuration = {}; } updateParameter(configuration); Configuration.getConfiguration().update('rustup', configuration, true); }
the_stack
import * as http from "http"; import { IncomingMessage, ServerResponse } from "http"; import * as querystring from "querystring"; import * as url from "url"; import * as createUrlRegex from "url-regex"; import { publicCollectionId } from "../activitypub"; import { clientAddressedActivity } from "../activitypub"; import { discoverOutbox } from "../activitypub"; import { ASJsonLdProfileContentType } from "../activitystreams"; import { Activity, ASObject } from "../activitystreams"; import { createLogger } from "../logger"; import { ASLink, HasLinkPrefetchResult, LinkPrefetchFailure, LinkPrefetchResult, LinkPrefetchSuccess, } from "../types"; import { requestUrl } from "../util"; import { isProbablyAbsoluteUrl } from "../util"; import { createHttpOrHttpsRequest } from "../util"; import { debuglog, first } from "../util"; import { encodeHtmlEntities, readableToString, sendRequest } from "../util"; import { distbinBodyTemplate } from "./partials"; import { internalUrlRewriter } from "./url-rewriter"; const logger = createLogger(__filename); export const createHandler = ({ apiUrl, externalUrl, internalUrl, }: { apiUrl: string; externalUrl: string; internalUrl: string; }) => { return async (req: IncomingMessage, res: ServerResponse) => { switch (req.method.toLowerCase()) { // POST is form submission to create a new post case "post": const submission = await readableToString(req); // assuming application/x-www-form-urlencoded const formFields = querystring.parse(submission); const { attachment } = formFields; const inReplyTo = first(formFields.inReplyTo); const firstAttachment = first(attachment); if (firstAttachment && !isProbablyAbsoluteUrl(firstAttachment)) { throw new Error( "attachment must be a URL, but got " + firstAttachment, ); } const attachmentLink = await getAttachmentLinkForUrl(firstAttachment); let location; try { location = parseLocationFormFields(formFields); } catch (error) { logger.error(error); throw new Error("Error parsing location form fields"); } let attributedTo = {} as any; if (formFields["attributedTo.name"]) { attributedTo.name = formFields["attributedTo.name"]; } const attributedToUrl = first(formFields["attributedTo.url"]); if (attributedToUrl) { if (!isProbablyAbsoluteUrl(attributedToUrl)) { throw new Error( "Invalid non-URL value for attributedTo.url: " + attributedToUrl, ); } attributedTo.url = attributedToUrl; } if (Object.keys(attributedTo).length === 0) { attributedTo = undefined; } let tag; if (formFields.tag_csv) { tag = first(formFields.tag_csv) .split(",") .map((n: string) => { return { name: n.trim(), }; }); } const note: ASObject = Object.assign( { attachment: attachmentLink ? [attachmentLink] : undefined, content: first(formFields.content), generator: { name: "distbin-html", type: "Application", url: externalUrl, // @todo add .url of externalUrl }, tag, type: "Note", }, inReplyTo ? { inReplyTo } : {}, ); const unaddressedActivity: Activity = { "@context": "https://www.w3.org/ns/activitystreams", attributedTo, cc: [publicCollectionId, inReplyTo].filter(Boolean), location, object: note, type: "Create", }; debuglog("about to await clientAddressedActivity", { unaddressedActivity, }); const addressedActivity = await (async () => { const withClientAddresssing = await clientAddressedActivity( unaddressedActivity, 0, true, internalUrlRewriter(internalUrl, externalUrl), ); return { ...withClientAddresssing, bcc: [ ...(Array.isArray(withClientAddresssing.bcc) ? withClientAddresssing.bcc : [withClientAddresssing.bcc].filter(Boolean) ), // Add to bcc any absolute URLs in the content ...(note.content.match(createUrlRegex()) || []), ] } })(); debuglog("addressedActivity", addressedActivity); // submit to outbox // #TODO discover outbox URL debuglog("about to discoverOutbox", { apiUrl }); const outboxUrl = await discoverOutbox(apiUrl); debuglog("distbin-html/home is posting to outbox", { apiUrl, outboxUrl, }); const postToOutboxRequest = http.request( Object.assign( url.parse(internalUrlRewriter(internalUrl, externalUrl)(outboxUrl)), { headers: { "content-type": ASJsonLdProfileContentType, }, method: "post", }, ), ); postToOutboxRequest.write(JSON.stringify(addressedActivity)); const postToOutboxResponse = await sendRequest(postToOutboxRequest); switch (postToOutboxResponse.statusCode) { case 201: const postedLocation = postToOutboxResponse.headers.location; // handle form submission by posting to outbox res.writeHead(302, { location: postedLocation }); res.end(); break; case 500: res.writeHead(500); postToOutboxResponse.pipe(res); break; default: throw new Error("unexpected upstream response"); } break; // GET renders home page will all kinds of stuff case "get": const query = url.parse(req.url, true).query; // todo sanitize const safeInReplyToDefault = encodeHtmlEntities( first(query.inReplyTo) || "", ); const safeContentDefault = encodeHtmlEntities( first(query.content) || "", ); const safeAttributedToNameDefault = encodeHtmlEntities( first(query['attributedTo.name']) || "", ); const safeTitleDefault = encodeHtmlEntities(first(query.title) || ""); const safeAttachmentUrl = encodeHtmlEntities( first(query.attachment) || "", ); res.writeHead(200, { "content-type": "text/html", }); /* tslint:disable:max-line-length */ res.write( distbinBodyTemplate({ externalUrl })(` ${` <style> .post-form textarea { height: calc(100% - 14em - 8px); /* everything except the rest of this form */ min-height: 4em; } .post-form textarea, .post-form input, .post-form-show-more > summary { border: 0; font: inherit; padding: 1em; margin-bottom: 2px; /* account for webkit :focus glow overflow */ } .post-form-stretch { width: calc(100% + 2em); margin-left: -1em; margin-right: -1em; } .post-form .post-form-label-with-input { margin: 1em 0; } .post-form-show-more { } .post-form input[type=submit]:hover, .post-form summary { cursor: pointer; } .cursor-pointer:hover { cursor: pointer; } </style> <script> window.addGeolocation = function (addLocationEl) { var currentlyInsertedEl = addLocationEl; var locationInputGroup = addLocationEl.closest('.post-form-geolocation-input-group') if ( ! locationInputGroup) { throw new Error("addGeolocation must be called with an element inside a .post-form-geolocation-input-group") } // show loading indicator var gettingLocationEl = document.createElement('span'); gettingLocationEl.innerHTML = 'Getting Location...' addLocationEl.parentNode.replaceChild(gettingLocationEl, addLocationEl) currentlyInsertedEl = gettingLocationEl // ok now to request location navigator.geolocation.getCurrentPosition(success, failure); function success(position) { var coords= position.coords || {}; logger.log('Your position', position) var coordPropsToFormFields = { 'altitude': 'location.altitude', 'latitude': 'location.latitude', 'longitude': 'location.longitude', 'accuracy': 'location.radius', } var hiddenInputsToCreate = Object.keys(coordPropsToFormFields).map(function (coordProp) { var coordValue = coords[coordProp] if ( ! coordValue) return; var formFieldName = coordPropsToFormFields[coordProp] return { name: formFieldName, value: coordValue, } }).filter(Boolean); if (coords.altitude || coords.accuracy) { hiddenInputsToCreate.push({ name: 'location.units', value: 'm' }) } if (coords.altitude || coords.latitude || coords.longitude) { hiddenInputsToCreate.push({ name: 'location.accuracy', value: 95.0 }) } // update the form with hidden fields for this info hiddenInputsToCreate.forEach(insertOrReplaceInput); // replace loading indicator with 'undo' var undoElement = createUndoElement([ 'Clicking post will save your coordinates', (coords.latitude && coords.longitude) ? (' ('+coords.latitude+', '+coords.longitude+')') : '', '. Click here to undo.' ].join('')) gettingLocationEl.parentNode.replaceChild(undoElement, currentlyInsertedEl); currentlyInsertedEl = undoElement function createUndoElement(text) { var undoElement = document.createElement('a'); undoElement.innerHTML = text; undoElement.style.cursor = 'pointer'; undoElement.onclick = function (event) { // replace with the original addLocationEl that triggered everything undoElement.parentNode.replaceChild(addLocationEl, undoElement); currentlyInsertedEl = addLocationEl } return undoElement } function insertOrReplaceInput(inputInfo) { var name = inputInfo.name; var value = inputInfo.value; var input = document.createElement('input') input.type = 'hidden'; input.value = value; input.name = name; var oldInput = locationInputGroup.querySelector('input[name="'+name+'"]') if (oldInput) { oldInput.parentNode.replaceChild(input, oldInput); } else { // insert locationInputGroup.appendChild(input) } } } function failure(error) { logger.error("Error getting current position", error) var failureElement = document.createElement('a'); failureElement.style.cursor = 'pointer'; failureElement.innerHTML = ['Error getting geolocation', error.message].filter(Boolean).join(': ') failureElement.onclick = function (e) { currentlyInsertedEl.parentNode.replaceChild(addLocationEl, currentlyInsertedEl); currentlyInsertedEl = addLocationEl } currentlyInsertedEl.parentNode.replaceChild(failureElement, currentlyInsertedEl); currentlyInsertedEl = failureElement } } </script> <form class="post-form" method="post"> <input name="name" type="text" placeholder="Title (optional)" value="${safeTitleDefault}" class="post-form-stretch"></input> <textarea name="content" placeholder="Write anonymously, get feedback" class="post-form-stretch">${safeContentDefault}</textarea> <input name="inReplyTo" type="text" placeholder="replying to another URL? (optional)" value="${safeInReplyToDefault}" class="post-form-stretch"></input> <details class="post-form-show-more"> <summary class="post-form-stretch">More</summary> <input name="attributedTo.name" type="text" placeholder="What's your name? (optional)" class="post-form-stretch" value="${safeAttributedToNameDefault}"></input> <input name="attributedTo.url" type="text" placeholder="What's your URL? (optional)" class="post-form-stretch"></input> <input name="attachment" type="text" placeholder="Attachment URL (optional)" class="post-form-stretch" value="${safeAttachmentUrl}"></input> <input name="tag_csv" type="text" placeholder="Tags (comma-separated, optional)" class="post-form-stretch"></input> <div class="post-form-geolocation-input-group"> <input name="location.name" type="text" placeholder="Where are you?" class="post-form-stretch" /> <p> <a onclick="addGeolocation(this)" class="cursor-pointer">Add Your Geolocation</a> </p> </div> </details> <input type="submit" value="post" class="post-form-stretch" /> </form> <script> (function () { var contentInput = document.querySelector('.post-form *[name=content]') contentInput.scrollIntoViewIfNeeded(); contentInput.focus(); }()) </script> `} <details> <summary>or POST via API</summary> <pre>${encodeHtmlEntities(` curl -XPOST "${requestUrl(req)}activitypub/outbox" -d @- <<EOF { "@context": "https://www.w3.org/ns/activitystreams", "type": "Note", "content": "This is a note", "published": "2015-02-10T15:04:55Z", "cc": ["${publicCollectionId}"] } EOF`)} </pre> </details> `), ); /* tslint:enable:max-line-length */ res.end(); } }; }; function parseLocationFormFields(formFields: { [key: string]: string | string[]; }) { interface ILocation { type: string; name: string; units: string; altitude: number; latitude: number; longitude: number; accuracy: number; radius: number; } const location = { type: "Place" } as ILocation; const formFieldPrefix = "location."; const prefixed = (name: string) => `${formFieldPrefix}${name}`; const floatFieldNames: Array<keyof ILocation> = [ "latitude", "longitude", "altitude", "accuracy", "radius", ]; if (formFields[prefixed("name")]) { location.name = first(formFields["location.name"]); } if (formFields[prefixed("units")]) { location.units = first(formFields["location.units"]); } floatFieldNames.forEach((k: keyof ILocation) => { const fieldVal = first(formFields[prefixed(k)]); if (!fieldVal) { return; } location[k] = parseFloat(fieldVal); }); if (Object.keys(location).length === 1) { // there were no location formFields return; } return location; } async function getAttachmentLinkForUrl(attachment: string) { const attachmentLink: ASLink & HasLinkPrefetchResult = attachment && { href: attachment, type: "Link", }; let linkPrefetchResult: LinkPrefetchResult; if (attachment && attachmentLink) { // try to request the URL to figure out what kind of media type it responds with // then we can store a hint to future clients that render it let connectionError; let attachmentResponse; try { attachmentResponse = await sendRequest( createHttpOrHttpsRequest(Object.assign(url.parse(attachment))), ); } catch (error) { connectionError = error; logger.warn("Error prefetching attachment URL " + attachment); logger.error(error); } if (connectionError) { linkPrefetchResult = new LinkPrefetchFailure({ error: { message: connectionError.message, }, }); } else if (attachmentResponse.statusCode === 200) { const contentType = attachmentResponse.headers["content-type"]; if (contentType) { linkPrefetchResult = new LinkPrefetchSuccess({ published: new Date().toISOString(), supportedMediaTypes: [contentType], }); } } else { // no connection error, not 200, must be another linkPrefetchResult = new LinkPrefetchFailure({ error: { status: attachmentResponse.statusCode, }, }); } attachmentLink["https://distbin.com/ns/linkPrefetch"] = linkPrefetchResult; } return attachmentLink; } // function createMoreInfo(req, apiUrl) { // return ` // <h2>More Info/Links</h2> // <p> // This URL as application/json (<code>curl -H "Accept: application/json" ${requestUrl(req)}</code>) // </p> // <pre>${ // encodeHtmlEntities( // await readableToString( // await sendRequest( // http.request(apiUrl) // ) // ) // ) // }</pre> // ` // }
the_stack
import { Texture, Vector2, Vector3, Vector4 } from "three"; import { Light, AREA_LIGHT, SKY_LIGHT } from "../Light"; // threejs passthrough vertex shader for fullscreen quad export const pathTracingVertexShaderSrc = ` precision highp float; precision highp int; out vec2 vUv; void main() { vUv = uv; gl_Position = vec4( position, 1.0 ); } `; export const pathTracingFragmentShaderSrc = ` precision highp float; precision highp int; precision highp sampler2D; precision highp sampler3D; #define PI (3.1415926535897932384626433832795) #define PI_OVER_2 (1.57079632679489661923) #define PI_OVER_4 (0.785398163397448309616) #define INV_PI (1.0/PI) #define INV_2_PI (0.5/PI) #define INV_4_PI (0.25/PI) const vec3 BLACK = vec3(0,0,0); const vec3 WHITE = vec3(1.0,1.0,1.0); const int ShaderType_Brdf = 0; const int ShaderType_Phase = 1; const int ShaderType_Mixed = 2; const float MAX_RAY_LEN = 1500000.0f; in vec2 vUv; struct Camera { vec3 mFrom; vec3 mU, mV, mN; vec4 mScreen; // left, right, bottom, top vec2 mInvScreen; // 1/w, 1/h float mFocalDistance; float mApertureSize; float mIsOrtho; // 1 or 0 }; uniform Camera gCamera; struct Light { float mTheta; float mPhi; float mWidth; float mHalfWidth; float mHeight; float mHalfHeight; float mDistance; float mSkyRadius; vec3 mP; vec3 mTarget; vec3 mN; vec3 mU; vec3 mV; float mArea; float mAreaPdf; vec3 mColor; vec3 mColorTop; vec3 mColorMiddle; vec3 mColorBottom; int mT; }; const int NUM_LIGHTS = 2; uniform Light gLights[2]; uniform vec3 gClippedAaBbMin; uniform vec3 gClippedAaBbMax; uniform float gDensityScale; uniform float gStepSize; uniform float gStepSizeShadow; uniform sampler3D volumeTexture; uniform vec3 gInvAaBbMax; uniform int gNChannels; uniform int gShadingType; uniform vec3 gGradientDeltaX; uniform vec3 gGradientDeltaY; uniform vec3 gGradientDeltaZ; uniform float gInvGradientDelta; uniform float gGradientFactor; uniform float uShowLights; uniform vec3 flipVolume; // per channel // the luttexture is a 256x4 rgba texture // each row is a 256 element lookup table. uniform sampler2D gLutTexture; uniform vec4 gIntensityMax; uniform vec4 gIntensityMin; uniform float gOpacity[4]; uniform vec3 gEmissive[4]; uniform vec3 gDiffuse[4]; uniform vec3 gSpecular[4]; uniform float gGlossiness[4]; // compositing / progressive render uniform float uFrameCounter; uniform float uSampleCounter; uniform vec2 uResolution; uniform sampler2D tPreviousTexture; // from iq https://www.shadertoy.com/view/4tXyWN float rand( inout uvec2 seed ) { seed += uvec2(1); uvec2 q = 1103515245U * ( (seed >> 1U) ^ (seed.yx) ); uint n = 1103515245U * ( (q.x) ^ (q.y >> 3U) ); return float(n) * (1.0 / float(0xffffffffU)); } vec3 XYZtoRGB(vec3 xyz) { return vec3( 3.240479f*xyz[0] - 1.537150f*xyz[1] - 0.498535f*xyz[2], -0.969256f*xyz[0] + 1.875991f*xyz[1] + 0.041556f*xyz[2], 0.055648f*xyz[0] - 0.204043f*xyz[1] + 1.057311f*xyz[2] ); } // Used to convert from linear RGB to XYZ space const mat3 RGB_2_XYZ = (mat3( 0.4124564, 0.3575761, 0.1804375, 0.2126729, 0.7151522, 0.0721750, 0.0193339, 0.1191920, 0.9503041 )); vec3 RGBtoXYZ(vec3 rgb) { return rgb * RGB_2_XYZ; } vec3 getUniformSphereSample(in vec2 U) { float z = 1.f - 2.f * U.x; float r = sqrt(max(0.f, 1.f - z*z)); float phi = 2.f * PI * U.y; float x = r * cos(phi); float y = r * sin(phi); return vec3(x, y, z); } float SphericalPhi(in vec3 Wl) { float p = atan(Wl.z, Wl.x); return (p < 0.f) ? p + 2.f * PI : p; } float SphericalTheta(in vec3 Wl) { return acos(clamp(Wl.y, -1.f, 1.f)); } bool SameHemisphere(in vec3 Ww1, in vec3 Ww2) { return (Ww1.z * Ww2.z) > 0.0f; } vec2 getConcentricDiskSample(in vec2 U) { float r, theta; // Map 0..1 to -1..1 float sx = 2.0 * U.x - 1.0; float sy = 2.0 * U.y - 1.0; // Map square to (r,theta) // Handle degeneracy at the origin if (sx == 0.0 && sy == 0.0) { return vec2(0.0f, 0.0f); } // quadrants of disk if (sx >= -sy) { if (sx > sy) { r = sx; if (sy > 0.0) theta = sy/r; else theta = 8.0f + sy/r; } else { r = sy; theta = 2.0f - sx/r; } } else { if (sx <= sy) { r = -sx; theta = 4.0f - sy/r; } else { r = -sy; theta = 6.0f + sx/r; } } theta *= PI_OVER_4; return vec2(r*cos(theta), r*sin(theta)); } vec3 getCosineWeightedHemisphereSample(in vec2 U) { vec2 ret = getConcentricDiskSample(U); return vec3(ret.x, ret.y, sqrt(max(0.f, 1.f - ret.x * ret.x - ret.y * ret.y))); } struct Ray { vec3 m_O; vec3 m_D; float m_MinT, m_MaxT; }; vec3 rayAt(Ray r, float t) { return r.m_O + t*r.m_D; } Ray GenerateCameraRay(in Camera cam, in vec2 Pixel, in vec2 ApertureRnd) { // negating ScreenPoint.y flips the up/down direction. depends on whether you want pixel 0 at top or bottom // we could also have flipped mScreen and mInvScreen, or cam.mV? vec2 ScreenPoint = vec2( cam.mScreen.x + (cam.mInvScreen.x * Pixel.x), cam.mScreen.z + (cam.mInvScreen.y * Pixel.y) ); vec3 dxy = (ScreenPoint.x * cam.mU) + (-ScreenPoint.y * cam.mV); // orthographic camera ray: start at (camera pos + screen point), go in direction N // perspective camera ray: start at camera pos, go in direction (N + screen point) vec3 RayO = cam.mFrom + cam.mIsOrtho * dxy; vec3 RayD = normalize(cam.mN + (1.0 - cam.mIsOrtho) * dxy); if (cam.mApertureSize != 0.0f) { vec2 LensUV = cam.mApertureSize * getConcentricDiskSample(ApertureRnd); vec3 LI = cam.mU * LensUV.x + cam.mV * LensUV.y; RayO += LI; RayD = normalize((RayD * cam.mFocalDistance) - LI); } return Ray(RayO, RayD, 0.0, MAX_RAY_LEN); } bool IntersectBox(in Ray R, out float pNearT, out float pFarT) { vec3 invR = vec3(1.0f, 1.0f, 1.0f) / R.m_D; vec3 bottomT = invR * (vec3(gClippedAaBbMin.x, gClippedAaBbMin.y, gClippedAaBbMin.z) - R.m_O); vec3 topT = invR * (vec3(gClippedAaBbMax.x, gClippedAaBbMax.y, gClippedAaBbMax.z) - R.m_O); vec3 minT = min(topT, bottomT); vec3 maxT = max(topT, bottomT); float largestMinT = max(max(minT.x, minT.y), max(minT.x, minT.z)); float smallestMaxT = min(min(maxT.x, maxT.y), min(maxT.x, maxT.z)); pNearT = largestMinT; pFarT = smallestMaxT; return smallestMaxT > largestMinT; } // assume volume is centered at 0,0,0 so p spans -bounds to + bounds // transform p to range from 0,0,0 to 1,1,1 for volume texture sampling. // optionally invert axes vec3 PtoVolumeTex(vec3 p) { vec3 uvw = p*gInvAaBbMax + vec3(0.5, 0.5, 0.5); // if flipVolume = 1, uvw is unchanged. // if flipVolume = -1, uvw = 1 - uvw uvw = (flipVolume*(uvw - 0.5) + 0.5); return uvw; } const float UINT8_MAX = 1.0;//255.0; // strategy: sample up to 4 channels, and take the post-LUT maximum intensity as the channel that wins // we will return the unmapped raw intensity value from the volume so that other luts can be applied again later. float GetNormalizedIntensityMax4ch(in vec3 P, out int ch) { vec4 intensity = UINT8_MAX * texture(volumeTexture, PtoVolumeTex(P)); //intensity = (intensity - gIntensityMin) / (gIntensityMax - gIntensityMin); vec4 ilut = vec4(0.0, 0.0, 0.0, 0.0); // w in the lut texture is "opacity" ilut.x = texture(gLutTexture, vec2(intensity.x, 0.5/4.0)).w / 255.0; ilut.y = texture(gLutTexture, vec2(intensity.y, 1.5/4.0)).w / 255.0; ilut.z = texture(gLutTexture, vec2(intensity.z, 2.5/4.0)).w / 255.0; ilut.w = texture(gLutTexture, vec2(intensity.w, 3.5/4.0)).w / 255.0; float maxIn = 0.0; float iOut = 0.0; ch = 0; for (int i = 0; i < min(gNChannels, 4); ++i) { if (ilut[i] > maxIn) { maxIn = ilut[i]; ch = i; iOut = intensity[i]; } } //return maxIn; return iOut; } float GetNormalizedIntensity4ch(vec3 P, int ch) { vec4 intensity = UINT8_MAX * texture(volumeTexture, PtoVolumeTex(P)); // select channel float intensityf = intensity[ch]; //intensityf = (intensityf - gIntensityMin[ch]) / (gIntensityMax[ch] - gIntensityMin[ch]); //intensityf = texture(gLutTexture, vec2(intensityf, (0.5+float(ch))/4.0)).x; return intensityf; } // note that gInvGradientDelta is maxpixeldim of volume // gGradientDeltaX,Y,Z is 1/X,Y,Z of volume vec3 Gradient4ch(vec3 P, int ch) { vec3 Gradient; Gradient.x = (GetNormalizedIntensity4ch(P + (gGradientDeltaX), ch) - GetNormalizedIntensity4ch(P - (gGradientDeltaX), ch)) * gInvGradientDelta; Gradient.y = (GetNormalizedIntensity4ch(P + (gGradientDeltaY), ch) - GetNormalizedIntensity4ch(P - (gGradientDeltaY), ch)) * gInvGradientDelta; Gradient.z = (GetNormalizedIntensity4ch(P + (gGradientDeltaZ), ch) - GetNormalizedIntensity4ch(P - (gGradientDeltaZ), ch)) * gInvGradientDelta; return Gradient; } float GetOpacity(float NormalizedIntensity, int ch) { // apply lut float o = texture(gLutTexture, vec2(NormalizedIntensity, (0.5+float(ch))/4.0)).w / 255.0; float Intensity = o * gOpacity[ch]; return Intensity; } vec3 GetEmissionN(float NormalizedIntensity, int ch) { return gEmissive[ch]; } vec3 GetDiffuseN(float NormalizedIntensity, int ch) { vec4 col = texture(gLutTexture, vec2(NormalizedIntensity, (0.5+float(ch))/4.0)); //vec3 col = vec3(1.0, 1.0, 1.0); return col.xyz * gDiffuse[ch]; } vec3 GetSpecularN(float NormalizedIntensity, int ch) { return gSpecular[ch]; } float GetGlossinessN(float NormalizedIntensity, int ch) { return gGlossiness[ch]; } // a bsdf sample, a sample on a light source, and a randomly chosen light index struct LightingSample { float m_bsdfComponent; vec2 m_bsdfDir; vec2 m_lightPos; float m_lightComponent; float m_LightNum; }; LightingSample LightingSample_LargeStep(inout uvec2 seed) { return LightingSample( rand(seed), vec2(rand(seed), rand(seed)), vec2(rand(seed), rand(seed)), rand(seed), rand(seed) ); } // return a color xyz vec3 Light_Le(in Light light, in vec2 UV) { if (light.mT == 0) return RGBtoXYZ(light.mColor) / light.mArea; if (light.mT == 1) { if (UV.y > 0.0f) return RGBtoXYZ(mix(light.mColorMiddle, light.mColorTop, abs(UV.y))); else return RGBtoXYZ(mix(light.mColorMiddle, light.mColorBottom, abs(UV.y))); } return BLACK; } // return a color xyz vec3 Light_SampleL(in Light light, in vec3 P, out Ray Rl, out float Pdf, in LightingSample LS) { vec3 L = BLACK; Pdf = 0.0; vec3 Ro = vec3(0,0,0), Rd = vec3(0,0,1); if (light.mT == 0) { Ro = (light.mP + ((-0.5f + LS.m_lightPos.x) * light.mWidth * light.mU) + ((-0.5f + LS.m_lightPos.y) * light.mHeight * light.mV)); Rd = normalize(P - Ro); L = dot(Rd, light.mN) > 0.0f ? Light_Le(light, vec2(0.0f)) : BLACK; Pdf = abs(dot(Rd, light.mN)) > 0.0f ? dot(P-Ro, P-Ro) / (abs(dot(Rd, light.mN)) * light.mArea) : 0.0f; } else if (light.mT == 1) { Ro = light.mP + light.mSkyRadius * getUniformSphereSample(LS.m_lightPos); Rd = normalize(P - Ro); L = Light_Le(light, vec2(1.0f) - 2.0f * LS.m_lightPos); Pdf = pow(light.mSkyRadius, 2.0f) / light.mArea; } Rl = Ray(Ro, Rd, 0.0f, length(P - Ro)); return L; } // Intersect ray with light bool Light_Intersect(Light light, inout Ray R, out float T, out vec3 L, out float pPdf) { if (light.mT == 0) { // Compute projection float DotN = dot(R.m_D, light.mN); // Ray is coplanar with light surface if (DotN >= 0.0f) return false; // Compute hit distance T = (-light.mDistance - dot(R.m_O, light.mN)) / DotN; // Intersection is in ray's negative direction if (T < R.m_MinT || T > R.m_MaxT) return false; // Determine position on light vec3 Pl = rayAt(R, T); // Vector from point on area light to center of area light vec3 Wl = Pl - light.mP; // Compute texture coordinates vec2 UV = vec2(dot(Wl, light.mU), dot(Wl, light.mV)); // Check if within bounds of light surface if (UV.x > light.mHalfWidth || UV.x < -light.mHalfWidth || UV.y > light.mHalfHeight || UV.y < -light.mHalfHeight) return false; R.m_MaxT = T; //pUV = UV; if (DotN < 0.0f) L = RGBtoXYZ(light.mColor) / light.mArea; else L = BLACK; pPdf = dot(R.m_O-Pl, R.m_O-Pl) / (DotN * light.mArea); return true; } else if (light.mT == 1) { T = light.mSkyRadius; // Intersection is in ray's negative direction if (T < R.m_MinT || T > R.m_MaxT) return false; R.m_MaxT = T; vec2 UV = vec2(SphericalPhi(R.m_D) * INV_2_PI, SphericalTheta(R.m_D) * INV_PI); L = Light_Le(light, vec2(1.0f,1.0f) - 2.0f * UV); pPdf = pow(light.mSkyRadius, 2.0f) / light.mArea; //pUV = UV; return true; } return false; } float Light_Pdf(in Light light, in vec3 P, in vec3 Wi) { vec3 L; vec2 UV; float Pdf = 1.0f; Ray Rl = Ray(P, Wi, 0.0f, 100000.0f); if (light.mT == 0) { float T = 0.0f; if (!Light_Intersect(light, Rl, T, L, Pdf)) return 0.0f; return pow(T, 2.0f) / (abs(dot(light.mN, -Wi)) * light.mArea); } else if (light.mT == 1) { return pow(light.mSkyRadius, 2.0f) / light.mArea; } return 0.0f; } struct VolumeShader { int m_Type; // 0 = bsdf, 1 = phase vec3 m_Kd; // isotropic phase // xyz color vec3 m_R; // specular reflectance float m_Ior; float m_Exponent; vec3 m_Nn; vec3 m_Nu; vec3 m_Nv; }; // return a xyz color vec3 ShaderPhase_F(in VolumeShader shader, in vec3 Wo, in vec3 Wi) { return shader.m_Kd * INV_PI; } float ShaderPhase_Pdf(in VolumeShader shader, in vec3 Wo, in vec3 Wi) { return INV_4_PI; } vec3 ShaderPhase_SampleF(in VolumeShader shader, in vec3 Wo, out vec3 Wi, out float Pdf, in vec2 U) { Wi = getUniformSphereSample(U); Pdf = ShaderPhase_Pdf(shader, Wo, Wi); return ShaderPhase_F(shader, Wo, Wi); } // return a xyz color vec3 Lambertian_F(in VolumeShader shader, in vec3 Wo, in vec3 Wi) { return shader.m_Kd * INV_PI; } float Lambertian_Pdf(in VolumeShader shader, in vec3 Wo, in vec3 Wi) { //return abs(Wi.z)*INV_PI; return SameHemisphere(Wo, Wi) ? abs(Wi.z) * INV_PI : 0.0f; } // return a xyz color vec3 Lambertian_SampleF(in VolumeShader shader, in vec3 Wo, out vec3 Wi, out float Pdf, in vec2 U) { Wi = getCosineWeightedHemisphereSample(U); if (Wo.z < 0.0f) Wi.z *= -1.0f; Pdf = Lambertian_Pdf(shader, Wo, Wi); return Lambertian_F(shader, Wo, Wi); } vec3 SphericalDirection(in float SinTheta, in float CosTheta, in float Phi) { return vec3(SinTheta * cos(Phi), SinTheta * sin(Phi), CosTheta); } void Blinn_SampleF(in VolumeShader shader, in vec3 Wo, out vec3 Wi, out float Pdf, in vec2 U) { // Compute sampled half-angle vector wh for Blinn distribution float costheta = pow(U.x, 1.f / (shader.m_Exponent+1.0)); float sintheta = sqrt(max(0.f, 1.f - costheta*costheta)); float phi = U.y * 2.f * PI; vec3 wh = SphericalDirection(sintheta, costheta, phi); if (!SameHemisphere(Wo, wh)) wh = -wh; // Compute incident direction by reflecting about wh Wi = -Wo + 2.f * dot(Wo, wh) * wh; // Compute PDF for wi from Blinn distribution float blinn_pdf = ((shader.m_Exponent + 1.f) * pow(costheta, shader.m_Exponent)) / (2.f * PI * 4.f * dot(Wo, wh)); if (dot(Wo, wh) <= 0.f) blinn_pdf = 0.f; Pdf = blinn_pdf; } float Blinn_D(in VolumeShader shader, in vec3 wh) { float costhetah = abs(wh.z);//AbsCosTheta(wh); return (shader.m_Exponent+2.0) * INV_2_PI * pow(costhetah, shader.m_Exponent); } float Microfacet_G(in VolumeShader shader, in vec3 wo, in vec3 wi, in vec3 wh) { float NdotWh = abs(wh.z);//AbsCosTheta(wh); float NdotWo = abs(wo.z);//AbsCosTheta(wo); float NdotWi = abs(wi.z);//AbsCosTheta(wi); float WOdotWh = abs(dot(wo, wh)); return min(1.f, min((2.f * NdotWh * NdotWo / WOdotWh), (2.f * NdotWh * NdotWi / WOdotWh))); } vec3 Microfacet_F(in VolumeShader shader, in vec3 wo, in vec3 wi) { float cosThetaO = abs(wo.z);//AbsCosTheta(wo); float cosThetaI = abs(wi.z);//AbsCosTheta(wi); if (cosThetaI == 0.f || cosThetaO == 0.f) return BLACK; vec3 wh = wi + wo; if (wh.x == 0. && wh.y == 0. && wh.z == 0.) return BLACK; wh = normalize(wh); float cosThetaH = dot(wi, wh); vec3 F = WHITE;//m_Fresnel.Evaluate(cosThetaH); return shader.m_R * Blinn_D(shader, wh) * Microfacet_G(shader, wo, wi, wh) * F / (4.f * cosThetaI * cosThetaO); } vec3 ShaderBsdf_WorldToLocal(in VolumeShader shader, in vec3 W) { return vec3(dot(W, shader.m_Nu), dot(W, shader.m_Nv), dot(W, shader.m_Nn)); } vec3 ShaderBsdf_LocalToWorld(in VolumeShader shader, in vec3 W) { return vec3( shader.m_Nu.x * W.x + shader.m_Nv.x * W.y + shader.m_Nn.x * W.z, shader.m_Nu.y * W.x + shader.m_Nv.y * W.y + shader.m_Nn.y * W.z, shader.m_Nu.z * W.x + shader.m_Nv.z * W.y + shader.m_Nn.z * W.z); } float Blinn_Pdf(in VolumeShader shader, in vec3 Wo, in vec3 Wi) { vec3 wh = normalize(Wo + Wi); float costheta = abs(wh.z);//AbsCosTheta(wh); // Compute PDF for wi from Blinn distribution float blinn_pdf = ((shader.m_Exponent + 1.f) * pow(costheta, shader.m_Exponent)) / (2.f * PI * 4.f * dot(Wo, wh)); if (dot(Wo, wh) <= 0.0f) blinn_pdf = 0.0f; return blinn_pdf; } vec3 Microfacet_SampleF(in VolumeShader shader, in vec3 wo, out vec3 wi, out float Pdf, in vec2 U) { Blinn_SampleF(shader, wo, wi, Pdf, U); if (!SameHemisphere(wo, wi)) return BLACK; return Microfacet_F(shader, wo, wi); } float Microfacet_Pdf(in VolumeShader shader, in vec3 wo, in vec3 wi) { if (!SameHemisphere(wo, wi)) return 0.0f; return Blinn_Pdf(shader, wo, wi); } // return a xyz color vec3 ShaderBsdf_F(in VolumeShader shader, in vec3 Wo, in vec3 Wi) { vec3 Wol = ShaderBsdf_WorldToLocal(shader, Wo); vec3 Wil = ShaderBsdf_WorldToLocal(shader, Wi); vec3 R = vec3(0,0,0); R += Lambertian_F(shader, Wol, Wil); R += Microfacet_F(shader, Wol, Wil); return R; } float ShaderBsdf_Pdf(in VolumeShader shader, in vec3 Wo, in vec3 Wi) { vec3 Wol = ShaderBsdf_WorldToLocal(shader, Wo); vec3 Wil = ShaderBsdf_WorldToLocal(shader, Wi); float Pdf = 0.0f; Pdf += Lambertian_Pdf(shader, Wol, Wil); Pdf += Microfacet_Pdf(shader, Wol, Wil); return Pdf; } vec3 ShaderBsdf_SampleF(in VolumeShader shader, in LightingSample S, in vec3 Wo, out vec3 Wi, out float Pdf, in vec2 U) { vec3 Wol = ShaderBsdf_WorldToLocal(shader, Wo); vec3 Wil = vec3(0,0,0); vec3 R = vec3(0,0,0); if (S.m_bsdfComponent <= 0.5f) { Lambertian_SampleF(shader, Wol, Wil, Pdf, S.m_bsdfDir); } else { Microfacet_SampleF(shader, Wol, Wil, Pdf, S.m_bsdfDir); } Pdf += Lambertian_Pdf(shader, Wol, Wil); Pdf += Microfacet_Pdf(shader, Wol, Wil); R += Lambertian_F(shader, Wol, Wil); R += Microfacet_F(shader, Wol, Wil); Wi = ShaderBsdf_LocalToWorld(shader, Wil); //return vec3(1,1,1); return R; } // return a xyz color vec3 Shader_F(in VolumeShader shader, in vec3 Wo, in vec3 Wi) { if (shader.m_Type == 0) { return ShaderBsdf_F(shader, Wo, Wi); } else { return ShaderPhase_F(shader, Wo, Wi); } } float Shader_Pdf(in VolumeShader shader, in vec3 Wo, in vec3 Wi) { if (shader.m_Type == 0) { return ShaderBsdf_Pdf(shader, Wo, Wi); } else { return ShaderPhase_Pdf(shader, Wo, Wi); } } vec3 Shader_SampleF(in VolumeShader shader, in LightingSample S, in vec3 Wo, out vec3 Wi, out float Pdf, in vec2 U) { //return vec3(1,0,0); if (shader.m_Type == 0) { return ShaderBsdf_SampleF(shader, S, Wo, Wi, Pdf, U); } else { return ShaderPhase_SampleF(shader, Wo, Wi, Pdf, U); } } bool IsBlack(in vec3 v) { return (v.x==0.0 && v.y == 0.0 && v.z == 0.0); } float PowerHeuristic(float nf, float fPdf, float ng, float gPdf) { float f = nf * fPdf; float g = ng * gPdf; // The power heuristic is Veach's MIS balance heuristic except each component is being squared // balance heuristic would be f/(f+g) ...? return (f * f) / (f * f + g * g); } float MISContribution(float pdf1, float pdf2) { return PowerHeuristic(1.0f, pdf1, 1.0f, pdf2); } // "shadow ray" using gStepSizeShadow, test whether it can exit the volume or not bool DoesSecondaryRayScatterInVolume(inout Ray R, inout uvec2 seed) { float MinT; float MaxT; vec3 Ps; if (!IntersectBox(R, MinT, MaxT)) return false; MinT = max(MinT, R.m_MinT); MaxT = min(MaxT, R.m_MaxT); // delta (Woodcock) tracking float S = -log(rand(seed)) / gDensityScale; float Sum = 0.0f; float SigmaT = 0.0f; MinT += rand(seed) * gStepSizeShadow; int ch = 0; float intensity = 0.0; while (Sum < S) { Ps = rayAt(R, MinT); // R.m_O + MinT * R.m_D; if (MinT > MaxT) return false; intensity = GetNormalizedIntensityMax4ch(Ps, ch); SigmaT = gDensityScale * GetOpacity(intensity, ch); Sum += SigmaT * gStepSizeShadow; MinT += gStepSizeShadow; } return true; } int GetNearestLight(Ray R, out vec3 oLightColor, out vec3 Pl, out float oPdf) { int hit = -1; float T = 0.0f; Ray rayCopy = R; float pdf = 0.0f; for (int i = 0; i < 2; i++) { if (Light_Intersect(gLights[i], rayCopy, T, oLightColor, pdf)) { Pl = rayAt(R, T); hit = i; } } oPdf = pdf; return hit; } // return a XYZ color // Wo is direction from scatter point out toward incident ray direction // Wi goes toward light sample and is not necessarily perfect reflection of Wo // ^Wi ^N ^Wo // \\ | // // \\ | // // \\ | // // \\ | // // \\|// Pe = volume sample where scattering occurs // --------- vec3 EstimateDirectLight(int shaderType, float Density, int ch, in Light light, in LightingSample LS, in vec3 Wo, in vec3 Pe, in vec3 N, inout uvec2 seed) { vec3 Ld = BLACK, Li = BLACK, F = BLACK; vec3 diffuse = GetDiffuseN(Density, ch); vec3 specular = GetSpecularN(Density, ch); float glossiness = GetGlossinessN(Density, ch); // can N and Wo be coincident???? vec3 nu = normalize(cross(N, Wo)); vec3 nv = normalize(cross(N, nu)); // the IoR here is hard coded... and unused!!!! VolumeShader Shader = VolumeShader(shaderType, RGBtoXYZ(diffuse), RGBtoXYZ(specular), 2.5f, glossiness, N, nu, nv); float LightPdf = 1.0f, ShaderPdf = 1.0f; Ray Rl = Ray(vec3(0,0,0), vec3(0,0,1.0), 0.0, MAX_RAY_LEN); // Rl is ray from light toward Pe in volume, with a max traversal of the distance from Pe to Light sample pos. Li = Light_SampleL(light, Pe, Rl, LightPdf, LS); // Wi: negate ray direction: from volume scatter point toward light...? vec3 Wi = -Rl.m_D, P = vec3(0,0,0); // we will calculate two lighting contributions and combine them by MIS. F = Shader_F(Shader,Wo, Wi); ShaderPdf = Shader_Pdf(Shader, Wo, Wi); // get a lighting contribution along Rl; see if Rl would scatter in the volume or not if (!IsBlack(Li) && (ShaderPdf > 0.0f) && (LightPdf > 0.0f) && !DoesSecondaryRayScatterInVolume(Rl, seed)) { // ray from light can see through volume to Pe! float dotProd = 1.0; if (shaderType == ShaderType_Brdf){ // (use abs or clamp here?) dotProd = abs(dot(Wi, N)); } Ld += F * Li * dotProd * MISContribution(LightPdf, ShaderPdf) / LightPdf; } // get a lighting contribution by sampling nearest light from the scattering point F = Shader_SampleF(Shader, LS, Wo, Wi, ShaderPdf, LS.m_bsdfDir); if (!IsBlack(F) && (ShaderPdf > 0.0f)) { vec3 Pl = vec3(0,0,0); int n = GetNearestLight(Ray(Pe, Wi, 0.0f, 1000000.0f), Li, Pl, LightPdf); if (n > -1) { Light pLight = gLights[n]; LightPdf = Light_Pdf(pLight, Pe, Wi); if ((LightPdf > 0.0f) && !IsBlack(Li)) { Ray rr = Ray(Pl, normalize(Pe - Pl), 0.0f, length(Pe - Pl)); if (!DoesSecondaryRayScatterInVolume(rr, seed)) { float dotProd = 1.0; if (shaderType == ShaderType_Brdf){ // (use abs or clamp here?) dotProd = abs(dot(Wi, N)); } // note order of MIS params is swapped Ld += F * Li * dotProd * MISContribution(ShaderPdf, LightPdf) / ShaderPdf; } } } } return Ld; } // return a linear xyz color vec3 UniformSampleOneLight(int shaderType, float Density, int ch, in vec3 Wo, in vec3 Pe, in vec3 N, inout uvec2 seed) { //if (NUM_LIGHTS == 0) // return BLACK; // select a random light, a random 2d sample on light, and a random 2d sample on brdf LightingSample LS = LightingSample_LargeStep(seed); int WhichLight = int(floor(LS.m_LightNum * float(NUM_LIGHTS))); Light light = gLights[WhichLight]; return float(NUM_LIGHTS) * EstimateDirectLight(shaderType, Density, ch, light, LS, Wo, Pe, N, seed); } bool SampleScatteringEvent(inout Ray R, inout uvec2 seed, out vec3 Ps) { float MinT; float MaxT; if (!IntersectBox(R, MinT, MaxT)) return false; MinT = max(MinT, R.m_MinT); MaxT = min(MaxT, R.m_MaxT); // delta (Woodcock) tracking // notes, not necessarily coherent: // ray march along the ray's projected path and keep an average sigmaT value. // The distance is weighted by the intensity at each ray step sample. High intensity increases the apparent distance. // When the distance has become greater than the average sigmaT value given by -log(RandomFloat[0, 1]) / averageSigmaT // then that would be considered the interaction position. // sigmaT = sigmaA + sigmaS = absorption coeff + scattering coeff = extinction coeff // Beer-Lambert law: transmittance T(t) = exp(-sigmaT*t) where t is a distance! // importance sampling the exponential function to produce a free path distance S // the PDF is p(t) = sigmaT * exp(-sigmaT * t) // In a homogeneous volume, // S is the free-path distance = -ln(1-zeta)/sigmaT where zeta is a random variable // density scale = 0 => S --> 0..inf. Low density means randomly sized ray paths // density scale = inf => S --> 0. High density means short ray paths! // note that ln(x:0..1) is negative // here gDensityScale represents sigmaMax, a majorant of sigmaT // it is a parameter that should be set as close to the max extinction coefficient as possible. float S = -log(rand(seed)) / gDensityScale; float Sum = 0.0f; float SigmaT = 0.0f; // accumulated extinction along ray march // start: take one step now. MinT += rand(seed) * gStepSize; int ch = 0; float intensity = 0.0; // ray march until we have traveled S (or hit the maxT of the ray) while (Sum < S) { Ps = rayAt(R, MinT); // R.m_O + MinT * R.m_D; // if we exit the volume with no scattering if (MinT > MaxT) return false; intensity = GetNormalizedIntensityMax4ch(Ps, ch); SigmaT = gDensityScale * GetOpacity(intensity, ch); Sum += SigmaT * gStepSize; MinT += gStepSize; } // at this time, MinT - original MinT is the T transmission distance before a scatter event. // Ps is the point return true; } vec4 CalculateRadiance(inout uvec2 seed) { float r = rand(seed); //return vec4(r,0,0,1); vec3 Lv = BLACK, Li = BLACK; //Ray Re = Ray(vec3(0,0,0), vec3(0,0,1), 0.0, MAX_RAY_LEN); vec2 UV = vUv*uResolution + vec2(rand(seed), rand(seed)); Ray Re = GenerateCameraRay(gCamera, UV, vec2(rand(seed), rand(seed))); //return vec4(vUv, 0.0, 1.0); //return vec4(0.5*(Re.m_D + 1.0), 1.0); //return vec4(Re.m_D, 1.0); //Re.m_MinT = 0.0f; //Re.m_MaxT = MAX_RAY_LEN; vec3 Pe = vec3(0,0,0), Pl = vec3(0,0,0); float lpdf = 0.0; float alpha = 0.0; // find point Pe along ray Re if (SampleScatteringEvent(Re, seed, Pe)) { alpha = 1.0; // is there a light between Re.m_O and Pe? (ray's maxT is distance to Pe) // (test to see if area light was hit before volume.) int i = GetNearestLight(Ray(Re.m_O, Re.m_D, 0.0f, length(Pe - Re.m_O)), Li, Pl, lpdf); if (i > -1) { // set sample pixel value in frame estimate (prior to accumulation) return vec4(Li, 1.0); } int ch = 0; float D = GetNormalizedIntensityMax4ch(Pe, ch); // emission from volume Lv += RGBtoXYZ(GetEmissionN(D, ch)); vec3 gradient = Gradient4ch(Pe, ch); // send ray out from Pe toward light switch (gShadingType) { case ShaderType_Brdf: { Lv += UniformSampleOneLight(ShaderType_Brdf, D, ch, normalize(-Re.m_D), Pe, normalize(gradient), seed); break; } case ShaderType_Phase: { Lv += 0.5f * UniformSampleOneLight(ShaderType_Phase, D, ch, normalize(-Re.m_D), Pe, normalize(gradient), seed); break; } case ShaderType_Mixed: { //const float GradMag = GradientMagnitude(Pe, volumedata.gradientVolumeTexture[ch]) * (1.0/volumedata.intensityMax[ch]); float GradMag = length(gradient); float PdfBrdf = (1.0f - exp(-gGradientFactor * GradMag)); vec3 cls; // xyz color if (rand(seed) < PdfBrdf) { cls = UniformSampleOneLight(ShaderType_Brdf, D, ch, normalize(-Re.m_D), Pe, normalize(gradient), seed); } else { cls = 0.5f * UniformSampleOneLight(ShaderType_Phase, D, ch, normalize(-Re.m_D), Pe, normalize(gradient), seed); } Lv += cls; break; } } } else { // background color: // set Lv to a selected color based on environment light source? // if (uShowLights > 0.0) { // int n = GetNearestLight(Ray(Re.m_O, Re.m_D, 0.0f, 1000000.0f), Li, Pl, lpdf); // if (n > -1) // Lv = Li; // } //Lv = vec3(r,0,0); } // set sample pixel value in frame estimate (prior to accumulation) return vec4(Lv, alpha); } vec4 CumulativeMovingAverage(vec4 A, vec4 Ax, float N) { return A + ((Ax - A) / max((N), 1.0f)); } void main() { // seed for rand(seed) function uvec2 seed = uvec2(uFrameCounter, uFrameCounter + 1.0) * uvec2(gl_FragCoord); // perform path tracing and get resulting pixel color vec4 pixelColor = CalculateRadiance( seed ); vec4 previousColor = texture(tPreviousTexture, vUv); if (uSampleCounter < 1.0) { previousColor = vec4(0,0,0,0); } pc_fragColor = CumulativeMovingAverage(previousColor, pixelColor, uSampleCounter); } `; // Must match values in shader code above. const SHADERTYPE_BRDF = 0; // const ShaderType_Phase = 1; // const ShaderType_Mixed = 2; export const pathTracingUniforms = { tPreviousTexture: { type: "t", value: new Texture() }, uSampleCounter: { type: "f", value: 0.0 }, uFrameCounter: { type: "f", value: 1.0 }, uResolution: { type: "v2", value: new Vector2() }, /////////////////////////// gClippedAaBbMin: { type: "v3", value: new Vector3(0, 0, 0) }, gClippedAaBbMax: { type: "v3", value: new Vector3(1, 1, 1) }, gDensityScale: { type: "f", value: 50.0 }, gStepSize: { type: "f", value: 1.0 }, gStepSizeShadow: { type: "f", value: 1.0 }, gInvAaBbMax: { type: "v3", value: new Vector3() }, gNChannels: { type: "i", value: 0 }, gShadingType: { type: "i", value: SHADERTYPE_BRDF }, gGradientDeltaX: { type: "v3", value: new Vector3(0.01, 0, 0) }, gGradientDeltaY: { type: "v3", value: new Vector3(0, 0.01, 0) }, gGradientDeltaZ: { type: "v3", value: new Vector3(0, 0, 0.01) }, gInvGradientDelta: { type: "f", value: 0.0 }, // controls the amount of BRDF-like versus phase-function-like shading gGradientFactor: { type: "f", value: 0.25 }, gCamera: { value: { // Camera struct mFrom: new Vector3(), mU: new Vector3(), mV: new Vector3(), mN: new Vector3(), mScreen: new Vector4(), // left, right, bottom, top mInvScreen: new Vector2(), // 1/w, 1/h mFocalDistance: 0.0, mApertureSize: 0.0, mIsOrtho: 0.0, }, }, gLights: { value: [new Light(SKY_LIGHT), new Light(AREA_LIGHT)], }, volumeTexture: { type: "t", value: new Texture() }, // per channel gLutTexture: { type: "t", value: new Texture() }, gIntensityMax: { type: "v4", value: new Vector4(1, 1, 1, 1) }, gIntensityMin: { type: "v4", value: new Vector4(0, 0, 0, 0) }, gOpacity: { type: "1fv", value: [1, 1, 1, 1] }, gEmissive: { type: "v3v", value: [new Vector3(0, 0, 0), new Vector3(0, 0, 0), new Vector3(0, 0, 0), new Vector3(0, 0, 0)], }, gDiffuse: { type: "v3v", value: [new Vector3(1, 0, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1), new Vector3(1, 0, 1)], }, gSpecular: { type: "v3v", value: [new Vector3(0, 0, 0), new Vector3(0, 0, 0), new Vector3(0, 0, 0), new Vector3(0, 0, 0)], }, gGlossiness: { type: "1fv", value: [1, 1, 1, 1] }, uShowLights: { type: "f", value: 0 }, flipVolume: { type: "v3", value: new Vector3(1, 1, 1) }, };
the_stack
import { generic } from "./decorators" import { createClass, reflection } from "./helpers" import { getMetadata, getMetadataForApplyTo, getOwnMetadata, mergeMetadata } from "./storage" import { Class, DecoratorOption, DecoratorOptionId, DESIGN_PARAMETER_TYPE, DESIGN_RETURN_TYPE, DESIGN_TYPE, MethodReflection, ParameterPropertiesDecorator, ParameterPropertyReflection, ParameterReflection, PrivateDecorator, PropertyReflection, TypeDecorator, } from "./types" import { TypedReflection, WalkMemberContext } from "./walker" // --------------------------------------------------------------------- // // -------------------------- ADD DESIGN TYPE -------------------------- // // --------------------------------------------------------------------- // export function addsDesignTypes(meta: TypedReflection, ctx: WalkMemberContext): TypedReflection { const getType = (type: any, i: number) => type[i] === Array ? [Object] : type[i] if (meta.kind === "Method") { const returnType: any = Reflect.getOwnMetadata(DESIGN_RETURN_TYPE, ctx.target.prototype, meta.name) return { ...meta, returnType } } else if (reflection.isParameterProperties(meta)) { const parTypes: any[] = Reflect.getOwnMetadata(DESIGN_PARAMETER_TYPE, ctx.target) || [] return { ...meta, type: getType(parTypes, meta.index) } } else if (meta.kind === "Property") { const type: any = Reflect.getOwnMetadata(DESIGN_TYPE, ctx.target.prototype, meta.name) return { ...meta, type } } else if (meta.kind === "Parameter" && ctx.parent.kind === "Constructor") { const parTypes: any[] = Reflect.getOwnMetadata(DESIGN_PARAMETER_TYPE, ctx.target) || [] return { ...meta, type: getType(parTypes, meta.index) } } else if (meta.kind === "Parameter" && ctx.parent.kind === "Method") { const parTypes: any[] = Reflect.getOwnMetadata(DESIGN_PARAMETER_TYPE, ctx.target.prototype, ctx.parent.name) || [] return { ...meta, type: getType(parTypes, meta.index) } } else return meta } // --------------------------------------------------------------------- // // --------------------------- ADD DECORATORS -------------------------- // // --------------------------------------------------------------------- // export function addsDecorators(meta: TypedReflection, ctx: WalkMemberContext): TypedReflection { if (meta.kind === "Parameter") { // constructor metadata are not inheritable const decorators = ctx.parent.name === "constructor" ? getOwnMetadata(ctx.target, ctx.parent.name, meta.index) : getMetadata(ctx.target, ctx.parent.name, meta.index) return { ...meta, decorators: meta.decorators.concat(decorators) } } if (reflection.isParameterProperties(meta)) { // get copy own metadata of constructor const decorators = getOwnMetadata(ctx.target, "constructor", meta.index) // and also a copy of metadata of the property (using applyTo) .concat(...getMetadata(ctx.target, meta.name)) return { ...meta, decorators: meta.decorators.concat(decorators) } } if (meta.kind === "Method" || meta.kind === "Property") { const decorators = getMetadata(ctx.target, meta.name) return { ...meta, decorators: meta.decorators.concat(decorators) } } if (meta.kind === "Class") { const decorators = getMetadata(meta.type) return { ...meta, decorators: meta.decorators.concat(decorators) } } return meta } // --------------------------------------------------------------------- // // ----------------------- ADD APPLY-TO DECORATOR ---------------------- // // --------------------------------------------------------------------- // export function addsApplyToDecorator(meta: TypedReflection, ctx: WalkMemberContext) { if (reflection.isParameterProperties(meta)) { // get copy own metadata of constructor const decorators = getMetadataForApplyTo(ctx.target, "constructor", meta.index) // and also a copy of metadata of the property (using applyTo) .concat(...getMetadataForApplyTo(ctx.target, meta.name)) return { ...meta, decorators: meta.decorators.concat(decorators) } } if (meta.kind === "Method" || meta.kind === "Property") { const decorators = getMetadataForApplyTo(ctx.target, meta.name) return { ...meta, decorators: mergeMetadata(decorators, meta.decorators, false) } } if (meta.kind === "Class") { const rawDecorators = getMetadataForApplyTo(meta.type) const removedDecorators = rawDecorators.filter(x => { const option: Required<DecoratorOption> = x[DecoratorOptionId] return option.removeApplied }) const decorators = rawDecorators.filter(x => { const option: Required<DecoratorOption> = x[DecoratorOptionId] return !option.removeApplied }) const result = { ...meta, decorators: meta.decorators.concat(decorators) } if (removedDecorators.length > 0) result.removedDecorators = removedDecorators return result } return meta } // --------------------------------------------------------------------- // // ------------------ ADD DATA TYPE BY TYPE DECORATOR ------------------ // // --------------------------------------------------------------------- // // check if a generic type @type("T") function isGeneric(decorator: TypeDecorator) { const [singleType] = reflection.getTypeFromDecorator(decorator) return typeof singleType === "string" } // check if a dynamic type @type({ name: String, age: Number }) function isDynamic(decorator: TypeDecorator) { const [singleType] = reflection.getTypeFromDecorator(decorator) return typeof singleType === "object" } // check if a type with generic parameter @type(Type, "T", "U") function isTypeWithGenericParameter(decorator: TypeDecorator) { const [singleType] = reflection.getTypeFromDecorator(decorator) return typeof singleType === "function" && decorator.genericArguments.length > 0 } function setType(meta: MethodReflection | PropertyReflection | ParameterReflection | ParameterPropertyReflection, type: Class | Class[]) { if (meta.kind === "Method") return { returnType: type } return { type } } export function addsTypeByTypeDecorator(meta: TypedReflection, ctx: WalkMemberContext): TypedReflection { if (meta.kind === "Constructor" || meta.kind === "Class") return meta const decorator = meta.decorators.find((x: TypeDecorator): x is TypeDecorator => x.kind === "Override") if (!decorator) return meta if (isGeneric(decorator)) { const type = generic.getType(decorator, ctx.target)! return { ...meta, ...setType(meta, type) } } if (isDynamic(decorator)) { const [rawType, isArray] = reflection.getTypeFromDecorator(decorator) const type = createClass(rawType as {}) return { ...meta, ...setType(meta, isArray ? [type] : type as any) } } if (isTypeWithGenericParameter(decorator)) { const genericParams: any[] = decorator.genericArguments.map(x => { const s = Array.isArray(x) ? x[0] : x // if the generic arguments already a class then return immediately return typeof s === "function" ? x : generic.getType({ type: x, target: decorator.target }, ctx.target) } ) const [parentType, isArray] = reflection.getTypeFromDecorator(decorator) const dynType = createClass({}, { extends: parentType as any, genericParams }) const type = isArray ? [dynType] : dynType return { ...meta, ...setType(meta, type) } } const [type, isArray] = reflection.getTypeFromDecorator(decorator) return { ...meta, ...setType(meta, isArray ? [type] : type as any) } } // --------------------------------------------------------------------- // // ----------------------- ADD TYPE CLASSIFICATION --------------------- // // --------------------------------------------------------------------- // export function addsTypeClassification(meta: TypedReflection, ctx: WalkMemberContext): TypedReflection | undefined { const get = (type: any): "Class" | "Array" | "Primitive" | undefined => { if (type === undefined) return undefined else if (Array.isArray(type)) return "Array" else if (reflection.isCustomClass(type)) return "Class" else return "Primitive" } if (meta.kind === "Method") return { ...meta, typeClassification: get(meta.returnType) } else if (meta.kind === "Property" || meta.kind === "Parameter") return { ...meta, typeClassification: get(meta.type) } else if (meta.kind === "Class") return { ...meta, typeClassification: "Class" } return meta } // --------------------------------------------------------------------- // // ---------------------- ADD PARAMETER PROPERTIES --------------------- // // --------------------------------------------------------------------- // export function addsParameterProperties(meta: TypedReflection, ctx: WalkMemberContext): TypedReflection | undefined { if (reflection.isParameterProperties(meta) && ctx.parent.kind === "Class") { const isParamProp = ctx.parent.decorators.some((x: ParameterPropertiesDecorator) => x.type === "ParameterProperties") return !!isParamProp ? meta : undefined } return meta } // --------------------------------------------------------------------- // // --------------------------- REMOVE IGNORE --------------------------- // // --------------------------------------------------------------------- // export function removeIgnored(meta: TypedReflection, ctx: WalkMemberContext): TypedReflection | undefined { if (meta.kind === "Property" || meta.kind === "Method") { const decorator = meta.decorators.find((x: PrivateDecorator): x is PrivateDecorator => x.kind === "Ignore") return !decorator ? meta : undefined } return meta }
the_stack