text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import * as cairo from '@gi-types/cairo'; import * as Gdk from '@gi-types/gdk'; import * as GdkPixbuf from '@gi-types/gdkpixbuf'; import * as Gio from '@gi-types/gio'; import * as GLib from '@gi-types/glib'; import * as GObject from '@gi-types/gobject'; import * as Graphene from '@gi-types/graphene'; import * as Gsk from '@gi-types/gsk'; import * as Pango from '@gi-types/pango'; export const ACCESSIBLE_VALUE_UNDEFINED: number; export const BINARY_AGE: number; export const IM_MODULE_EXTENSION_POINT_NAME: string; export const INPUT_ERROR: number; export const INTERFACE_AGE: number; export const LEVEL_BAR_OFFSET_FULL: string; export const LEVEL_BAR_OFFSET_HIGH: string; export const LEVEL_BAR_OFFSET_LOW: string; export const MAJOR_VERSION: number; export const MAX_COMPOSE_LEN: number; export const MEDIA_FILE_EXTENSION_POINT_NAME: string; export const MICRO_VERSION: number; export const MINOR_VERSION: number; export const PAPER_NAME_A3: string; export const PAPER_NAME_A4: string; export const PAPER_NAME_A5: string; export const PAPER_NAME_B5: string; export const PAPER_NAME_EXECUTIVE: string; export const PAPER_NAME_LEGAL: string; export const PAPER_NAME_LETTER: string; export const PRINT_SETTINGS_COLLATE: string; export const PRINT_SETTINGS_DEFAULT_SOURCE: string; export const PRINT_SETTINGS_DITHER: string; export const PRINT_SETTINGS_DUPLEX: string; export const PRINT_SETTINGS_FINISHINGS: string; export const PRINT_SETTINGS_MEDIA_TYPE: string; export const PRINT_SETTINGS_NUMBER_UP: string; export const PRINT_SETTINGS_NUMBER_UP_LAYOUT: string; export const PRINT_SETTINGS_N_COPIES: string; export const PRINT_SETTINGS_ORIENTATION: string; export const PRINT_SETTINGS_OUTPUT_BASENAME: string; export const PRINT_SETTINGS_OUTPUT_BIN: string; export const PRINT_SETTINGS_OUTPUT_DIR: string; export const PRINT_SETTINGS_OUTPUT_FILE_FORMAT: string; export const PRINT_SETTINGS_OUTPUT_URI: string; export const PRINT_SETTINGS_PAGE_RANGES: string; export const PRINT_SETTINGS_PAGE_SET: string; export const PRINT_SETTINGS_PAPER_FORMAT: string; export const PRINT_SETTINGS_PAPER_HEIGHT: string; export const PRINT_SETTINGS_PAPER_WIDTH: string; export const PRINT_SETTINGS_PRINTER: string; export const PRINT_SETTINGS_PRINTER_LPI: string; export const PRINT_SETTINGS_PRINT_PAGES: string; export const PRINT_SETTINGS_QUALITY: string; export const PRINT_SETTINGS_RESOLUTION: string; export const PRINT_SETTINGS_RESOLUTION_X: string; export const PRINT_SETTINGS_RESOLUTION_Y: string; export const PRINT_SETTINGS_REVERSE: string; export const PRINT_SETTINGS_SCALE: string; export const PRINT_SETTINGS_USE_COLOR: string; export const PRINT_SETTINGS_WIN32_DRIVER_EXTRA: string; export const PRINT_SETTINGS_WIN32_DRIVER_VERSION: string; export const PRIORITY_RESIZE: number; export const STYLE_PROVIDER_PRIORITY_APPLICATION: number; export const STYLE_PROVIDER_PRIORITY_FALLBACK: number; export const STYLE_PROVIDER_PRIORITY_SETTINGS: number; export const STYLE_PROVIDER_PRIORITY_THEME: number; export const STYLE_PROVIDER_PRIORITY_USER: number; export const TEXT_VIEW_PRIORITY_VALIDATE: number; export const TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID: number; export const TREE_SORTABLE_UNSORTED_SORT_COLUMN_ID: number; export function accelerator_get_default_mod_mask(): Gdk.ModifierType; export function accelerator_get_label( accelerator_key: number, accelerator_mods: Gdk.ModifierType ): string; export function accelerator_get_label_with_keycode( display: Gdk.Display | null, accelerator_key: number, keycode: number, accelerator_mods: Gdk.ModifierType ): string; export function accelerator_name( accelerator_key: number, accelerator_mods: Gdk.ModifierType ): string; export function accelerator_name_with_keycode( display: Gdk.Display | null, accelerator_key: number, keycode: number, accelerator_mods: Gdk.ModifierType ): string; export function accelerator_parse( accelerator: string ): [boolean, number | null, Gdk.ModifierType | null]; export function accelerator_parse_with_keycode( accelerator: string, display?: Gdk.Display | null ): [boolean, number | null, number[] | null, Gdk.ModifierType | null]; export function accelerator_valid( keyval: number, modifiers: Gdk.ModifierType ): boolean; export function accessible_property_init_value( property: AccessibleProperty, value: any ): void; export function accessible_relation_init_value( relation: AccessibleRelation, value: any ): void; export function accessible_state_init_value( state: AccessibleState, value: any ): void; export function bitset_iter_init_at( set: Bitset, target: number ): [boolean, BitsetIter, number | null]; export function bitset_iter_init_first( set: Bitset ): [boolean, BitsetIter, number | null]; export function bitset_iter_init_last( set: Bitset ): [boolean, BitsetIter, number | null]; export function builder_error_quark(): GLib.Quark; export function check_version( required_major: number, required_minor: number, required_micro: number ): string | null; export function constraint_vfl_parser_error_quark(): GLib.Quark; export function css_parser_error_quark(): GLib.Quark; export function css_parser_warning_quark(): GLib.Quark; export function disable_setlocale(): void; export function distribute_natural_allocation( extra_space: number, n_requested_sizes: number, sizes: RequestedSize ): number; export function editable_delegate_get_property( object: GObject.Object, prop_id: number, value: any, pspec: GObject.ParamSpec ): boolean; export function editable_delegate_set_property( object: GObject.Object, prop_id: number, value: any, pspec: GObject.ParamSpec ): boolean; export function editable_install_properties( object_class: GObject.Object, first_prop: number ): number; export function file_chooser_error_quark(): GLib.Quark; export function get_binary_age(): number; export function get_debug_flags(): DebugFlags; export function get_default_language(): Pango.Language; export function get_interface_age(): number; export function get_locale_direction(): TextDirection; export function get_major_version(): number; export function get_micro_version(): number; export function get_minor_version(): number; export function hsv_to_rgb( h: number, s: number, v: number ): [number, number, number]; export function icon_theme_error_quark(): GLib.Quark; export function im_modules_init(): void; export function init(): void; export function init_check(): boolean; export function is_initialized(): boolean; export function native_get_for_surface(surface: Gdk.Surface): Native; export function paper_size_get_default(): string; export function paper_size_get_paper_sizes( include_custom: boolean ): PaperSize[]; export function param_spec_expression( name: string, nick: string, blurb: string, flags: GObject.ParamFlags ): GObject.ParamSpec; export function print_error_quark(): GLib.Quark; export function print_run_page_setup_dialog( parent: Window | null, page_setup: PageSetup | null, settings: PrintSettings ): PageSetup; export function print_run_page_setup_dialog_async( parent: Window | null, page_setup: PageSetup | null, settings: PrintSettings, done_cb: PageSetupDoneFunc ): void; export function recent_manager_error_quark(): GLib.Quark; export function render_activity( context: StyleContext, cr: cairo.Context, x: number, y: number, width: number, height: number ): void; export function render_arrow( context: StyleContext, cr: cairo.Context, angle: number, x: number, y: number, size: number ): void; export function render_background( context: StyleContext, cr: cairo.Context, x: number, y: number, width: number, height: number ): void; export function render_check( context: StyleContext, cr: cairo.Context, x: number, y: number, width: number, height: number ): void; export function render_expander( context: StyleContext, cr: cairo.Context, x: number, y: number, width: number, height: number ): void; export function render_focus( context: StyleContext, cr: cairo.Context, x: number, y: number, width: number, height: number ): void; export function render_frame( context: StyleContext, cr: cairo.Context, x: number, y: number, width: number, height: number ): void; export function render_handle( context: StyleContext, cr: cairo.Context, x: number, y: number, width: number, height: number ): void; export function render_icon( context: StyleContext, cr: cairo.Context, texture: Gdk.Texture, x: number, y: number ): void; export function render_layout( context: StyleContext, cr: cairo.Context, x: number, y: number, layout: Pango.Layout ): void; export function render_line( context: StyleContext, cr: cairo.Context, x0: number, y0: number, x1: number, y1: number ): void; export function render_option( context: StyleContext, cr: cairo.Context, x: number, y: number, width: number, height: number ): void; export function rgb_to_hsv( r: number, g: number, b: number ): [number, number, number]; export function set_debug_flags(flags: DebugFlags): void; export function show_uri( parent: Window | null, uri: string, timestamp: number ): void; export function show_uri_full( parent: Window | null, uri: string, timestamp: number, cancellable?: Gio.Cancellable | null ): void; export function show_uri_full_finish( parent: Window, result: Gio.AsyncResult ): boolean; export function test_accessible_assertion_message_role( domain: string, file: string, line: number, func: string, expr: string, accessible: Accessible, expected_role: AccessibleRole, actual_role: AccessibleRole ): void; export function test_accessible_has_property( accessible: Accessible, property: AccessibleProperty ): boolean; export function test_accessible_has_relation( accessible: Accessible, relation: AccessibleRelation ): boolean; export function test_accessible_has_role( accessible: Accessible, role: AccessibleRole ): boolean; export function test_accessible_has_state( accessible: Accessible, state: AccessibleState ): boolean; export function test_list_all_types(): GObject.GType[]; export function test_register_all_types(): void; export function test_widget_wait_for_draw(widget: Widget): void; export function tree_create_row_drag_content( tree_model: TreeModel, path: TreePath ): Gdk.ContentProvider; export function tree_get_row_drag_data( value: any ): [boolean, TreeModel | null, TreePath | null]; export function tree_row_reference_deleted( proxy: GObject.Object, path: TreePath ): void; export function tree_row_reference_inserted( proxy: GObject.Object, path: TreePath ): void; export function value_dup_expression(value: any): Expression | null; export function value_get_expression(value: any): Expression | null; export function value_set_expression(value: any, expression: Expression): void; export function value_take_expression( value: any, expression?: Expression | null ): void; export type AssistantPageFunc = (current_page: number) => number; export type CellAllocCallback = ( renderer: CellRenderer, cell_area: Gdk.Rectangle, cell_background: Gdk.Rectangle ) => boolean; export type CellCallback = (renderer: CellRenderer) => boolean; export type CellLayoutDataFunc = ( cell_layout: CellLayout, cell: CellRenderer, tree_model: TreeModel, iter: TreeIter ) => void; export type CustomAllocateFunc = ( widget: Widget, width: number, height: number, baseline: number ) => void; export type CustomFilterFunc<A = GObject.Object> = (item: A) => boolean; export type CustomMeasureFunc = ( widget: Widget, orientation: Orientation, for_size: number ) => void; export type CustomRequestModeFunc = (widget: Widget) => SizeRequestMode; export type DrawingAreaDrawFunc = ( drawing_area: DrawingArea, cr: cairo.Context, width: number, height: number ) => void; export type EntryCompletionMatchFunc = ( completion: EntryCompletion, key: string, iter: TreeIter ) => boolean; export type ExpressionNotify = () => void; export type FlowBoxCreateWidgetFunc<A = GObject.Object> = (item: A) => Widget; export type FlowBoxFilterFunc = (child: FlowBoxChild) => boolean; export type FlowBoxForeachFunc = (box: FlowBox, child: FlowBoxChild) => void; export type FlowBoxSortFunc = ( child1: FlowBoxChild, child2: FlowBoxChild ) => number; export type FontFilterFunc = ( family: Pango.FontFamily, face: Pango.FontFace ) => boolean; export type IconViewForeachFunc = (icon_view: IconView, path: TreePath) => void; export type ListBoxCreateWidgetFunc<A = GObject.Object> = (item: A) => Widget; export type ListBoxFilterFunc = (row: ListBoxRow) => boolean; export type ListBoxForeachFunc = (box: ListBox, row: ListBoxRow) => void; export type ListBoxSortFunc = (row1: ListBoxRow, row2: ListBoxRow) => number; export type ListBoxUpdateHeaderFunc = ( row: ListBoxRow, before?: ListBoxRow | null ) => void; export type MapListModelMapFunc<A = GObject.Object> = ( item: A ) => GObject.Object; export type MenuButtonCreatePopupFunc = (menu_button: MenuButton) => void; export type PageSetupDoneFunc = (page_setup: PageSetup) => void; export type PrintSettingsFunc = (key: string, value: string) => void; export type ScaleFormatValueFunc = (scale: Scale, value: number) => string; export type ShortcutFunc = ( widget: Widget, args?: GLib.Variant | null ) => boolean; export type TextCharPredicate = (ch: number) => boolean; export type TextTagTableForeach = (tag: TextTag) => void; export type TickCallback = ( widget: Widget, frame_clock: Gdk.FrameClock ) => boolean; export type TreeCellDataFunc = ( tree_column: TreeViewColumn, cell: CellRenderer, tree_model: TreeModel, iter: TreeIter ) => void; export type TreeIterCompareFunc = ( model: TreeModel, a: TreeIter, b: TreeIter ) => number; export type TreeListModelCreateModelFunc<A = GObject.Object> = ( item: A ) => Gio.ListModel | null; export type TreeModelFilterModifyFunc = ( model: TreeModel, iter: TreeIter, column: number ) => void; export type TreeModelFilterVisibleFunc = ( model: TreeModel, iter: TreeIter ) => boolean; export type TreeModelForeachFunc = ( model: TreeModel, path: TreePath, iter: TreeIter ) => boolean; export type TreeSelectionForeachFunc = ( model: TreeModel, path: TreePath, iter: TreeIter ) => void; export type TreeSelectionFunc = ( selection: TreeSelection, model: TreeModel, path: TreePath, path_currently_selected: boolean ) => boolean; export type TreeViewColumnDropFunc = ( tree_view: TreeView, column: TreeViewColumn, prev_column: TreeViewColumn, next_column: TreeViewColumn ) => boolean; export type TreeViewMappingFunc = (tree_view: TreeView, path: TreePath) => void; export type TreeViewRowSeparatorFunc = ( model: TreeModel, iter: TreeIter ) => boolean; export type TreeViewSearchEqualFunc = ( model: TreeModel, column: number, key: string, iter: TreeIter ) => boolean; export type WidgetActionActivateFunc = ( widget: Widget, action_name: string, parameter: GLib.Variant ) => void; export type TreeRowData = object | null; export namespace AccessibleAutocomplete { export const $gtype: GObject.GType<AccessibleAutocomplete>; } export enum AccessibleAutocomplete { NONE = 0, INLINE = 1, LIST = 2, BOTH = 3, } export namespace AccessibleInvalidState { export const $gtype: GObject.GType<AccessibleInvalidState>; } export enum AccessibleInvalidState { FALSE = 0, TRUE = 1, GRAMMAR = 2, SPELLING = 3, } export namespace AccessibleProperty { export const $gtype: GObject.GType<AccessibleProperty>; } export enum AccessibleProperty { AUTOCOMPLETE = 0, DESCRIPTION = 1, HAS_POPUP = 2, KEY_SHORTCUTS = 3, LABEL = 4, LEVEL = 5, MODAL = 6, MULTI_LINE = 7, MULTI_SELECTABLE = 8, ORIENTATION = 9, PLACEHOLDER = 10, READ_ONLY = 11, REQUIRED = 12, ROLE_DESCRIPTION = 13, SORT = 14, VALUE_MAX = 15, VALUE_MIN = 16, VALUE_NOW = 17, VALUE_TEXT = 18, } export namespace AccessibleRelation { export const $gtype: GObject.GType<AccessibleRelation>; } export enum AccessibleRelation { ACTIVE_DESCENDANT = 0, COL_COUNT = 1, COL_INDEX = 2, COL_INDEX_TEXT = 3, COL_SPAN = 4, CONTROLS = 5, DESCRIBED_BY = 6, DETAILS = 7, ERROR_MESSAGE = 8, FLOW_TO = 9, LABELLED_BY = 10, OWNS = 11, POS_IN_SET = 12, ROW_COUNT = 13, ROW_INDEX = 14, ROW_INDEX_TEXT = 15, ROW_SPAN = 16, SET_SIZE = 17, } export namespace AccessibleRole { export const $gtype: GObject.GType<AccessibleRole>; } export enum AccessibleRole { ALERT = 0, ALERT_DIALOG = 1, BANNER = 2, BUTTON = 3, CAPTION = 4, CELL = 5, CHECKBOX = 6, COLUMN_HEADER = 7, COMBO_BOX = 8, COMMAND = 9, COMPOSITE = 10, DIALOG = 11, DOCUMENT = 12, FEED = 13, FORM = 14, GENERIC = 15, GRID = 16, GRID_CELL = 17, GROUP = 18, HEADING = 19, IMG = 20, INPUT = 21, LABEL = 22, LANDMARK = 23, LEGEND = 24, LINK = 25, LIST = 26, LIST_BOX = 27, LIST_ITEM = 28, LOG = 29, MAIN = 30, MARQUEE = 31, MATH = 32, METER = 33, MENU = 34, MENU_BAR = 35, MENU_ITEM = 36, MENU_ITEM_CHECKBOX = 37, MENU_ITEM_RADIO = 38, NAVIGATION = 39, NONE = 40, NOTE = 41, OPTION = 42, PRESENTATION = 43, PROGRESS_BAR = 44, RADIO = 45, RADIO_GROUP = 46, RANGE = 47, REGION = 48, ROW = 49, ROW_GROUP = 50, ROW_HEADER = 51, SCROLLBAR = 52, SEARCH = 53, SEARCH_BOX = 54, SECTION = 55, SECTION_HEAD = 56, SELECT = 57, SEPARATOR = 58, SLIDER = 59, SPIN_BUTTON = 60, STATUS = 61, STRUCTURE = 62, SWITCH = 63, TAB = 64, TABLE = 65, TAB_LIST = 66, TAB_PANEL = 67, TEXT_BOX = 68, TIME = 69, TIMER = 70, TOOLBAR = 71, TOOLTIP = 72, TREE = 73, TREE_GRID = 74, TREE_ITEM = 75, WIDGET = 76, WINDOW = 77, } export namespace AccessibleSort { export const $gtype: GObject.GType<AccessibleSort>; } export enum AccessibleSort { NONE = 0, ASCENDING = 1, DESCENDING = 2, OTHER = 3, } export namespace AccessibleState { export const $gtype: GObject.GType<AccessibleState>; } export enum AccessibleState { BUSY = 0, CHECKED = 1, DISABLED = 2, EXPANDED = 3, HIDDEN = 4, INVALID = 5, PRESSED = 6, SELECTED = 7, } export namespace AccessibleTristate { export const $gtype: GObject.GType<AccessibleTristate>; } export enum AccessibleTristate { FALSE = 0, TRUE = 1, MIXED = 2, } export namespace Align { export const $gtype: GObject.GType<Align>; } export enum Align { FILL = 0, START = 1, END = 2, CENTER = 3, BASELINE = 4, } export namespace ArrowType { export const $gtype: GObject.GType<ArrowType>; } export enum ArrowType { UP = 0, DOWN = 1, LEFT = 2, RIGHT = 3, NONE = 4, } export namespace AssistantPageType { export const $gtype: GObject.GType<AssistantPageType>; } export enum AssistantPageType { CONTENT = 0, INTRO = 1, CONFIRM = 2, SUMMARY = 3, PROGRESS = 4, CUSTOM = 5, } export namespace BaselinePosition { export const $gtype: GObject.GType<BaselinePosition>; } export enum BaselinePosition { TOP = 0, CENTER = 1, BOTTOM = 2, } export namespace BorderStyle { export const $gtype: GObject.GType<BorderStyle>; } export enum BorderStyle { NONE = 0, HIDDEN = 1, SOLID = 2, INSET = 3, OUTSET = 4, DOTTED = 5, DASHED = 6, DOUBLE = 7, GROOVE = 8, RIDGE = 9, } export class BuilderError extends GLib.Error { static $gtype: GObject.GType<BuilderError>; constructor(options: { message: string; code: number }); constructor(copy: BuilderError); // Properties static INVALID_TYPE_FUNCTION: number; static UNHANDLED_TAG: number; static MISSING_ATTRIBUTE: number; static INVALID_ATTRIBUTE: number; static INVALID_TAG: number; static MISSING_PROPERTY_VALUE: number; static INVALID_VALUE: number; static VERSION_MISMATCH: number; static DUPLICATE_ID: number; static OBJECT_TYPE_REFUSED: number; static TEMPLATE_MISMATCH: number; static INVALID_PROPERTY: number; static INVALID_SIGNAL: number; static INVALID_ID: number; static INVALID_FUNCTION: number; // Members static quark(): GLib.Quark; } export namespace ButtonsType { export const $gtype: GObject.GType<ButtonsType>; } export enum ButtonsType { NONE = 0, OK = 1, CLOSE = 2, CANCEL = 3, YES_NO = 4, OK_CANCEL = 5, } export namespace CellRendererAccelMode { export const $gtype: GObject.GType<CellRendererAccelMode>; } export enum CellRendererAccelMode { GTK = 0, OTHER = 1, } export namespace CellRendererMode { export const $gtype: GObject.GType<CellRendererMode>; } export enum CellRendererMode { INERT = 0, ACTIVATABLE = 1, EDITABLE = 2, } export namespace ConstraintAttribute { export const $gtype: GObject.GType<ConstraintAttribute>; } export enum ConstraintAttribute { NONE = 0, LEFT = 1, RIGHT = 2, TOP = 3, BOTTOM = 4, START = 5, END = 6, WIDTH = 7, HEIGHT = 8, CENTER_X = 9, CENTER_Y = 10, BASELINE = 11, } export namespace ConstraintRelation { export const $gtype: GObject.GType<ConstraintRelation>; } export enum ConstraintRelation { LE = -1, EQ = 0, GE = 1, } export namespace ConstraintStrength { export const $gtype: GObject.GType<ConstraintStrength>; } export enum ConstraintStrength { REQUIRED = 1001001000, STRONG = 1000000000, MEDIUM = 1000, WEAK = 1, } export class ConstraintVflParserError extends GLib.Error { static $gtype: GObject.GType<ConstraintVflParserError>; constructor(options: { message: string; code: number }); constructor(copy: ConstraintVflParserError); // Properties static SYMBOL: number; static ATTRIBUTE: number; static VIEW: number; static METRIC: number; static PRIORITY: number; static RELATION: number; // Members static quark(): GLib.Quark; } export namespace CornerType { export const $gtype: GObject.GType<CornerType>; } export enum CornerType { TOP_LEFT = 0, BOTTOM_LEFT = 1, TOP_RIGHT = 2, BOTTOM_RIGHT = 3, } export class CssParserError extends GLib.Error { static $gtype: GObject.GType<CssParserError>; constructor(options: { message: string; code: number }); constructor(copy: CssParserError); // Properties static FAILED: number; static SYNTAX: number; static IMPORT: number; static NAME: number; static UNKNOWN_VALUE: number; } export namespace CssParserWarning { export const $gtype: GObject.GType<CssParserWarning>; } export enum CssParserWarning { DEPRECATED = 0, SYNTAX = 1, UNIMPLEMENTED = 2, } export namespace DeleteType { export const $gtype: GObject.GType<DeleteType>; } export enum DeleteType { CHARS = 0, WORD_ENDS = 1, WORDS = 2, DISPLAY_LINES = 3, DISPLAY_LINE_ENDS = 4, PARAGRAPH_ENDS = 5, PARAGRAPHS = 6, WHITESPACE = 7, } export namespace DirectionType { export const $gtype: GObject.GType<DirectionType>; } export enum DirectionType { TAB_FORWARD = 0, TAB_BACKWARD = 1, UP = 2, DOWN = 3, LEFT = 4, RIGHT = 5, } export namespace EditableProperties { export const $gtype: GObject.GType<EditableProperties>; } export enum EditableProperties { PROP_TEXT = 0, PROP_CURSOR_POSITION = 1, PROP_SELECTION_BOUND = 2, PROP_EDITABLE = 3, PROP_WIDTH_CHARS = 4, PROP_MAX_WIDTH_CHARS = 5, PROP_XALIGN = 6, PROP_ENABLE_UNDO = 7, NUM_PROPERTIES = 8, } export namespace EntryIconPosition { export const $gtype: GObject.GType<EntryIconPosition>; } export enum EntryIconPosition { PRIMARY = 0, SECONDARY = 1, } export namespace EventSequenceState { export const $gtype: GObject.GType<EventSequenceState>; } export enum EventSequenceState { NONE = 0, CLAIMED = 1, DENIED = 2, } export namespace FileChooserAction { export const $gtype: GObject.GType<FileChooserAction>; } export enum FileChooserAction { OPEN = 0, SAVE = 1, SELECT_FOLDER = 2, } export class FileChooserError extends GLib.Error { static $gtype: GObject.GType<FileChooserError>; constructor(options: { message: string; code: number }); constructor(copy: FileChooserError); // Properties static NONEXISTENT: number; static BAD_FILENAME: number; static ALREADY_EXISTS: number; static INCOMPLETE_HOSTNAME: number; // Members static quark(): GLib.Quark; } export namespace FilterChange { export const $gtype: GObject.GType<FilterChange>; } export enum FilterChange { DIFFERENT = 0, LESS_STRICT = 1, MORE_STRICT = 2, } export namespace FilterMatch { export const $gtype: GObject.GType<FilterMatch>; } export enum FilterMatch { SOME = 0, NONE = 1, ALL = 2, } export namespace IconSize { export const $gtype: GObject.GType<IconSize>; } export enum IconSize { INHERIT = 0, NORMAL = 1, LARGE = 2, } export class IconThemeError extends GLib.Error { static $gtype: GObject.GType<IconThemeError>; constructor(options: { message: string; code: number }); constructor(copy: IconThemeError); // Properties static NOT_FOUND: number; static FAILED: number; // Members static quark(): GLib.Quark; } export namespace IconViewDropPosition { export const $gtype: GObject.GType<IconViewDropPosition>; } export enum IconViewDropPosition { NO_DROP = 0, DROP_INTO = 1, DROP_LEFT = 2, DROP_RIGHT = 3, DROP_ABOVE = 4, DROP_BELOW = 5, } export namespace ImageType { export const $gtype: GObject.GType<ImageType>; } export enum ImageType { EMPTY = 0, ICON_NAME = 1, GICON = 2, PAINTABLE = 3, } export namespace InputPurpose { export const $gtype: GObject.GType<InputPurpose>; } export enum InputPurpose { FREE_FORM = 0, ALPHA = 1, DIGITS = 2, NUMBER = 3, PHONE = 4, URL = 5, EMAIL = 6, NAME = 7, PASSWORD = 8, PIN = 9, TERMINAL = 10, } export namespace Justification { export const $gtype: GObject.GType<Justification>; } export enum Justification { LEFT = 0, RIGHT = 1, CENTER = 2, FILL = 3, } export namespace LevelBarMode { export const $gtype: GObject.GType<LevelBarMode>; } export enum LevelBarMode { CONTINUOUS = 0, DISCRETE = 1, } export namespace License { export const $gtype: GObject.GType<License>; } export enum License { UNKNOWN = 0, CUSTOM = 1, GPL_2_0 = 2, GPL_3_0 = 3, LGPL_2_1 = 4, LGPL_3_0 = 5, BSD = 6, MIT_X11 = 7, ARTISTIC = 8, GPL_2_0_ONLY = 9, GPL_3_0_ONLY = 10, LGPL_2_1_ONLY = 11, LGPL_3_0_ONLY = 12, AGPL_3_0 = 13, AGPL_3_0_ONLY = 14, BSD_3 = 15, APACHE_2_0 = 16, MPL_2_0 = 17, } export namespace MessageType { export const $gtype: GObject.GType<MessageType>; } export enum MessageType { INFO = 0, WARNING = 1, QUESTION = 2, ERROR = 3, OTHER = 4, } export namespace MovementStep { export const $gtype: GObject.GType<MovementStep>; } export enum MovementStep { LOGICAL_POSITIONS = 0, VISUAL_POSITIONS = 1, WORDS = 2, DISPLAY_LINES = 3, DISPLAY_LINE_ENDS = 4, PARAGRAPHS = 5, PARAGRAPH_ENDS = 6, PAGES = 7, BUFFER_ENDS = 8, HORIZONTAL_PAGES = 9, } export namespace NotebookTab { export const $gtype: GObject.GType<NotebookTab>; } export enum NotebookTab { FIRST = 0, LAST = 1, } export namespace NumberUpLayout { export const $gtype: GObject.GType<NumberUpLayout>; } export enum NumberUpLayout { LRTB = 0, LRBT = 1, RLTB = 2, RLBT = 3, TBLR = 4, TBRL = 5, BTLR = 6, BTRL = 7, } export namespace Ordering { export const $gtype: GObject.GType<Ordering>; } export enum Ordering { SMALLER = -1, EQUAL = 0, LARGER = 1, } export namespace Orientation { export const $gtype: GObject.GType<Orientation>; } export enum Orientation { HORIZONTAL = 0, VERTICAL = 1, } export namespace Overflow { export const $gtype: GObject.GType<Overflow>; } export enum Overflow { VISIBLE = 0, HIDDEN = 1, } export namespace PackType { export const $gtype: GObject.GType<PackType>; } export enum PackType { START = 0, END = 1, } export namespace PadActionType { export const $gtype: GObject.GType<PadActionType>; } export enum PadActionType { BUTTON = 0, RING = 1, STRIP = 2, } export namespace PageOrientation { export const $gtype: GObject.GType<PageOrientation>; } export enum PageOrientation { PORTRAIT = 0, LANDSCAPE = 1, REVERSE_PORTRAIT = 2, REVERSE_LANDSCAPE = 3, } export namespace PageSet { export const $gtype: GObject.GType<PageSet>; } export enum PageSet { ALL = 0, EVEN = 1, ODD = 2, } export namespace PanDirection { export const $gtype: GObject.GType<PanDirection>; } export enum PanDirection { LEFT = 0, RIGHT = 1, UP = 2, DOWN = 3, } export namespace PolicyType { export const $gtype: GObject.GType<PolicyType>; } export enum PolicyType { ALWAYS = 0, AUTOMATIC = 1, NEVER = 2, EXTERNAL = 3, } export namespace PositionType { export const $gtype: GObject.GType<PositionType>; } export enum PositionType { LEFT = 0, RIGHT = 1, TOP = 2, BOTTOM = 3, } export namespace PrintDuplex { export const $gtype: GObject.GType<PrintDuplex>; } export enum PrintDuplex { SIMPLEX = 0, HORIZONTAL = 1, VERTICAL = 2, } export class PrintError extends GLib.Error { static $gtype: GObject.GType<PrintError>; constructor(options: { message: string; code: number }); constructor(copy: PrintError); // Properties static GENERAL: number; static INTERNAL_ERROR: number; static NOMEM: number; static INVALID_FILE: number; // Members static quark(): GLib.Quark; } export namespace PrintOperationAction { export const $gtype: GObject.GType<PrintOperationAction>; } export enum PrintOperationAction { PRINT_DIALOG = 0, PRINT = 1, PREVIEW = 2, EXPORT = 3, } export namespace PrintOperationResult { export const $gtype: GObject.GType<PrintOperationResult>; } export enum PrintOperationResult { ERROR = 0, APPLY = 1, CANCEL = 2, IN_PROGRESS = 3, } export namespace PrintPages { export const $gtype: GObject.GType<PrintPages>; } export enum PrintPages { ALL = 0, CURRENT = 1, RANGES = 2, SELECTION = 3, } export namespace PrintQuality { export const $gtype: GObject.GType<PrintQuality>; } export enum PrintQuality { LOW = 0, NORMAL = 1, HIGH = 2, DRAFT = 3, } export namespace PrintStatus { export const $gtype: GObject.GType<PrintStatus>; } export enum PrintStatus { INITIAL = 0, PREPARING = 1, GENERATING_DATA = 2, SENDING_DATA = 3, PENDING = 4, PENDING_ISSUE = 5, PRINTING = 6, FINISHED = 7, FINISHED_ABORTED = 8, } export namespace PropagationLimit { export const $gtype: GObject.GType<PropagationLimit>; } export enum PropagationLimit { NONE = 0, SAME_NATIVE = 1, } export namespace PropagationPhase { export const $gtype: GObject.GType<PropagationPhase>; } export enum PropagationPhase { NONE = 0, CAPTURE = 1, BUBBLE = 2, TARGET = 3, } export class RecentManagerError extends GLib.Error { static $gtype: GObject.GType<RecentManagerError>; constructor(options: { message: string; code: number }); constructor(copy: RecentManagerError); // Properties static NOT_FOUND: number; static INVALID_URI: number; static INVALID_ENCODING: number; static NOT_REGISTERED: number; static READ: number; static WRITE: number; static UNKNOWN: number; // Members static quark(): GLib.Quark; } export namespace ResponseType { export const $gtype: GObject.GType<ResponseType>; } export enum ResponseType { NONE = -1, REJECT = -2, ACCEPT = -3, DELETE_EVENT = -4, OK = -5, CANCEL = -6, CLOSE = -7, YES = -8, NO = -9, APPLY = -10, HELP = -11, } export namespace RevealerTransitionType { export const $gtype: GObject.GType<RevealerTransitionType>; } export enum RevealerTransitionType { NONE = 0, CROSSFADE = 1, SLIDE_RIGHT = 2, SLIDE_LEFT = 3, SLIDE_UP = 4, SLIDE_DOWN = 5, SWING_RIGHT = 6, SWING_LEFT = 7, SWING_UP = 8, SWING_DOWN = 9, } export namespace ScrollStep { export const $gtype: GObject.GType<ScrollStep>; } export enum ScrollStep { STEPS = 0, PAGES = 1, ENDS = 2, HORIZONTAL_STEPS = 3, HORIZONTAL_PAGES = 4, HORIZONTAL_ENDS = 5, } export namespace ScrollType { export const $gtype: GObject.GType<ScrollType>; } export enum ScrollType { NONE = 0, JUMP = 1, STEP_BACKWARD = 2, STEP_FORWARD = 3, PAGE_BACKWARD = 4, PAGE_FORWARD = 5, STEP_UP = 6, STEP_DOWN = 7, PAGE_UP = 8, PAGE_DOWN = 9, STEP_LEFT = 10, STEP_RIGHT = 11, PAGE_LEFT = 12, PAGE_RIGHT = 13, START = 14, END = 15, } export namespace ScrollablePolicy { export const $gtype: GObject.GType<ScrollablePolicy>; } export enum ScrollablePolicy { MINIMUM = 0, NATURAL = 1, } export namespace SelectionMode { export const $gtype: GObject.GType<SelectionMode>; } export enum SelectionMode { NONE = 0, SINGLE = 1, BROWSE = 2, MULTIPLE = 3, } export namespace SensitivityType { export const $gtype: GObject.GType<SensitivityType>; } export enum SensitivityType { AUTO = 0, ON = 1, OFF = 2, } export namespace ShortcutScope { export const $gtype: GObject.GType<ShortcutScope>; } export enum ShortcutScope { LOCAL = 0, MANAGED = 1, GLOBAL = 2, } export namespace ShortcutType { export const $gtype: GObject.GType<ShortcutType>; } export enum ShortcutType { ACCELERATOR = 0, GESTURE_PINCH = 1, GESTURE_STRETCH = 2, GESTURE_ROTATE_CLOCKWISE = 3, GESTURE_ROTATE_COUNTERCLOCKWISE = 4, GESTURE_TWO_FINGER_SWIPE_LEFT = 5, GESTURE_TWO_FINGER_SWIPE_RIGHT = 6, GESTURE = 7, GESTURE_SWIPE_LEFT = 8, GESTURE_SWIPE_RIGHT = 9, } export namespace SizeGroupMode { export const $gtype: GObject.GType<SizeGroupMode>; } export enum SizeGroupMode { NONE = 0, HORIZONTAL = 1, VERTICAL = 2, BOTH = 3, } export namespace SizeRequestMode { export const $gtype: GObject.GType<SizeRequestMode>; } export enum SizeRequestMode { HEIGHT_FOR_WIDTH = 0, WIDTH_FOR_HEIGHT = 1, CONSTANT_SIZE = 2, } export namespace SortType { export const $gtype: GObject.GType<SortType>; } export enum SortType { ASCENDING = 0, DESCENDING = 1, } export namespace SorterChange { export const $gtype: GObject.GType<SorterChange>; } export enum SorterChange { DIFFERENT = 0, INVERTED = 1, LESS_STRICT = 2, MORE_STRICT = 3, } export namespace SorterOrder { export const $gtype: GObject.GType<SorterOrder>; } export enum SorterOrder { PARTIAL = 0, NONE = 1, TOTAL = 2, } export namespace SpinButtonUpdatePolicy { export const $gtype: GObject.GType<SpinButtonUpdatePolicy>; } export enum SpinButtonUpdatePolicy { ALWAYS = 0, IF_VALID = 1, } export namespace SpinType { export const $gtype: GObject.GType<SpinType>; } export enum SpinType { STEP_FORWARD = 0, STEP_BACKWARD = 1, PAGE_FORWARD = 2, PAGE_BACKWARD = 3, HOME = 4, END = 5, USER_DEFINED = 6, } export namespace StackTransitionType { export const $gtype: GObject.GType<StackTransitionType>; } export enum StackTransitionType { NONE = 0, CROSSFADE = 1, SLIDE_RIGHT = 2, SLIDE_LEFT = 3, SLIDE_UP = 4, SLIDE_DOWN = 5, SLIDE_LEFT_RIGHT = 6, SLIDE_UP_DOWN = 7, OVER_UP = 8, OVER_DOWN = 9, OVER_LEFT = 10, OVER_RIGHT = 11, UNDER_UP = 12, UNDER_DOWN = 13, UNDER_LEFT = 14, UNDER_RIGHT = 15, OVER_UP_DOWN = 16, OVER_DOWN_UP = 17, OVER_LEFT_RIGHT = 18, OVER_RIGHT_LEFT = 19, ROTATE_LEFT = 20, ROTATE_RIGHT = 21, ROTATE_LEFT_RIGHT = 22, } export namespace StringFilterMatchMode { export const $gtype: GObject.GType<StringFilterMatchMode>; } export enum StringFilterMatchMode { EXACT = 0, SUBSTRING = 1, PREFIX = 2, } export namespace SystemSetting { export const $gtype: GObject.GType<SystemSetting>; } export enum SystemSetting { DPI = 0, FONT_NAME = 1, FONT_CONFIG = 2, DISPLAY = 3, ICON_THEME = 4, } export namespace TextDirection { export const $gtype: GObject.GType<TextDirection>; } export enum TextDirection { NONE = 0, LTR = 1, RTL = 2, } export namespace TextExtendSelection { export const $gtype: GObject.GType<TextExtendSelection>; } export enum TextExtendSelection { WORD = 0, LINE = 1, } export namespace TextViewLayer { export const $gtype: GObject.GType<TextViewLayer>; } export enum TextViewLayer { BELOW_TEXT = 0, ABOVE_TEXT = 1, } export namespace TextWindowType { export const $gtype: GObject.GType<TextWindowType>; } export enum TextWindowType { WIDGET = 1, TEXT = 2, LEFT = 3, RIGHT = 4, TOP = 5, BOTTOM = 6, } export namespace TreeViewColumnSizing { export const $gtype: GObject.GType<TreeViewColumnSizing>; } export enum TreeViewColumnSizing { GROW_ONLY = 0, AUTOSIZE = 1, FIXED = 2, } export namespace TreeViewDropPosition { export const $gtype: GObject.GType<TreeViewDropPosition>; } export enum TreeViewDropPosition { BEFORE = 0, AFTER = 1, INTO_OR_BEFORE = 2, INTO_OR_AFTER = 3, } export namespace TreeViewGridLines { export const $gtype: GObject.GType<TreeViewGridLines>; } export enum TreeViewGridLines { NONE = 0, HORIZONTAL = 1, VERTICAL = 2, BOTH = 3, } export namespace Unit { export const $gtype: GObject.GType<Unit>; } export enum Unit { NONE = 0, POINTS = 1, INCH = 2, MM = 3, } export namespace WrapMode { export const $gtype: GObject.GType<WrapMode>; } export enum WrapMode { NONE = 0, CHAR = 1, WORD = 2, WORD_CHAR = 3, } export namespace ApplicationInhibitFlags { export const $gtype: GObject.GType<ApplicationInhibitFlags>; } export enum ApplicationInhibitFlags { LOGOUT = 1, SWITCH = 2, SUSPEND = 4, IDLE = 8, } export namespace BuilderClosureFlags { export const $gtype: GObject.GType<BuilderClosureFlags>; } export enum BuilderClosureFlags { SWAPPED = 1, } export namespace CellRendererState { export const $gtype: GObject.GType<CellRendererState>; } export enum CellRendererState { SELECTED = 1, PRELIT = 2, INSENSITIVE = 4, SORTED = 8, FOCUSED = 16, EXPANDABLE = 32, EXPANDED = 64, } export namespace DebugFlags { export const $gtype: GObject.GType<DebugFlags>; } export enum DebugFlags { TEXT = 1, TREE = 2, KEYBINDINGS = 4, MODULES = 8, GEOMETRY = 16, ICONTHEME = 32, PRINTING = 64, BUILDER = 128, SIZE_REQUEST = 256, NO_CSS_CACHE = 512, INTERACTIVE = 1024, TOUCHSCREEN = 2048, ACTIONS = 4096, LAYOUT = 8192, SNAPSHOT = 16384, CONSTRAINTS = 32768, BUILDER_OBJECTS = 65536, A11Y = 131072, } export namespace DialogFlags { export const $gtype: GObject.GType<DialogFlags>; } export enum DialogFlags { MODAL = 1, DESTROY_WITH_PARENT = 2, USE_HEADER_BAR = 4, } export namespace EventControllerScrollFlags { export const $gtype: GObject.GType<EventControllerScrollFlags>; } export enum EventControllerScrollFlags { NONE = 0, VERTICAL = 1, HORIZONTAL = 2, DISCRETE = 4, KINETIC = 8, BOTH_AXES = 3, } export namespace FontChooserLevel { export const $gtype: GObject.GType<FontChooserLevel>; } export enum FontChooserLevel { FAMILY = 0, STYLE = 1, SIZE = 2, VARIATIONS = 4, FEATURES = 8, } export namespace IconLookupFlags { export const $gtype: GObject.GType<IconLookupFlags>; } export enum IconLookupFlags { FORCE_REGULAR = 1, FORCE_SYMBOLIC = 2, PRELOAD = 4, } export namespace InputHints { export const $gtype: GObject.GType<InputHints>; } export enum InputHints { NONE = 0, SPELLCHECK = 1, NO_SPELLCHECK = 2, WORD_COMPLETION = 4, LOWERCASE = 8, UPPERCASE_CHARS = 16, UPPERCASE_WORDS = 32, UPPERCASE_SENTENCES = 64, INHIBIT_OSK = 128, VERTICAL_WRITING = 256, EMOJI = 512, NO_EMOJI = 1024, PRIVATE = 2048, } export namespace PickFlags { export const $gtype: GObject.GType<PickFlags>; } export enum PickFlags { DEFAULT = 0, INSENSITIVE = 1, NON_TARGETABLE = 2, } export namespace PopoverMenuFlags { export const $gtype: GObject.GType<PopoverMenuFlags>; } export enum PopoverMenuFlags { NESTED = 1, } export namespace ShortcutActionFlags { export const $gtype: GObject.GType<ShortcutActionFlags>; } export enum ShortcutActionFlags { EXCLUSIVE = 1, } export namespace StateFlags { export const $gtype: GObject.GType<StateFlags>; } export enum StateFlags { NORMAL = 0, ACTIVE = 1, PRELIGHT = 2, SELECTED = 4, INSENSITIVE = 8, INCONSISTENT = 16, FOCUSED = 32, BACKDROP = 64, DIR_LTR = 128, DIR_RTL = 256, LINK = 512, VISITED = 1024, CHECKED = 2048, DROP_ACTIVE = 4096, FOCUS_VISIBLE = 8192, FOCUS_WITHIN = 16384, } export namespace StyleContextPrintFlags { export const $gtype: GObject.GType<StyleContextPrintFlags>; } export enum StyleContextPrintFlags { NONE = 0, RECURSE = 1, SHOW_STYLE = 2, SHOW_CHANGE = 4, } export namespace TextSearchFlags { export const $gtype: GObject.GType<TextSearchFlags>; } export enum TextSearchFlags { VISIBLE_ONLY = 1, TEXT_ONLY = 2, CASE_INSENSITIVE = 4, } export namespace TreeModelFlags { export const $gtype: GObject.GType<TreeModelFlags>; } export enum TreeModelFlags { ITERS_PERSIST = 1, LIST_ONLY = 2, } export namespace ATContext { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; accessible: Accessible; accessible_role: AccessibleRole; accessibleRole: AccessibleRole; display: Gdk.Display; } } export abstract class ATContext extends GObject.Object { static $gtype: GObject.GType<ATContext>; constructor( properties?: Partial<ATContext.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ATContext.ConstructorProperties>, ...args: any[] ): void; // Properties accessible: Accessible; accessible_role: AccessibleRole; accessibleRole: AccessibleRole; display: Gdk.Display; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'state-change', callback: (_source: this) => void): number; connect_after( signal: 'state-change', callback: (_source: this) => void ): number; emit(signal: 'state-change'): void; // Constructors static create( accessible_role: AccessibleRole, accessible: Accessible, display: Gdk.Display ): ATContext; // Members get_accessible(): Accessible; get_accessible_role(): AccessibleRole; } export namespace AboutDialog { export interface ConstructorProperties extends Window.ConstructorProperties { [key: string]: any; artists: string[]; authors: string[]; comments: string; copyright: string; documenters: string[]; license: string; license_type: License; licenseType: License; logo: Gdk.Paintable; logo_icon_name: string; logoIconName: string; program_name: string; programName: string; system_information: string; systemInformation: string; translator_credits: string; translatorCredits: string; version: string; website: string; website_label: string; websiteLabel: string; wrap_license: boolean; wrapLicense: boolean; } } export class AboutDialog extends Window implements Accessible, Buildable, ConstraintTarget, Native, Root, ShortcutManager { static $gtype: GObject.GType<AboutDialog>; constructor( properties?: Partial<AboutDialog.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<AboutDialog.ConstructorProperties>, ...args: any[] ): void; // Properties artists: string[]; authors: string[]; comments: string; copyright: string; documenters: string[]; license: string; license_type: License; licenseType: License; logo: Gdk.Paintable; logo_icon_name: string; logoIconName: string; program_name: string; programName: string; system_information: string; systemInformation: string; translator_credits: string; translatorCredits: string; version: string; website: string; website_label: string; websiteLabel: string; wrap_license: boolean; wrapLicense: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'activate-link', callback: (_source: this, uri: string) => boolean ): number; connect_after( signal: 'activate-link', callback: (_source: this, uri: string) => boolean ): number; emit(signal: 'activate-link', uri: string): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](): AboutDialog; // Members add_credit_section(section_name: string, people: string[]): void; get_artists(): string[]; get_authors(): string[]; get_comments(): string | null; get_copyright(): string | null; get_documenters(): string[]; get_license(): string | null; get_license_type(): License; get_logo(): Gdk.Paintable | null; get_logo_icon_name(): string | null; get_program_name(): string | null; get_system_information(): string | null; get_translator_credits(): string | null; get_version(): string | null; get_website(): string | null; get_website_label(): string | null; get_wrap_license(): boolean; set_artists(artists: string[]): void; set_authors(authors: string[]): void; set_comments(comments?: string | null): void; set_copyright(copyright?: string | null): void; set_documenters(documenters: string[]): void; set_license(license?: string | null): void; set_license_type(license_type: License): void; set_logo(logo?: Gdk.Paintable | null): void; set_logo_icon_name(icon_name?: string | null): void; set_program_name(name: string): void; set_system_information(system_information?: string | null): void; set_translator_credits(translator_credits?: string | null): void; set_version(version?: string | null): void; set_website(website?: string | null): void; set_website_label(website_label: string): void; set_wrap_license(wrap_license: boolean): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_renderer(): Gsk.Renderer; get_surface(): Gdk.Surface; get_surface_transform(): [number, number]; realize(): void; unrealize(): void; get_display(): Gdk.Display; get_focus(): Widget | null; set_focus(focus?: Widget | null): void; vfunc_add_controller(controller: ShortcutController): void; vfunc_remove_controller(controller: ShortcutController): void; } export namespace ActionBar { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; revealed: boolean; } } export class ActionBar extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<ActionBar>; constructor( properties?: Partial<ActionBar.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ActionBar.ConstructorProperties>, ...args: any[] ): void; // Properties revealed: boolean; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](): ActionBar; // Members get_center_widget(): Widget | null; get_revealed(): boolean; pack_end(child: Widget): void; pack_start(child: Widget): void; remove(child: Widget): void; set_center_widget(center_widget?: Widget | null): void; set_revealed(revealed: boolean): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace ActivateAction { export interface ConstructorProperties extends ShortcutAction.ConstructorProperties { [key: string]: any; } } export class ActivateAction extends ShortcutAction { static $gtype: GObject.GType<ActivateAction>; constructor( properties?: Partial<ActivateAction.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ActivateAction.ConstructorProperties>, ...args: any[] ): void; // Members static get(): ActivateAction; } export namespace Adjustment { export interface ConstructorProperties extends GObject.InitiallyUnowned.ConstructorProperties { [key: string]: any; lower: number; page_increment: number; pageIncrement: number; page_size: number; pageSize: number; step_increment: number; stepIncrement: number; upper: number; value: number; } } export class Adjustment extends GObject.InitiallyUnowned { static $gtype: GObject.GType<Adjustment>; constructor( properties?: Partial<Adjustment.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Adjustment.ConstructorProperties>, ...args: any[] ): void; // Properties lower: number; page_increment: number; pageIncrement: number; page_size: number; pageSize: number; step_increment: number; stepIncrement: number; upper: number; value: number; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'changed', callback: (_source: this) => void): number; connect_after(signal: 'changed', callback: (_source: this) => void): number; emit(signal: 'changed'): void; connect(signal: 'value-changed', callback: (_source: this) => void): number; connect_after( signal: 'value-changed', callback: (_source: this) => void ): number; emit(signal: 'value-changed'): void; // Constructors static ['new']( value: number, lower: number, upper: number, step_increment: number, page_increment: number, page_size: number ): Adjustment; // Members clamp_page(lower: number, upper: number): void; configure( value: number, lower: number, upper: number, step_increment: number, page_increment: number, page_size: number ): void; get_lower(): number; get_minimum_increment(): number; get_page_increment(): number; get_page_size(): number; get_step_increment(): number; get_upper(): number; get_value(): number; set_lower(lower: number): void; set_page_increment(page_increment: number): void; set_page_size(page_size: number): void; set_step_increment(step_increment: number): void; set_upper(upper: number): void; set_value(value: number): void; vfunc_changed(): void; vfunc_value_changed(): void; } export namespace AlternativeTrigger { export interface ConstructorProperties extends ShortcutTrigger.ConstructorProperties { [key: string]: any; first: ShortcutTrigger; second: ShortcutTrigger; } } export class AlternativeTrigger extends ShortcutTrigger { static $gtype: GObject.GType<AlternativeTrigger>; constructor( properties?: Partial<AlternativeTrigger.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<AlternativeTrigger.ConstructorProperties>, ...args: any[] ): void; // Properties first: ShortcutTrigger; second: ShortcutTrigger; // Constructors static ['new']( first: ShortcutTrigger, second: ShortcutTrigger ): AlternativeTrigger; // Members get_first(): ShortcutTrigger; get_second(): ShortcutTrigger; } export namespace AnyFilter { export interface ConstructorProperties< A extends GObject.Object = GObject.Object > extends MultiFilter.ConstructorProperties<A> { [key: string]: any; } } export class AnyFilter<A extends GObject.Object = GObject.Object> extends MultiFilter<A> implements Gio.ListModel<A>, Buildable { static $gtype: GObject.GType<AnyFilter>; constructor( properties?: Partial<AnyFilter.ConstructorProperties<A>>, ...args: any[] ); _init( properties?: Partial<AnyFilter.ConstructorProperties<A>>, ...args: any[] ): void; // Constructors static ['new'](): AnyFilter; // Implemented Members get_item_type(): GObject.GType; get_n_items(): number; get_item(position: number): A | null; items_changed(position: number, removed: number, added: number): void; vfunc_get_item(position: number): A | null; vfunc_get_item_type(): GObject.GType; vfunc_get_n_items(): number; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace AppChooserButton { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; heading: string; modal: boolean; show_default_item: boolean; showDefaultItem: boolean; show_dialog_item: boolean; showDialogItem: boolean; } } export class AppChooserButton extends Widget implements Accessible, AppChooser, Buildable, ConstraintTarget { static $gtype: GObject.GType<AppChooserButton>; constructor( properties?: Partial<AppChooserButton.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<AppChooserButton.ConstructorProperties>, ...args: any[] ): void; // Properties heading: string; modal: boolean; show_default_item: boolean; showDefaultItem: boolean; show_dialog_item: boolean; showDialogItem: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'changed', callback: (_source: this) => void): number; connect_after(signal: 'changed', callback: (_source: this) => void): number; emit(signal: 'changed'): void; connect( signal: 'custom-item-activated', callback: (_source: this, item_name: string) => void ): number; connect_after( signal: 'custom-item-activated', callback: (_source: this, item_name: string) => void ): number; emit(signal: 'custom-item-activated', item_name: string): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; content_type: string; contentType: string; // Constructors static ['new'](content_type: string): AppChooserButton; // Members append_custom_item(name: string, label: string, icon: Gio.Icon): void; append_separator(): void; get_heading(): string | null; get_modal(): boolean; get_show_default_item(): boolean; get_show_dialog_item(): boolean; set_active_custom_item(name: string): void; set_heading(heading: string): void; set_modal(modal: boolean): void; set_show_default_item(setting: boolean): void; set_show_dialog_item(setting: boolean): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_app_info(): Gio.AppInfo | null; get_content_type(): string; refresh(): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace AppChooserDialog { export interface ConstructorProperties extends Dialog.ConstructorProperties { [key: string]: any; gfile: Gio.File; heading: string; } } export class AppChooserDialog extends Dialog implements Accessible, AppChooser, Buildable, ConstraintTarget, Native, Root, ShortcutManager { static $gtype: GObject.GType<AppChooserDialog>; constructor( properties?: Partial<AppChooserDialog.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<AppChooserDialog.ConstructorProperties>, ...args: any[] ): void; // Properties gfile: Gio.File; heading: string; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; content_type: string; contentType: string; // Constructors static ['new']( parent: Window | null, flags: DialogFlags, file: Gio.File ): AppChooserDialog; static ['new'](...args: never[]): never; static new_for_content_type( parent: Window | null, flags: DialogFlags, content_type: string ): AppChooserDialog; // Members get_heading(): string | null; get_widget(): Widget; set_heading(heading: string): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_app_info(): Gio.AppInfo | null; get_content_type(): string; refresh(): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_renderer(): Gsk.Renderer; get_surface(): Gdk.Surface; get_surface_transform(): [number, number]; realize(): void; unrealize(): void; get_display(): Gdk.Display; get_focus(): Widget | null; set_focus(focus?: Widget | null): void; vfunc_add_controller(controller: ShortcutController): void; vfunc_remove_controller(controller: ShortcutController): void; } export namespace AppChooserWidget { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; default_text: string; defaultText: string; show_default: boolean; showDefault: boolean; show_fallback: boolean; showFallback: boolean; show_other: boolean; showOther: boolean; show_recommended: boolean; showRecommended: boolean; } } export class AppChooserWidget extends Widget implements Accessible, AppChooser, Buildable, ConstraintTarget { static $gtype: GObject.GType<AppChooserWidget>; constructor( properties?: Partial<AppChooserWidget.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<AppChooserWidget.ConstructorProperties>, ...args: any[] ): void; // Properties default_text: string; defaultText: string; show_default: boolean; showDefault: boolean; show_fallback: boolean; showFallback: boolean; show_other: boolean; showOther: boolean; show_recommended: boolean; showRecommended: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'application-activated', callback: (_source: this, application: Gio.AppInfo) => void ): number; connect_after( signal: 'application-activated', callback: (_source: this, application: Gio.AppInfo) => void ): number; emit(signal: 'application-activated', application: Gio.AppInfo): void; connect( signal: 'application-selected', callback: (_source: this, application: Gio.AppInfo) => void ): number; connect_after( signal: 'application-selected', callback: (_source: this, application: Gio.AppInfo) => void ): number; emit(signal: 'application-selected', application: Gio.AppInfo): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; content_type: string; contentType: string; // Constructors static ['new'](content_type: string): AppChooserWidget; // Members get_default_text(): string | null; get_show_all(): boolean; get_show_default(): boolean; get_show_fallback(): boolean; get_show_other(): boolean; get_show_recommended(): boolean; set_default_text(text: string): void; set_show_all(setting: boolean): void; set_show_default(setting: boolean): void; set_show_fallback(setting: boolean): void; set_show_other(setting: boolean): void; set_show_recommended(setting: boolean): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_app_info(): Gio.AppInfo | null; get_content_type(): string; refresh(): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace Application { export interface ConstructorProperties extends Gio.Application.ConstructorProperties { [key: string]: any; active_window: Window; activeWindow: Window; menubar: Gio.MenuModel; register_session: boolean; registerSession: boolean; screensaver_active: boolean; screensaverActive: boolean; } } export class Application extends Gio.Application implements Gio.ActionGroup, Gio.ActionMap { static $gtype: GObject.GType<Application>; constructor( properties?: Partial<Application.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Application.ConstructorProperties>, ...args: any[] ): void; // Properties active_window: Window; activeWindow: Window; menubar: Gio.MenuModel; register_session: boolean; registerSession: boolean; screensaver_active: boolean; screensaverActive: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'query-end', callback: (_source: this) => void): number; connect_after( signal: 'query-end', callback: (_source: this) => void ): number; emit(signal: 'query-end'): void; connect( signal: 'window-added', callback: (_source: this, window: Window) => void ): number; connect_after( signal: 'window-added', callback: (_source: this, window: Window) => void ): number; emit(signal: 'window-added', window: Window): void; connect( signal: 'window-removed', callback: (_source: this, window: Window) => void ): number; connect_after( signal: 'window-removed', callback: (_source: this, window: Window) => void ): number; emit(signal: 'window-removed', window: Window): void; // Constructors static ['new']( application_id: string | null, flags: Gio.ApplicationFlags ): Application; // Members add_window(window: Window): void; get_accels_for_action(detailed_action_name: string): string[]; get_actions_for_accel(accel: string): string[]; get_active_window(): Window | null; get_menu_by_id(id: string): Gio.Menu | null; get_menubar(): Gio.MenuModel | null; get_window_by_id(id: number): Window | null; get_windows(): Window[]; inhibit( window: Window | null, flags: ApplicationInhibitFlags, reason?: string | null ): number; list_action_descriptions(): string[]; remove_window(window: Window): void; set_accels_for_action(detailed_action_name: string, accels: string[]): void; set_menubar(menubar?: Gio.MenuModel | null): void; uninhibit(cookie: number): void; vfunc_window_added(window: Window): void; vfunc_window_removed(window: Window): void; // Implemented Members action_added(action_name: string): void; action_enabled_changed(action_name: string, enabled: boolean): void; action_removed(action_name: string): void; action_state_changed(action_name: string, state: GLib.Variant): void; activate_action(action_name: string, parameter?: GLib.Variant | null): void; change_action_state(action_name: string, value: GLib.Variant): void; get_action_enabled(action_name: string): boolean; get_action_parameter_type(action_name: string): GLib.VariantType | null; get_action_state(action_name: string): GLib.Variant | null; get_action_state_hint(action_name: string): GLib.Variant | null; get_action_state_type(action_name: string): GLib.VariantType | null; has_action(action_name: string): boolean; list_actions(): string[]; query_action( action_name: string ): [ boolean, boolean, GLib.VariantType | null, GLib.VariantType | null, GLib.Variant | null, GLib.Variant | null ]; vfunc_action_added(action_name: string): void; vfunc_action_enabled_changed(action_name: string, enabled: boolean): void; vfunc_action_removed(action_name: string): void; vfunc_action_state_changed(action_name: string, state: GLib.Variant): void; vfunc_activate_action( action_name: string, parameter?: GLib.Variant | null ): void; vfunc_change_action_state(action_name: string, value: GLib.Variant): void; vfunc_get_action_enabled(action_name: string): boolean; vfunc_get_action_parameter_type( action_name: string ): GLib.VariantType | null; vfunc_get_action_state(action_name: string): GLib.Variant | null; vfunc_get_action_state_hint(action_name: string): GLib.Variant | null; vfunc_get_action_state_type(action_name: string): GLib.VariantType | null; vfunc_has_action(action_name: string): boolean; vfunc_list_actions(): string[]; vfunc_query_action( action_name: string ): [ boolean, boolean, GLib.VariantType | null, GLib.VariantType | null, GLib.Variant | null, GLib.Variant | null ]; add_action(action: Gio.Action): void; add_action_entries( entries: Gio.ActionEntry[], user_data?: any | null ): void; lookup_action(action_name: string): Gio.Action; remove_action(action_name: string): void; vfunc_add_action(action: Gio.Action): void; vfunc_lookup_action(action_name: string): Gio.Action; vfunc_remove_action(action_name: string): void; } export namespace ApplicationWindow { export interface ConstructorProperties extends Window.ConstructorProperties { [key: string]: any; show_menubar: boolean; showMenubar: boolean; } } export class ApplicationWindow extends Window implements Gio.ActionGroup, Gio.ActionMap, Accessible, Buildable, ConstraintTarget, Native, Root, ShortcutManager { static $gtype: GObject.GType<ApplicationWindow>; constructor( properties?: Partial<ApplicationWindow.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ApplicationWindow.ConstructorProperties>, ...args: any[] ): void; // Properties show_menubar: boolean; showMenubar: boolean; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](application: Application): ApplicationWindow; static ['new'](...args: never[]): never; // Members get_help_overlay(): ShortcutsWindow | null; get_id(): number; get_show_menubar(): boolean; set_help_overlay(help_overlay?: ShortcutsWindow | null): void; set_show_menubar(show_menubar: boolean): void; // Implemented Members action_added(action_name: string): void; action_enabled_changed(action_name: string, enabled: boolean): void; action_removed(action_name: string): void; action_state_changed(action_name: string, state: GLib.Variant): void; activate_action(action_name: string, parameter?: GLib.Variant | null): void; activate_action(...args: never[]): never; change_action_state(action_name: string, value: GLib.Variant): void; get_action_enabled(action_name: string): boolean; get_action_parameter_type(action_name: string): GLib.VariantType | null; get_action_state(action_name: string): GLib.Variant | null; get_action_state_hint(action_name: string): GLib.Variant | null; get_action_state_type(action_name: string): GLib.VariantType | null; has_action(action_name: string): boolean; list_actions(): string[]; query_action( action_name: string ): [ boolean, boolean, GLib.VariantType | null, GLib.VariantType | null, GLib.Variant | null, GLib.Variant | null ]; vfunc_action_added(action_name: string): void; vfunc_action_enabled_changed(action_name: string, enabled: boolean): void; vfunc_action_removed(action_name: string): void; vfunc_action_state_changed(action_name: string, state: GLib.Variant): void; vfunc_activate_action( action_name: string, parameter?: GLib.Variant | null ): void; vfunc_change_action_state(action_name: string, value: GLib.Variant): void; vfunc_get_action_enabled(action_name: string): boolean; vfunc_get_action_parameter_type( action_name: string ): GLib.VariantType | null; vfunc_get_action_state(action_name: string): GLib.Variant | null; vfunc_get_action_state_hint(action_name: string): GLib.Variant | null; vfunc_get_action_state_type(action_name: string): GLib.VariantType | null; vfunc_has_action(action_name: string): boolean; vfunc_list_actions(): string[]; vfunc_query_action( action_name: string ): [ boolean, boolean, GLib.VariantType | null, GLib.VariantType | null, GLib.Variant | null, GLib.Variant | null ]; add_action(action: Gio.Action): void; add_action_entries( entries: Gio.ActionEntry[], user_data?: any | null ): void; lookup_action(action_name: string): Gio.Action; remove_action(action_name: string): void; vfunc_add_action(action: Gio.Action): void; vfunc_lookup_action(action_name: string): Gio.Action; vfunc_remove_action(action_name: string): void; get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_renderer(): Gsk.Renderer; get_surface(): Gdk.Surface; get_surface_transform(): [number, number]; realize(): void; unrealize(): void; get_display(): Gdk.Display; get_focus(): Widget | null; set_focus(focus?: Widget | null): void; vfunc_add_controller(controller: ShortcutController): void; vfunc_remove_controller(controller: ShortcutController): void; } export namespace AspectFrame { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; child: Widget; obey_child: boolean; obeyChild: boolean; ratio: number; xalign: number; yalign: number; } } export class AspectFrame extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<AspectFrame>; constructor( properties?: Partial<AspectFrame.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<AspectFrame.ConstructorProperties>, ...args: any[] ): void; // Properties child: Widget; obey_child: boolean; obeyChild: boolean; ratio: number; xalign: number; yalign: number; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new']( xalign: number, yalign: number, ratio: number, obey_child: boolean ): AspectFrame; // Members get_child(): Widget | null; get_obey_child(): boolean; get_ratio(): number; get_xalign(): number; get_yalign(): number; set_child(child?: Widget | null): void; set_obey_child(obey_child: boolean): void; set_ratio(ratio: number): void; set_xalign(xalign: number): void; set_yalign(yalign: number): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace Assistant { export interface ConstructorProperties extends Window.ConstructorProperties { [key: string]: any; pages: Gio.ListModel; use_header_bar: number; useHeaderBar: number; } } export class Assistant extends Window implements Accessible, Buildable, ConstraintTarget, Native, Root, ShortcutManager { static $gtype: GObject.GType<Assistant>; constructor( properties?: Partial<Assistant.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Assistant.ConstructorProperties>, ...args: any[] ): void; // Properties pages: Gio.ListModel; use_header_bar: number; useHeaderBar: number; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'apply', callback: (_source: this) => void): number; connect_after(signal: 'apply', callback: (_source: this) => void): number; emit(signal: 'apply'): void; connect(signal: 'cancel', callback: (_source: this) => void): number; connect_after(signal: 'cancel', callback: (_source: this) => void): number; emit(signal: 'cancel'): void; connect(signal: 'close', callback: (_source: this) => void): number; connect_after(signal: 'close', callback: (_source: this) => void): number; emit(signal: 'close'): void; connect(signal: 'escape', callback: (_source: this) => void): number; connect_after(signal: 'escape', callback: (_source: this) => void): number; emit(signal: 'escape'): void; connect( signal: 'prepare', callback: (_source: this, page: Widget) => void ): number; connect_after( signal: 'prepare', callback: (_source: this, page: Widget) => void ): number; emit(signal: 'prepare', page: Widget): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](): Assistant; // Members add_action_widget(child: Widget): void; append_page(page: Widget): number; commit(): void; get_current_page(): number; get_n_pages(): number; get_nth_page(page_num: number): Widget | null; get_page(child: Widget): AssistantPage; get_page_complete(page: Widget): boolean; get_page_title(page: Widget): string; get_page_type(page: Widget): AssistantPageType; get_pages(): Gio.ListModel; insert_page(page: Widget, position: number): number; next_page(): void; prepend_page(page: Widget): number; previous_page(): void; remove_action_widget(child: Widget): void; remove_page(page_num: number): void; set_current_page(page_num: number): void; set_forward_page_func(page_func?: AssistantPageFunc | null): void; set_page_complete(page: Widget, complete: boolean): void; set_page_title(page: Widget, title: string): void; set_page_type(page: Widget, type: AssistantPageType): void; update_buttons_state(): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_renderer(): Gsk.Renderer; get_surface(): Gdk.Surface; get_surface_transform(): [number, number]; realize(): void; unrealize(): void; get_display(): Gdk.Display; get_focus(): Widget | null; set_focus(focus?: Widget | null): void; vfunc_add_controller(controller: ShortcutController): void; vfunc_remove_controller(controller: ShortcutController): void; } export namespace AssistantPage { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; child: Widget; complete: boolean; page_type: AssistantPageType; pageType: AssistantPageType; title: string; } } export class AssistantPage extends GObject.Object { static $gtype: GObject.GType<AssistantPage>; constructor( properties?: Partial<AssistantPage.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<AssistantPage.ConstructorProperties>, ...args: any[] ): void; // Properties child: Widget; complete: boolean; page_type: AssistantPageType; pageType: AssistantPageType; title: string; // Members get_child(): Widget; } export namespace BinLayout { export interface ConstructorProperties extends LayoutManager.ConstructorProperties { [key: string]: any; } } export class BinLayout extends LayoutManager { static $gtype: GObject.GType<BinLayout>; constructor( properties?: Partial<BinLayout.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<BinLayout.ConstructorProperties>, ...args: any[] ): void; // Constructors static ['new'](): BinLayout; } export namespace BookmarkList { export interface ConstructorProperties< A extends GObject.Object = GObject.Object > extends GObject.Object.ConstructorProperties { [key: string]: any; attributes: string; filename: string; io_priority: number; ioPriority: number; loading: boolean; } } export class BookmarkList<A extends GObject.Object = GObject.Object> extends GObject.Object implements Gio.ListModel<A> { static $gtype: GObject.GType<BookmarkList>; constructor( properties?: Partial<BookmarkList.ConstructorProperties<A>>, ...args: any[] ); _init( properties?: Partial<BookmarkList.ConstructorProperties<A>>, ...args: any[] ): void; // Properties attributes: string; filename: string; io_priority: number; ioPriority: number; loading: boolean; // Constructors static ['new']( filename?: string | null, attributes?: string | null ): BookmarkList; // Members get_attributes(): string | null; get_filename(): string; get_io_priority(): number; is_loading(): boolean; set_attributes(attributes?: string | null): void; set_io_priority(io_priority: number): void; // Implemented Members get_item_type(): GObject.GType; get_n_items(): number; get_item(position: number): A | null; items_changed(position: number, removed: number, added: number): void; vfunc_get_item(position: number): A | null; vfunc_get_item_type(): GObject.GType; vfunc_get_n_items(): number; } export namespace BoolFilter { export interface ConstructorProperties extends Filter.ConstructorProperties { [key: string]: any; expression: Expression; invert: boolean; } } export class BoolFilter extends Filter { static $gtype: GObject.GType<BoolFilter>; constructor( properties?: Partial<BoolFilter.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<BoolFilter.ConstructorProperties>, ...args: any[] ): void; // Properties expression: Expression; invert: boolean; // Constructors static ['new'](expression?: Expression | null): BoolFilter; // Members get_expression(): Expression; get_invert(): boolean; set_expression(expression: Expression): void; set_invert(invert: boolean): void; } export namespace Box { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; baseline_position: BaselinePosition; baselinePosition: BaselinePosition; homogeneous: boolean; spacing: number; } } export class Box extends Widget implements Accessible, Buildable, ConstraintTarget, Orientable { static $gtype: GObject.GType<Box>; constructor( properties?: Partial<Box.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Box.ConstructorProperties>, ...args: any[] ): void; // Properties baseline_position: BaselinePosition; baselinePosition: BaselinePosition; homogeneous: boolean; spacing: number; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; orientation: Orientation; // Constructors static ['new'](orientation: Orientation, spacing: number): Box; // Members append(child: Widget): void; get_baseline_position(): BaselinePosition; get_homogeneous(): boolean; get_spacing(): number; insert_child_after(child: Widget, sibling?: Widget | null): void; prepend(child: Widget): void; remove(child: Widget): void; reorder_child_after(child: Widget, sibling?: Widget | null): void; set_baseline_position(position: BaselinePosition): void; set_homogeneous(homogeneous: boolean): void; set_spacing(spacing: number): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_orientation(): Orientation; set_orientation(orientation: Orientation): void; } export namespace BoxLayout { export interface ConstructorProperties extends LayoutManager.ConstructorProperties { [key: string]: any; baseline_position: BaselinePosition; baselinePosition: BaselinePosition; homogeneous: boolean; spacing: number; } } export class BoxLayout extends LayoutManager implements Orientable { static $gtype: GObject.GType<BoxLayout>; constructor( properties?: Partial<BoxLayout.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<BoxLayout.ConstructorProperties>, ...args: any[] ): void; // Properties baseline_position: BaselinePosition; baselinePosition: BaselinePosition; homogeneous: boolean; spacing: number; // Implemented Properties orientation: Orientation; // Constructors static ['new'](orientation: Orientation): BoxLayout; // Members get_baseline_position(): BaselinePosition; get_homogeneous(): boolean; get_spacing(): number; set_baseline_position(position: BaselinePosition): void; set_homogeneous(homogeneous: boolean): void; set_spacing(spacing: number): void; // Implemented Members get_orientation(): Orientation; set_orientation(orientation: Orientation): void; } export namespace Builder { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; current_object: GObject.Object; currentObject: GObject.Object; scope: BuilderScope; translation_domain: string; translationDomain: string; } } export class Builder extends GObject.Object { static $gtype: GObject.GType<Builder>; constructor( properties?: Partial<Builder.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Builder.ConstructorProperties>, ...args: any[] ): void; // Properties current_object: GObject.Object; currentObject: GObject.Object; scope: BuilderScope; translation_domain: string; translationDomain: string; // Constructors static ['new'](): Builder; static new_from_file(filename: string): Builder; static new_from_resource(resource_path: string): Builder; static new_from_string(string: string, length: number): Builder; // Members add_from_file(filename: string): boolean; add_from_resource(resource_path: string): boolean; add_from_string(buffer: string, length: number): boolean; add_objects_from_file(filename: string, object_ids: string[]): boolean; add_objects_from_resource( resource_path: string, object_ids: string[] ): boolean; add_objects_from_string( buffer: string, length: number, object_ids: string[] ): boolean; create_closure( function_name: string, flags: BuilderClosureFlags, object?: GObject.Object | null ): GObject.Closure | null; expose_object(name: string, object: GObject.Object): void; extend_with_template( object: GObject.Object, template_type: GObject.GType, buffer: string, length: number ): boolean; get_current_object<T = GObject.Object>(): T; get_object<T = GObject.Object>(name: string): T; get_objects(): GObject.Object[]; get_scope(): BuilderScope; get_translation_domain(): string | null; get_type_from_name(type_name: string): GObject.GType; set_current_object(current_object?: GObject.Object | null): void; set_scope(scope?: BuilderScope | null): void; set_translation_domain(domain?: string | null): void; value_from_string( pspec: GObject.ParamSpec, string: string ): [boolean, unknown]; value_from_string_type( type: GObject.GType, string: string ): [boolean, unknown]; } export namespace BuilderCScope { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class BuilderCScope extends GObject.Object implements BuilderScope { static $gtype: GObject.GType<BuilderCScope>; constructor( properties?: Partial<BuilderCScope.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<BuilderCScope.ConstructorProperties>, ...args: any[] ): void; // Constructors static ['new'](): BuilderCScope; // Members add_callback_symbol( callback_name: string, callback_symbol: GObject.Callback ): void; // Implemented Members vfunc_create_closure( builder: Builder, function_name: string, flags: BuilderClosureFlags, object: GObject.Object ): GObject.Closure; vfunc_get_type_from_function( builder: Builder, function_name: string ): GObject.GType; vfunc_get_type_from_name( builder: Builder, type_name: string ): GObject.GType; } export namespace BuilderListItemFactory { export interface ConstructorProperties extends ListItemFactory.ConstructorProperties { [key: string]: any; bytes: GLib.Bytes; resource: string; scope: BuilderScope; } } export class BuilderListItemFactory extends ListItemFactory { static $gtype: GObject.GType<BuilderListItemFactory>; constructor( properties?: Partial<BuilderListItemFactory.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<BuilderListItemFactory.ConstructorProperties>, ...args: any[] ): void; // Properties bytes: GLib.Bytes; resource: string; scope: BuilderScope; // Constructors static new_from_bytes( scope: BuilderScope | null, bytes: GLib.Bytes | Uint8Array ): BuilderListItemFactory; static new_from_resource( scope: BuilderScope | null, resource_path: string ): BuilderListItemFactory; // Members get_bytes(): GLib.Bytes; get_resource(): string | null; get_scope(): BuilderScope | null; } export namespace Button { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; child: Widget; has_frame: boolean; hasFrame: boolean; icon_name: string; iconName: string; label: string; use_underline: boolean; useUnderline: boolean; } } export class Button extends Widget implements Accessible, Actionable, Buildable, ConstraintTarget { static $gtype: GObject.GType<Button>; constructor( properties?: Partial<Button.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Button.ConstructorProperties>, ...args: any[] ): void; // Properties child: Widget; has_frame: boolean; hasFrame: boolean; icon_name: string; iconName: string; label: string; use_underline: boolean; useUnderline: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'activate', callback: (_source: this) => void): number; connect_after( signal: 'activate', callback: (_source: this) => void ): number; emit(signal: 'activate'): void; connect(signal: 'clicked', callback: (_source: this) => void): number; connect_after(signal: 'clicked', callback: (_source: this) => void): number; emit(signal: 'clicked'): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; action_name: string; actionName: string; action_target: GLib.Variant; actionTarget: GLib.Variant; // Constructors static ['new'](): Button; static new_from_icon_name(icon_name?: string | null): Button; static new_with_label(label: string): Button; static new_with_mnemonic(label: string): Button; // Members get_child(): Widget | null; get_has_frame(): boolean; get_icon_name(): string | null; get_label(): string | null; get_use_underline(): boolean; set_child(child?: Widget | null): void; set_has_frame(has_frame: boolean): void; set_icon_name(icon_name: string): void; set_label(label: string): void; set_use_underline(use_underline: boolean): void; vfunc_activate(): void; vfunc_clicked(): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_action_name(): string | null; get_action_target_value(): GLib.Variant | null; set_action_name(action_name?: string | null): void; set_action_target_value(target_value?: GLib.Variant | null): void; set_detailed_action_name(detailed_action_name: string): void; vfunc_get_action_name(): string | null; vfunc_get_action_target_value(): GLib.Variant | null; vfunc_set_action_name(action_name?: string | null): void; vfunc_set_action_target_value(target_value?: GLib.Variant | null): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace CClosureExpression { export interface ConstructorProperties extends Expression.ConstructorProperties { [key: string]: any; } } export class CClosureExpression extends Expression { static $gtype: GObject.GType<CClosureExpression>; constructor( properties?: Partial<CClosureExpression.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<CClosureExpression.ConstructorProperties>, ...args: any[] ): void; // Constructors static ['new']( value_type: GObject.GType, marshal: GObject.ClosureMarshal | null, params: Expression[], callback_func: GObject.Callback, user_destroy?: GObject.ClosureNotify | null ): CClosureExpression; } export namespace Calendar { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; day: number; month: number; show_day_names: boolean; showDayNames: boolean; show_heading: boolean; showHeading: boolean; show_week_numbers: boolean; showWeekNumbers: boolean; year: number; } } export class Calendar extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<Calendar>; constructor( properties?: Partial<Calendar.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Calendar.ConstructorProperties>, ...args: any[] ): void; // Properties day: number; month: number; show_day_names: boolean; showDayNames: boolean; show_heading: boolean; showHeading: boolean; show_week_numbers: boolean; showWeekNumbers: boolean; year: number; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'day-selected', callback: (_source: this) => void): number; connect_after( signal: 'day-selected', callback: (_source: this) => void ): number; emit(signal: 'day-selected'): void; connect(signal: 'next-month', callback: (_source: this) => void): number; connect_after( signal: 'next-month', callback: (_source: this) => void ): number; emit(signal: 'next-month'): void; connect(signal: 'next-year', callback: (_source: this) => void): number; connect_after( signal: 'next-year', callback: (_source: this) => void ): number; emit(signal: 'next-year'): void; connect(signal: 'prev-month', callback: (_source: this) => void): number; connect_after( signal: 'prev-month', callback: (_source: this) => void ): number; emit(signal: 'prev-month'): void; connect(signal: 'prev-year', callback: (_source: this) => void): number; connect_after( signal: 'prev-year', callback: (_source: this) => void ): number; emit(signal: 'prev-year'): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](): Calendar; // Members clear_marks(): void; get_date(): GLib.DateTime; get_day_is_marked(day: number): boolean; get_show_day_names(): boolean; get_show_heading(): boolean; get_show_week_numbers(): boolean; mark_day(day: number): void; select_day(date: GLib.DateTime): void; set_show_day_names(value: boolean): void; set_show_heading(value: boolean): void; set_show_week_numbers(value: boolean): void; unmark_day(day: number): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace CallbackAction { export interface ConstructorProperties extends ShortcutAction.ConstructorProperties { [key: string]: any; } } export class CallbackAction extends ShortcutAction { static $gtype: GObject.GType<CallbackAction>; constructor( properties?: Partial<CallbackAction.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<CallbackAction.ConstructorProperties>, ...args: any[] ): void; // Constructors static ['new'](): CallbackAction; } export namespace CellArea { export interface ConstructorProperties extends GObject.InitiallyUnowned.ConstructorProperties { [key: string]: any; edit_widget: CellEditable; editWidget: CellEditable; edited_cell: CellRenderer; editedCell: CellRenderer; focus_cell: CellRenderer; focusCell: CellRenderer; } } export abstract class CellArea extends GObject.InitiallyUnowned implements Buildable, CellLayout { static $gtype: GObject.GType<CellArea>; constructor( properties?: Partial<CellArea.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<CellArea.ConstructorProperties>, ...args: any[] ): void; // Properties edit_widget: CellEditable; editWidget: CellEditable; edited_cell: CellRenderer; editedCell: CellRenderer; focus_cell: CellRenderer; focusCell: CellRenderer; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'add-editable', callback: ( _source: this, renderer: CellRenderer, editable: CellEditable, cell_area: Gdk.Rectangle, path: string ) => void ): number; connect_after( signal: 'add-editable', callback: ( _source: this, renderer: CellRenderer, editable: CellEditable, cell_area: Gdk.Rectangle, path: string ) => void ): number; emit( signal: 'add-editable', renderer: CellRenderer, editable: CellEditable, cell_area: Gdk.Rectangle, path: string ): void; connect( signal: 'apply-attributes', callback: ( _source: this, model: TreeModel, iter: TreeIter, is_expander: boolean, is_expanded: boolean ) => void ): number; connect_after( signal: 'apply-attributes', callback: ( _source: this, model: TreeModel, iter: TreeIter, is_expander: boolean, is_expanded: boolean ) => void ): number; emit( signal: 'apply-attributes', model: TreeModel, iter: TreeIter, is_expander: boolean, is_expanded: boolean ): void; connect( signal: 'focus-changed', callback: (_source: this, renderer: CellRenderer, path: string) => void ): number; connect_after( signal: 'focus-changed', callback: (_source: this, renderer: CellRenderer, path: string) => void ): number; emit(signal: 'focus-changed', renderer: CellRenderer, path: string): void; connect( signal: 'remove-editable', callback: ( _source: this, renderer: CellRenderer, editable: CellEditable ) => void ): number; connect_after( signal: 'remove-editable', callback: ( _source: this, renderer: CellRenderer, editable: CellEditable ) => void ): number; emit( signal: 'remove-editable', renderer: CellRenderer, editable: CellEditable ): void; // Members activate( context: CellAreaContext, widget: Widget, cell_area: Gdk.Rectangle, flags: CellRendererState, edit_only: boolean ): boolean; activate_cell( widget: Widget, renderer: CellRenderer, event: Gdk.Event, cell_area: Gdk.Rectangle, flags: CellRendererState ): boolean; add(renderer: CellRenderer): void; add_focus_sibling(renderer: CellRenderer, sibling: CellRenderer): void; apply_attributes( tree_model: TreeModel, iter: TreeIter, is_expander: boolean, is_expanded: boolean ): void; attribute_connect( renderer: CellRenderer, attribute: string, column: number ): void; attribute_disconnect(renderer: CellRenderer, attribute: string): void; attribute_get_column(renderer: CellRenderer, attribute: string): number; cell_get_property( renderer: CellRenderer, property_name: string, value: any ): void; cell_set_property( renderer: CellRenderer, property_name: string, value: any ): void; copy_context(context: CellAreaContext): CellAreaContext; create_context(): CellAreaContext; event( context: CellAreaContext, widget: Widget, event: Gdk.Event, cell_area: Gdk.Rectangle, flags: CellRendererState ): number; focus(direction: DirectionType): boolean; foreach(callback: CellCallback): void; foreach_alloc( context: CellAreaContext, widget: Widget, cell_area: Gdk.Rectangle, background_area: Gdk.Rectangle, callback: CellAllocCallback ): void; get_cell_allocation( context: CellAreaContext, widget: Widget, renderer: CellRenderer, cell_area: Gdk.Rectangle ): Gdk.Rectangle; get_cell_at_position( context: CellAreaContext, widget: Widget, cell_area: Gdk.Rectangle, x: number, y: number ): [CellRenderer, Gdk.Rectangle | null]; get_current_path_string(): string; get_edit_widget(): CellEditable; get_edited_cell(): CellRenderer; get_focus_cell(): CellRenderer; get_focus_from_sibling(renderer: CellRenderer): CellRenderer | null; get_focus_siblings(renderer: CellRenderer): CellRenderer[]; get_preferred_height( context: CellAreaContext, widget: Widget ): [number | null, number | null]; get_preferred_height_for_width( context: CellAreaContext, widget: Widget, width: number ): [number | null, number | null]; get_preferred_width( context: CellAreaContext, widget: Widget ): [number | null, number | null]; get_preferred_width_for_height( context: CellAreaContext, widget: Widget, height: number ): [number | null, number | null]; get_request_mode(): SizeRequestMode; has_renderer(renderer: CellRenderer): boolean; inner_cell_area(widget: Widget, cell_area: Gdk.Rectangle): Gdk.Rectangle; is_activatable(): boolean; is_focus_sibling(renderer: CellRenderer, sibling: CellRenderer): boolean; remove(renderer: CellRenderer): void; remove_focus_sibling(renderer: CellRenderer, sibling: CellRenderer): void; request_renderer( renderer: CellRenderer, orientation: Orientation, widget: Widget, for_size: number ): [number | null, number | null]; set_focus_cell(renderer: CellRenderer): void; snapshot( context: CellAreaContext, widget: Widget, snapshot: Snapshot, background_area: Gdk.Rectangle, cell_area: Gdk.Rectangle, flags: CellRendererState, paint_focus: boolean ): void; stop_editing(canceled: boolean): void; vfunc_activate( context: CellAreaContext, widget: Widget, cell_area: Gdk.Rectangle, flags: CellRendererState, edit_only: boolean ): boolean; vfunc_add(renderer: CellRenderer): void; vfunc_apply_attributes( tree_model: TreeModel, iter: TreeIter, is_expander: boolean, is_expanded: boolean ): void; vfunc_copy_context(context: CellAreaContext): CellAreaContext; vfunc_create_context(): CellAreaContext; vfunc_event( context: CellAreaContext, widget: Widget, event: Gdk.Event, cell_area: Gdk.Rectangle, flags: CellRendererState ): number; vfunc_focus(direction: DirectionType): boolean; vfunc_foreach(callback: CellCallback): void; vfunc_foreach_alloc( context: CellAreaContext, widget: Widget, cell_area: Gdk.Rectangle, background_area: Gdk.Rectangle, callback: CellAllocCallback ): void; vfunc_get_cell_property( renderer: CellRenderer, property_id: number, value: any, pspec: GObject.ParamSpec ): void; vfunc_get_preferred_height( context: CellAreaContext, widget: Widget ): [number | null, number | null]; vfunc_get_preferred_height_for_width( context: CellAreaContext, widget: Widget, width: number ): [number | null, number | null]; vfunc_get_preferred_width( context: CellAreaContext, widget: Widget ): [number | null, number | null]; vfunc_get_preferred_width_for_height( context: CellAreaContext, widget: Widget, height: number ): [number | null, number | null]; vfunc_get_request_mode(): SizeRequestMode; vfunc_is_activatable(): boolean; vfunc_remove(renderer: CellRenderer): void; vfunc_set_cell_property( renderer: CellRenderer, property_id: number, value: any, pspec: GObject.ParamSpec ): void; vfunc_snapshot( context: CellAreaContext, widget: Widget, snapshot: Snapshot, background_area: Gdk.Rectangle, cell_area: Gdk.Rectangle, flags: CellRendererState, paint_focus: boolean ): void; // Implemented Members get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; add_attribute(cell: CellRenderer, attribute: string, column: number): void; clear(): void; clear_attributes(cell: CellRenderer): void; get_area(): CellArea | null; get_cells(): CellRenderer[]; pack_end(cell: CellRenderer, expand: boolean): void; pack_start(cell: CellRenderer, expand: boolean): void; reorder(cell: CellRenderer, position: number): void; set_cell_data_func( cell: CellRenderer, func?: CellLayoutDataFunc | null ): void; vfunc_add_attribute( cell: CellRenderer, attribute: string, column: number ): void; vfunc_clear(): void; vfunc_clear_attributes(cell: CellRenderer): void; vfunc_get_area(): CellArea | null; vfunc_get_cells(): CellRenderer[]; vfunc_pack_end(cell: CellRenderer, expand: boolean): void; vfunc_pack_start(cell: CellRenderer, expand: boolean): void; vfunc_reorder(cell: CellRenderer, position: number): void; vfunc_set_cell_data_func( cell: CellRenderer, func?: CellLayoutDataFunc | null ): void; } export namespace CellAreaBox { export interface ConstructorProperties extends CellArea.ConstructorProperties { [key: string]: any; spacing: number; } } export class CellAreaBox extends CellArea implements Buildable, CellLayout, Orientable { static $gtype: GObject.GType<CellAreaBox>; constructor( properties?: Partial<CellAreaBox.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<CellAreaBox.ConstructorProperties>, ...args: any[] ): void; // Properties spacing: number; // Implemented Properties orientation: Orientation; // Constructors static ['new'](): CellAreaBox; // Members get_spacing(): number; pack_end( renderer: CellRenderer, expand: boolean, align: boolean, fixed: boolean ): void; pack_end(...args: never[]): never; pack_start( renderer: CellRenderer, expand: boolean, align: boolean, fixed: boolean ): void; pack_start(...args: never[]): never; set_spacing(spacing: number): void; // Implemented Members get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; add_attribute(cell: CellRenderer, attribute: string, column: number): void; clear(): void; clear_attributes(cell: CellRenderer): void; get_area(): CellArea | null; get_cells(): CellRenderer[]; reorder(cell: CellRenderer, position: number): void; set_cell_data_func( cell: CellRenderer, func?: CellLayoutDataFunc | null ): void; vfunc_add_attribute( cell: CellRenderer, attribute: string, column: number ): void; vfunc_clear(): void; vfunc_clear_attributes(cell: CellRenderer): void; vfunc_get_area(): CellArea | null; vfunc_get_cells(): CellRenderer[]; vfunc_pack_end(cell: CellRenderer, expand: boolean): void; vfunc_pack_start(cell: CellRenderer, expand: boolean): void; vfunc_reorder(cell: CellRenderer, position: number): void; vfunc_set_cell_data_func( cell: CellRenderer, func?: CellLayoutDataFunc | null ): void; get_orientation(): Orientation; set_orientation(orientation: Orientation): void; } export namespace CellAreaContext { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; area: CellArea; minimum_height: number; minimumHeight: number; minimum_width: number; minimumWidth: number; natural_height: number; naturalHeight: number; natural_width: number; naturalWidth: number; } } export class CellAreaContext extends GObject.Object { static $gtype: GObject.GType<CellAreaContext>; constructor( properties?: Partial<CellAreaContext.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<CellAreaContext.ConstructorProperties>, ...args: any[] ): void; // Properties area: CellArea; minimum_height: number; minimumHeight: number; minimum_width: number; minimumWidth: number; natural_height: number; naturalHeight: number; natural_width: number; naturalWidth: number; // Members allocate(width: number, height: number): void; get_allocation(): [number | null, number | null]; get_area(): CellArea; get_preferred_height(): [number | null, number | null]; get_preferred_height_for_width( width: number ): [number | null, number | null]; get_preferred_width(): [number | null, number | null]; get_preferred_width_for_height( height: number ): [number | null, number | null]; push_preferred_height(minimum_height: number, natural_height: number): void; push_preferred_width(minimum_width: number, natural_width: number): void; reset(): void; vfunc_allocate(width: number, height: number): void; vfunc_get_preferred_height_for_width( width: number ): [number | null, number | null]; vfunc_get_preferred_width_for_height( height: number ): [number | null, number | null]; vfunc_reset(): void; } export namespace CellRenderer { export interface ConstructorProperties extends GObject.InitiallyUnowned.ConstructorProperties { [key: string]: any; cell_background: string; cellBackground: string; cell_background_rgba: Gdk.RGBA; cellBackgroundRgba: Gdk.RGBA; cell_background_set: boolean; cellBackgroundSet: boolean; editing: boolean; height: number; is_expanded: boolean; isExpanded: boolean; is_expander: boolean; isExpander: boolean; mode: CellRendererMode; sensitive: boolean; visible: boolean; width: number; xalign: number; xpad: number; yalign: number; ypad: number; } } export abstract class CellRenderer extends GObject.InitiallyUnowned { static $gtype: GObject.GType<CellRenderer>; constructor( properties?: Partial<CellRenderer.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<CellRenderer.ConstructorProperties>, ...args: any[] ): void; // Properties cell_background: string; cellBackground: string; cell_background_rgba: Gdk.RGBA; cellBackgroundRgba: Gdk.RGBA; cell_background_set: boolean; cellBackgroundSet: boolean; editing: boolean; height: number; is_expanded: boolean; isExpanded: boolean; is_expander: boolean; isExpander: boolean; mode: CellRendererMode; sensitive: boolean; visible: boolean; width: number; xalign: number; xpad: number; yalign: number; ypad: number; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'editing-canceled', callback: (_source: this) => void ): number; connect_after( signal: 'editing-canceled', callback: (_source: this) => void ): number; emit(signal: 'editing-canceled'): void; connect( signal: 'editing-started', callback: (_source: this, editable: CellEditable, path: string) => void ): number; connect_after( signal: 'editing-started', callback: (_source: this, editable: CellEditable, path: string) => void ): number; emit(signal: 'editing-started', editable: CellEditable, path: string): void; // Members activate( event: Gdk.Event, widget: Widget, path: string, background_area: Gdk.Rectangle, cell_area: Gdk.Rectangle, flags: CellRendererState ): boolean; get_aligned_area( widget: Widget, flags: CellRendererState, cell_area: Gdk.Rectangle ): Gdk.Rectangle; get_alignment(): [number | null, number | null]; get_fixed_size(): [number | null, number | null]; get_is_expanded(): boolean; get_is_expander(): boolean; get_padding(): [number | null, number | null]; get_preferred_height(widget: Widget): [number | null, number | null]; get_preferred_height_for_width( widget: Widget, width: number ): [number | null, number | null]; get_preferred_size( widget: Widget ): [Requisition | null, Requisition | null]; get_preferred_width(widget: Widget): [number | null, number | null]; get_preferred_width_for_height( widget: Widget, height: number ): [number | null, number | null]; get_request_mode(): SizeRequestMode; get_sensitive(): boolean; get_state(widget: Widget | null, cell_state: CellRendererState): StateFlags; get_visible(): boolean; is_activatable(): boolean; set_alignment(xalign: number, yalign: number): void; set_fixed_size(width: number, height: number): void; set_is_expanded(is_expanded: boolean): void; set_is_expander(is_expander: boolean): void; set_padding(xpad: number, ypad: number): void; set_sensitive(sensitive: boolean): void; set_visible(visible: boolean): void; snapshot( snapshot: Snapshot, widget: Widget, background_area: Gdk.Rectangle, cell_area: Gdk.Rectangle, flags: CellRendererState ): void; start_editing( event: Gdk.Event | null, widget: Widget, path: string, background_area: Gdk.Rectangle, cell_area: Gdk.Rectangle, flags: CellRendererState ): CellEditable | null; stop_editing(canceled: boolean): void; vfunc_activate( event: Gdk.Event, widget: Widget, path: string, background_area: Gdk.Rectangle, cell_area: Gdk.Rectangle, flags: CellRendererState ): boolean; vfunc_editing_canceled(): void; vfunc_editing_started(editable: CellEditable, path: string): void; vfunc_get_aligned_area( widget: Widget, flags: CellRendererState, cell_area: Gdk.Rectangle ): Gdk.Rectangle; vfunc_get_preferred_height(widget: Widget): [number | null, number | null]; vfunc_get_preferred_height_for_width( widget: Widget, width: number ): [number | null, number | null]; vfunc_get_preferred_width(widget: Widget): [number | null, number | null]; vfunc_get_preferred_width_for_height( widget: Widget, height: number ): [number | null, number | null]; vfunc_get_request_mode(): SizeRequestMode; vfunc_snapshot( snapshot: Snapshot, widget: Widget, background_area: Gdk.Rectangle, cell_area: Gdk.Rectangle, flags: CellRendererState ): void; vfunc_start_editing( event: Gdk.Event | null, widget: Widget, path: string, background_area: Gdk.Rectangle, cell_area: Gdk.Rectangle, flags: CellRendererState ): CellEditable | null; } export namespace CellRendererAccel { export interface ConstructorProperties extends CellRendererText.ConstructorProperties { [key: string]: any; accel_key: number; accelKey: number; accel_mode: CellRendererAccelMode; accelMode: CellRendererAccelMode; accel_mods: Gdk.ModifierType; accelMods: Gdk.ModifierType; keycode: number; } } export class CellRendererAccel extends CellRendererText { static $gtype: GObject.GType<CellRendererAccel>; constructor( properties?: Partial<CellRendererAccel.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<CellRendererAccel.ConstructorProperties>, ...args: any[] ): void; // Properties accel_key: number; accelKey: number; accel_mode: CellRendererAccelMode; accelMode: CellRendererAccelMode; accel_mods: Gdk.ModifierType; accelMods: Gdk.ModifierType; keycode: number; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'accel-cleared', callback: (_source: this, path_string: string) => void ): number; connect_after( signal: 'accel-cleared', callback: (_source: this, path_string: string) => void ): number; emit(signal: 'accel-cleared', path_string: string): void; connect( signal: 'accel-edited', callback: ( _source: this, path_string: string, accel_key: number, accel_mods: Gdk.ModifierType, hardware_keycode: number ) => void ): number; connect_after( signal: 'accel-edited', callback: ( _source: this, path_string: string, accel_key: number, accel_mods: Gdk.ModifierType, hardware_keycode: number ) => void ): number; emit( signal: 'accel-edited', path_string: string, accel_key: number, accel_mods: Gdk.ModifierType, hardware_keycode: number ): void; // Constructors static ['new'](): CellRendererAccel; } export namespace CellRendererCombo { export interface ConstructorProperties extends CellRendererText.ConstructorProperties { [key: string]: any; has_entry: boolean; hasEntry: boolean; model: TreeModel; text_column: number; textColumn: number; } } export class CellRendererCombo extends CellRendererText { static $gtype: GObject.GType<CellRendererCombo>; constructor( properties?: Partial<CellRendererCombo.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<CellRendererCombo.ConstructorProperties>, ...args: any[] ): void; // Properties has_entry: boolean; hasEntry: boolean; model: TreeModel; text_column: number; textColumn: number; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'changed', callback: ( _source: this, path_string: string, new_iter: TreeIter ) => void ): number; connect_after( signal: 'changed', callback: ( _source: this, path_string: string, new_iter: TreeIter ) => void ): number; emit(signal: 'changed', path_string: string, new_iter: TreeIter): void; // Constructors static ['new'](): CellRendererCombo; } export namespace CellRendererPixbuf { export interface ConstructorProperties extends CellRenderer.ConstructorProperties { [key: string]: any; gicon: Gio.Icon; icon_name: string; iconName: string; icon_size: IconSize; iconSize: IconSize; pixbuf: GdkPixbuf.Pixbuf; pixbuf_expander_closed: GdkPixbuf.Pixbuf; pixbufExpanderClosed: GdkPixbuf.Pixbuf; pixbuf_expander_open: GdkPixbuf.Pixbuf; pixbufExpanderOpen: GdkPixbuf.Pixbuf; texture: Gdk.Texture; } } export class CellRendererPixbuf extends CellRenderer { static $gtype: GObject.GType<CellRendererPixbuf>; constructor( properties?: Partial<CellRendererPixbuf.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<CellRendererPixbuf.ConstructorProperties>, ...args: any[] ): void; // Properties gicon: Gio.Icon; icon_name: string; iconName: string; icon_size: IconSize; iconSize: IconSize; pixbuf: GdkPixbuf.Pixbuf; pixbuf_expander_closed: GdkPixbuf.Pixbuf; pixbufExpanderClosed: GdkPixbuf.Pixbuf; pixbuf_expander_open: GdkPixbuf.Pixbuf; pixbufExpanderOpen: GdkPixbuf.Pixbuf; texture: Gdk.Texture; // Constructors static ['new'](): CellRendererPixbuf; } export namespace CellRendererProgress { export interface ConstructorProperties extends CellRenderer.ConstructorProperties { [key: string]: any; inverted: boolean; pulse: number; text: string; text_xalign: number; textXalign: number; text_yalign: number; textYalign: number; value: number; } } export class CellRendererProgress extends CellRenderer implements Orientable { static $gtype: GObject.GType<CellRendererProgress>; constructor( properties?: Partial<CellRendererProgress.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<CellRendererProgress.ConstructorProperties>, ...args: any[] ): void; // Properties inverted: boolean; pulse: number; text: string; text_xalign: number; textXalign: number; text_yalign: number; textYalign: number; value: number; // Implemented Properties orientation: Orientation; // Constructors static ['new'](): CellRendererProgress; // Implemented Members get_orientation(): Orientation; set_orientation(orientation: Orientation): void; } export namespace CellRendererSpin { export interface ConstructorProperties extends CellRendererText.ConstructorProperties { [key: string]: any; adjustment: Adjustment; climb_rate: number; climbRate: number; digits: number; } } export class CellRendererSpin extends CellRendererText { static $gtype: GObject.GType<CellRendererSpin>; constructor( properties?: Partial<CellRendererSpin.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<CellRendererSpin.ConstructorProperties>, ...args: any[] ): void; // Properties adjustment: Adjustment; climb_rate: number; climbRate: number; digits: number; // Constructors static ['new'](): CellRendererSpin; } export namespace CellRendererSpinner { export interface ConstructorProperties extends CellRenderer.ConstructorProperties { [key: string]: any; active: boolean; pulse: number; size: IconSize; } } export class CellRendererSpinner extends CellRenderer { static $gtype: GObject.GType<CellRendererSpinner>; constructor( properties?: Partial<CellRendererSpinner.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<CellRendererSpinner.ConstructorProperties>, ...args: any[] ): void; // Properties active: boolean; pulse: number; size: IconSize; // Constructors static ['new'](): CellRendererSpinner; } export namespace CellRendererText { export interface ConstructorProperties extends CellRenderer.ConstructorProperties { [key: string]: any; align_set: boolean; alignSet: boolean; alignment: Pango.Alignment; attributes: Pango.AttrList; background: string; background_rgba: Gdk.RGBA; backgroundRgba: Gdk.RGBA; background_set: boolean; backgroundSet: boolean; editable: boolean; editable_set: boolean; editableSet: boolean; ellipsize: Pango.EllipsizeMode; ellipsize_set: boolean; ellipsizeSet: boolean; family: string; family_set: boolean; familySet: boolean; font: string; font_desc: Pango.FontDescription; fontDesc: Pango.FontDescription; foreground: string; foreground_rgba: Gdk.RGBA; foregroundRgba: Gdk.RGBA; foreground_set: boolean; foregroundSet: boolean; language: string; language_set: boolean; languageSet: boolean; markup: string; max_width_chars: number; maxWidthChars: number; placeholder_text: string; placeholderText: string; rise: number; rise_set: boolean; riseSet: boolean; scale: number; scale_set: boolean; scaleSet: boolean; single_paragraph_mode: boolean; singleParagraphMode: boolean; size: number; size_points: number; sizePoints: number; size_set: boolean; sizeSet: boolean; stretch: Pango.Stretch; stretch_set: boolean; stretchSet: boolean; strikethrough: boolean; strikethrough_set: boolean; strikethroughSet: boolean; style: Pango.Style; style_set: boolean; styleSet: boolean; text: string; underline: Pango.Underline; underline_set: boolean; underlineSet: boolean; variant: Pango.Variant; variant_set: boolean; variantSet: boolean; weight: number; weight_set: boolean; weightSet: boolean; width_chars: number; widthChars: number; wrap_mode: Pango.WrapMode; wrapMode: Pango.WrapMode; wrap_width: number; wrapWidth: number; } } export class CellRendererText extends CellRenderer { static $gtype: GObject.GType<CellRendererText>; constructor( properties?: Partial<CellRendererText.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<CellRendererText.ConstructorProperties>, ...args: any[] ): void; // Properties align_set: boolean; alignSet: boolean; alignment: Pango.Alignment; attributes: Pango.AttrList; background: string; background_rgba: Gdk.RGBA; backgroundRgba: Gdk.RGBA; background_set: boolean; backgroundSet: boolean; editable: boolean; editable_set: boolean; editableSet: boolean; ellipsize: Pango.EllipsizeMode; ellipsize_set: boolean; ellipsizeSet: boolean; family: string; family_set: boolean; familySet: boolean; font: string; font_desc: Pango.FontDescription; fontDesc: Pango.FontDescription; foreground: string; foreground_rgba: Gdk.RGBA; foregroundRgba: Gdk.RGBA; foreground_set: boolean; foregroundSet: boolean; language: string; language_set: boolean; languageSet: boolean; markup: string; max_width_chars: number; maxWidthChars: number; placeholder_text: string; placeholderText: string; rise: number; rise_set: boolean; riseSet: boolean; scale: number; scale_set: boolean; scaleSet: boolean; single_paragraph_mode: boolean; singleParagraphMode: boolean; size: number; size_points: number; sizePoints: number; size_set: boolean; sizeSet: boolean; stretch: Pango.Stretch; stretch_set: boolean; stretchSet: boolean; strikethrough: boolean; strikethrough_set: boolean; strikethroughSet: boolean; style: Pango.Style; style_set: boolean; styleSet: boolean; text: string; underline: Pango.Underline; underline_set: boolean; underlineSet: boolean; variant: Pango.Variant; variant_set: boolean; variantSet: boolean; weight: number; weight_set: boolean; weightSet: boolean; width_chars: number; widthChars: number; wrap_mode: Pango.WrapMode; wrapMode: Pango.WrapMode; wrap_width: number; wrapWidth: number; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'edited', callback: (_source: this, path: string, new_text: string) => void ): number; connect_after( signal: 'edited', callback: (_source: this, path: string, new_text: string) => void ): number; emit(signal: 'edited', path: string, new_text: string): void; // Constructors static ['new'](): CellRendererText; // Members set_fixed_height_from_font(number_of_rows: number): void; vfunc_edited(path: string, new_text: string): void; } export namespace CellRendererToggle { export interface ConstructorProperties extends CellRenderer.ConstructorProperties { [key: string]: any; activatable: boolean; active: boolean; inconsistent: boolean; radio: boolean; } } export class CellRendererToggle extends CellRenderer { static $gtype: GObject.GType<CellRendererToggle>; constructor( properties?: Partial<CellRendererToggle.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<CellRendererToggle.ConstructorProperties>, ...args: any[] ): void; // Properties activatable: boolean; active: boolean; inconsistent: boolean; radio: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'toggled', callback: (_source: this, path: string) => void ): number; connect_after( signal: 'toggled', callback: (_source: this, path: string) => void ): number; emit(signal: 'toggled', path: string): void; // Constructors static ['new'](): CellRendererToggle; // Members get_activatable(): boolean; get_active(): boolean; get_radio(): boolean; set_activatable(setting: boolean): void; set_active(setting: boolean): void; set_radio(radio: boolean): void; } export namespace CellView { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; cell_area: CellArea; cellArea: CellArea; cell_area_context: CellAreaContext; cellAreaContext: CellAreaContext; draw_sensitive: boolean; drawSensitive: boolean; fit_model: boolean; fitModel: boolean; model: TreeModel; } } export class CellView extends Widget implements Accessible, Buildable, CellLayout, ConstraintTarget, Orientable { static $gtype: GObject.GType<CellView>; constructor( properties?: Partial<CellView.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<CellView.ConstructorProperties>, ...args: any[] ): void; // Properties cell_area: CellArea; cellArea: CellArea; cell_area_context: CellAreaContext; cellAreaContext: CellAreaContext; draw_sensitive: boolean; drawSensitive: boolean; fit_model: boolean; fitModel: boolean; model: TreeModel; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; orientation: Orientation; // Constructors static ['new'](): CellView; static new_with_context(area: CellArea, context: CellAreaContext): CellView; static new_with_markup(markup: string): CellView; static new_with_text(text: string): CellView; static new_with_texture(texture: Gdk.Texture): CellView; // Members get_displayed_row(): TreePath | null; get_draw_sensitive(): boolean; get_fit_model(): boolean; get_model(): TreeModel | null; set_displayed_row(path?: TreePath | null): void; set_draw_sensitive(draw_sensitive: boolean): void; set_fit_model(fit_model: boolean): void; set_model(model?: TreeModel | null): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; add_attribute(cell: CellRenderer, attribute: string, column: number): void; clear(): void; clear_attributes(cell: CellRenderer): void; get_area(): CellArea | null; get_cells(): CellRenderer[]; pack_end(cell: CellRenderer, expand: boolean): void; pack_start(cell: CellRenderer, expand: boolean): void; reorder(cell: CellRenderer, position: number): void; set_cell_data_func( cell: CellRenderer, func?: CellLayoutDataFunc | null ): void; vfunc_add_attribute( cell: CellRenderer, attribute: string, column: number ): void; vfunc_clear(): void; vfunc_clear_attributes(cell: CellRenderer): void; vfunc_get_area(): CellArea | null; vfunc_get_cells(): CellRenderer[]; vfunc_pack_end(cell: CellRenderer, expand: boolean): void; vfunc_pack_start(cell: CellRenderer, expand: boolean): void; vfunc_reorder(cell: CellRenderer, position: number): void; vfunc_set_cell_data_func( cell: CellRenderer, func?: CellLayoutDataFunc | null ): void; get_orientation(): Orientation; set_orientation(orientation: Orientation): void; } export namespace CenterBox { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; baseline_position: BaselinePosition; baselinePosition: BaselinePosition; } } export class CenterBox extends Widget implements Accessible, Buildable, ConstraintTarget, Orientable { static $gtype: GObject.GType<CenterBox>; constructor( properties?: Partial<CenterBox.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<CenterBox.ConstructorProperties>, ...args: any[] ): void; // Properties baseline_position: BaselinePosition; baselinePosition: BaselinePosition; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; orientation: Orientation; // Constructors static ['new'](): CenterBox; // Members get_baseline_position(): BaselinePosition; get_center_widget(): Widget | null; get_end_widget(): Widget | null; get_start_widget(): Widget | null; set_baseline_position(position: BaselinePosition): void; set_center_widget(child?: Widget | null): void; set_end_widget(child?: Widget | null): void; set_start_widget(child?: Widget | null): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_orientation(): Orientation; set_orientation(orientation: Orientation): void; } export namespace CenterLayout { export interface ConstructorProperties extends LayoutManager.ConstructorProperties { [key: string]: any; } } export class CenterLayout extends LayoutManager { static $gtype: GObject.GType<CenterLayout>; constructor( properties?: Partial<CenterLayout.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<CenterLayout.ConstructorProperties>, ...args: any[] ): void; // Constructors static ['new'](): CenterLayout; // Members get_baseline_position(): BaselinePosition; get_center_widget(): Widget | null; get_end_widget(): Widget | null; get_orientation(): Orientation; get_start_widget(): Widget | null; set_baseline_position(baseline_position: BaselinePosition): void; set_center_widget(widget?: Widget | null): void; set_end_widget(widget?: Widget | null): void; set_orientation(orientation: Orientation): void; set_start_widget(widget?: Widget | null): void; } export namespace CheckButton { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; active: boolean; group: CheckButton; inconsistent: boolean; label: string; use_underline: boolean; useUnderline: boolean; } } export class CheckButton extends Widget implements Accessible, Actionable, Buildable, ConstraintTarget { static $gtype: GObject.GType<CheckButton>; constructor( properties?: Partial<CheckButton.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<CheckButton.ConstructorProperties>, ...args: any[] ): void; // Properties active: boolean; group: CheckButton; inconsistent: boolean; label: string; use_underline: boolean; useUnderline: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'toggled', callback: (_source: this) => void): number; connect_after(signal: 'toggled', callback: (_source: this) => void): number; emit(signal: 'toggled'): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; action_name: string; actionName: string; action_target: GLib.Variant; actionTarget: GLib.Variant; // Constructors static ['new'](): CheckButton; static new_with_label(label?: string | null): CheckButton; static new_with_mnemonic(label?: string | null): CheckButton; // Members get_active(): boolean; get_inconsistent(): boolean; get_label(): string | null; get_use_underline(): boolean; set_active(setting: boolean): void; set_group(group?: CheckButton | null): void; set_inconsistent(inconsistent: boolean): void; set_label(label?: string | null): void; set_use_underline(setting: boolean): void; vfunc_toggled(): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_action_name(): string | null; get_action_target_value(): GLib.Variant | null; set_action_name(action_name?: string | null): void; set_action_target_value(target_value?: GLib.Variant | null): void; set_detailed_action_name(detailed_action_name: string): void; vfunc_get_action_name(): string | null; vfunc_get_action_target_value(): GLib.Variant | null; vfunc_set_action_name(action_name?: string | null): void; vfunc_set_action_target_value(target_value?: GLib.Variant | null): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace ClosureExpression { export interface ConstructorProperties extends Expression.ConstructorProperties { [key: string]: any; } } export class ClosureExpression extends Expression { static $gtype: GObject.GType<ClosureExpression>; constructor( properties?: Partial<ClosureExpression.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ClosureExpression.ConstructorProperties>, ...args: any[] ): void; // Constructors static ['new']( value_type: GObject.GType, closure: GObject.Closure, params?: Expression[] | null ): ClosureExpression; } export namespace ColorButton { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; modal: boolean; show_editor: boolean; showEditor: boolean; title: string; } } export class ColorButton extends Widget implements Accessible, Buildable, ColorChooser, ConstraintTarget { static $gtype: GObject.GType<ColorButton>; constructor( properties?: Partial<ColorButton.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ColorButton.ConstructorProperties>, ...args: any[] ): void; // Properties modal: boolean; show_editor: boolean; showEditor: boolean; title: string; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'color-set', callback: (_source: this) => void): number; connect_after( signal: 'color-set', callback: (_source: this) => void ): number; emit(signal: 'color-set'): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; rgba: Gdk.RGBA; use_alpha: boolean; useAlpha: boolean; // Constructors static ['new'](): ColorButton; static new_with_rgba(rgba: Gdk.RGBA): ColorButton; // Members get_modal(): boolean; get_title(): string; set_modal(modal: boolean): void; set_title(title: string): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; add_palette( orientation: Orientation, colors_per_line: number, colors?: Gdk.RGBA[] | null ): void; get_rgba(): Gdk.RGBA; get_use_alpha(): boolean; set_rgba(color: Gdk.RGBA): void; set_use_alpha(use_alpha: boolean): void; vfunc_add_palette( orientation: Orientation, colors_per_line: number, colors?: Gdk.RGBA[] | null ): void; vfunc_color_activated(color: Gdk.RGBA): void; vfunc_get_rgba(): Gdk.RGBA; vfunc_set_rgba(color: Gdk.RGBA): void; } export namespace ColorChooserDialog { export interface ConstructorProperties extends Dialog.ConstructorProperties { [key: string]: any; show_editor: boolean; showEditor: boolean; } } export class ColorChooserDialog extends Dialog implements Accessible, Buildable, ColorChooser, ConstraintTarget, Native, Root, ShortcutManager { static $gtype: GObject.GType<ColorChooserDialog>; constructor( properties?: Partial<ColorChooserDialog.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ColorChooserDialog.ConstructorProperties>, ...args: any[] ): void; // Properties show_editor: boolean; showEditor: boolean; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; rgba: Gdk.RGBA; use_alpha: boolean; useAlpha: boolean; // Constructors static ['new']( title?: string | null, parent?: Window | null ): ColorChooserDialog; static ['new'](...args: never[]): never; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; add_palette( orientation: Orientation, colors_per_line: number, colors?: Gdk.RGBA[] | null ): void; get_rgba(): Gdk.RGBA; get_use_alpha(): boolean; set_rgba(color: Gdk.RGBA): void; set_use_alpha(use_alpha: boolean): void; vfunc_add_palette( orientation: Orientation, colors_per_line: number, colors?: Gdk.RGBA[] | null ): void; vfunc_color_activated(color: Gdk.RGBA): void; vfunc_get_rgba(): Gdk.RGBA; vfunc_set_rgba(color: Gdk.RGBA): void; get_renderer(): Gsk.Renderer; get_surface(): Gdk.Surface; get_surface_transform(): [number, number]; realize(): void; unrealize(): void; get_display(): Gdk.Display; get_focus(): Widget | null; set_focus(focus?: Widget | null): void; vfunc_add_controller(controller: ShortcutController): void; vfunc_remove_controller(controller: ShortcutController): void; } export namespace ColorChooserWidget { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; show_editor: boolean; showEditor: boolean; } } export class ColorChooserWidget extends Widget implements Accessible, Buildable, ColorChooser, ConstraintTarget { static $gtype: GObject.GType<ColorChooserWidget>; constructor( properties?: Partial<ColorChooserWidget.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ColorChooserWidget.ConstructorProperties>, ...args: any[] ): void; // Properties show_editor: boolean; showEditor: boolean; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; rgba: Gdk.RGBA; use_alpha: boolean; useAlpha: boolean; // Constructors static ['new'](): ColorChooserWidget; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; add_palette( orientation: Orientation, colors_per_line: number, colors?: Gdk.RGBA[] | null ): void; get_rgba(): Gdk.RGBA; get_use_alpha(): boolean; set_rgba(color: Gdk.RGBA): void; set_use_alpha(use_alpha: boolean): void; vfunc_add_palette( orientation: Orientation, colors_per_line: number, colors?: Gdk.RGBA[] | null ): void; vfunc_color_activated(color: Gdk.RGBA): void; vfunc_get_rgba(): Gdk.RGBA; vfunc_set_rgba(color: Gdk.RGBA): void; } export namespace ColumnView { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; columns: Gio.ListModel; enable_rubberband: boolean; enableRubberband: boolean; model: SelectionModel; reorderable: boolean; show_column_separators: boolean; showColumnSeparators: boolean; show_row_separators: boolean; showRowSeparators: boolean; single_click_activate: boolean; singleClickActivate: boolean; sorter: Sorter; } } export class ColumnView extends Widget implements Accessible, Buildable, ConstraintTarget, Scrollable { static $gtype: GObject.GType<ColumnView>; constructor( properties?: Partial<ColumnView.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ColumnView.ConstructorProperties>, ...args: any[] ): void; // Properties columns: Gio.ListModel; enable_rubberband: boolean; enableRubberband: boolean; model: SelectionModel; reorderable: boolean; show_column_separators: boolean; showColumnSeparators: boolean; show_row_separators: boolean; showRowSeparators: boolean; single_click_activate: boolean; singleClickActivate: boolean; sorter: Sorter; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'activate', callback: (_source: this, position: number) => void ): number; connect_after( signal: 'activate', callback: (_source: this, position: number) => void ): number; emit(signal: 'activate', position: number): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; hadjustment: Adjustment; hscroll_policy: ScrollablePolicy; hscrollPolicy: ScrollablePolicy; vadjustment: Adjustment; vscroll_policy: ScrollablePolicy; vscrollPolicy: ScrollablePolicy; // Constructors static ['new'](model?: SelectionModel | null): ColumnView; // Members append_column(column: ColumnViewColumn): void; get_columns(): Gio.ListModel; get_enable_rubberband(): boolean; get_model(): SelectionModel | null; get_reorderable(): boolean; get_show_column_separators(): boolean; get_show_row_separators(): boolean; get_single_click_activate(): boolean; get_sorter(): Sorter | null; insert_column(position: number, column: ColumnViewColumn): void; remove_column(column: ColumnViewColumn): void; set_enable_rubberband(enable_rubberband: boolean): void; set_model(model?: SelectionModel | null): void; set_reorderable(reorderable: boolean): void; set_show_column_separators(show_column_separators: boolean): void; set_show_row_separators(show_row_separators: boolean): void; set_single_click_activate(single_click_activate: boolean): void; sort_by_column(column: ColumnViewColumn | null, direction: SortType): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_border(): [boolean, Border]; get_hadjustment(): Adjustment; get_hscroll_policy(): ScrollablePolicy; get_vadjustment(): Adjustment; get_vscroll_policy(): ScrollablePolicy; set_hadjustment(hadjustment?: Adjustment | null): void; set_hscroll_policy(policy: ScrollablePolicy): void; set_vadjustment(vadjustment?: Adjustment | null): void; set_vscroll_policy(policy: ScrollablePolicy): void; vfunc_get_border(): [boolean, Border]; } export namespace ColumnViewColumn { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; column_view: ColumnView; columnView: ColumnView; expand: boolean; factory: ListItemFactory; fixed_width: number; fixedWidth: number; header_menu: Gio.MenuModel; headerMenu: Gio.MenuModel; resizable: boolean; sorter: Sorter; title: string; visible: boolean; } } export class ColumnViewColumn extends GObject.Object { static $gtype: GObject.GType<ColumnViewColumn>; constructor( properties?: Partial<ColumnViewColumn.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ColumnViewColumn.ConstructorProperties>, ...args: any[] ): void; // Properties column_view: ColumnView; columnView: ColumnView; expand: boolean; factory: ListItemFactory; fixed_width: number; fixedWidth: number; header_menu: Gio.MenuModel; headerMenu: Gio.MenuModel; resizable: boolean; sorter: Sorter; title: string; visible: boolean; // Constructors static ['new']( title?: string | null, factory?: ListItemFactory | null ): ColumnViewColumn; // Members get_column_view(): ColumnView | null; get_expand(): boolean; get_factory(): ListItemFactory | null; get_fixed_width(): number; get_header_menu(): Gio.MenuModel | null; get_resizable(): boolean; get_sorter(): Sorter | null; get_title(): string | null; get_visible(): boolean; set_expand(expand: boolean): void; set_factory(factory?: ListItemFactory | null): void; set_fixed_width(fixed_width: number): void; set_header_menu(menu?: Gio.MenuModel | null): void; set_resizable(resizable: boolean): void; set_sorter(sorter?: Sorter | null): void; set_title(title?: string | null): void; set_visible(visible: boolean): void; } export namespace ComboBox { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; active: number; active_id: string; activeId: string; button_sensitivity: SensitivityType; buttonSensitivity: SensitivityType; child: Widget; entry_text_column: number; entryTextColumn: number; has_entry: boolean; hasEntry: boolean; has_frame: boolean; hasFrame: boolean; id_column: number; idColumn: number; model: TreeModel; popup_fixed_width: boolean; popupFixedWidth: boolean; popup_shown: boolean; popupShown: boolean; } } export class ComboBox extends Widget implements Accessible, Buildable, CellEditable, CellLayout, ConstraintTarget { static $gtype: GObject.GType<ComboBox>; constructor( properties?: Partial<ComboBox.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ComboBox.ConstructorProperties>, ...args: any[] ): void; // Properties active: number; active_id: string; activeId: string; button_sensitivity: SensitivityType; buttonSensitivity: SensitivityType; child: Widget; entry_text_column: number; entryTextColumn: number; has_entry: boolean; hasEntry: boolean; has_frame: boolean; hasFrame: boolean; id_column: number; idColumn: number; model: TreeModel; popup_fixed_width: boolean; popupFixedWidth: boolean; popup_shown: boolean; popupShown: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'changed', callback: (_source: this) => void): number; connect_after(signal: 'changed', callback: (_source: this) => void): number; emit(signal: 'changed'): void; connect( signal: 'format-entry-text', callback: (_source: this, path: string) => string ): number; connect_after( signal: 'format-entry-text', callback: (_source: this, path: string) => string ): number; emit(signal: 'format-entry-text', path: string): void; connect( signal: 'move-active', callback: (_source: this, scroll_type: ScrollType) => void ): number; connect_after( signal: 'move-active', callback: (_source: this, scroll_type: ScrollType) => void ): number; emit(signal: 'move-active', scroll_type: ScrollType): void; connect(signal: 'popdown', callback: (_source: this) => boolean): number; connect_after( signal: 'popdown', callback: (_source: this) => boolean ): number; emit(signal: 'popdown'): void; connect(signal: 'popup', callback: (_source: this) => void): number; connect_after(signal: 'popup', callback: (_source: this) => void): number; emit(signal: 'popup'): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; editing_canceled: boolean; editingCanceled: boolean; // Constructors static ['new'](): ComboBox; static new_with_entry(): ComboBox; static new_with_model(model: TreeModel): ComboBox; static new_with_model_and_entry(model: TreeModel): ComboBox; // Members get_active(): number; get_active_id(): string | null; get_active_iter(): [boolean, TreeIter]; get_button_sensitivity(): SensitivityType; get_child(): Widget | null; get_entry_text_column(): number; get_has_entry(): boolean; get_id_column(): number; get_model(): TreeModel | null; get_popup_fixed_width(): boolean; popdown(): void; popup(): void; popup_for_device(device: Gdk.Device): void; set_active(index_: number): void; set_active_id(active_id?: string | null): boolean; set_active_iter(iter?: TreeIter | null): void; set_button_sensitivity(sensitivity: SensitivityType): void; set_child(child?: Widget | null): void; set_entry_text_column(text_column: number): void; set_id_column(id_column: number): void; set_model(model?: TreeModel | null): void; set_popup_fixed_width(fixed: boolean): void; set_row_separator_func( func?: TreeViewRowSeparatorFunc | null, destroy?: GLib.DestroyNotify | null ): void; vfunc_changed(): void; vfunc_format_entry_text(path: string): string; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; editing_done(): void; remove_widget(): void; start_editing(event?: Gdk.Event | null): void; vfunc_editing_done(): void; vfunc_remove_widget(): void; vfunc_start_editing(event?: Gdk.Event | null): void; add_attribute(cell: CellRenderer, attribute: string, column: number): void; clear(): void; clear_attributes(cell: CellRenderer): void; get_area(): CellArea | null; get_cells(): CellRenderer[]; pack_end(cell: CellRenderer, expand: boolean): void; pack_start(cell: CellRenderer, expand: boolean): void; reorder(cell: CellRenderer, position: number): void; set_cell_data_func( cell: CellRenderer, func?: CellLayoutDataFunc | null ): void; vfunc_add_attribute( cell: CellRenderer, attribute: string, column: number ): void; vfunc_clear(): void; vfunc_clear_attributes(cell: CellRenderer): void; vfunc_get_area(): CellArea | null; vfunc_get_cells(): CellRenderer[]; vfunc_pack_end(cell: CellRenderer, expand: boolean): void; vfunc_pack_start(cell: CellRenderer, expand: boolean): void; vfunc_reorder(cell: CellRenderer, position: number): void; vfunc_set_cell_data_func( cell: CellRenderer, func?: CellLayoutDataFunc | null ): void; } export namespace ComboBoxText { export interface ConstructorProperties extends ComboBox.ConstructorProperties { [key: string]: any; } } export class ComboBoxText extends ComboBox implements Accessible, Buildable, CellEditable, CellLayout, ConstraintTarget { static $gtype: GObject.GType<ComboBoxText>; constructor( properties?: Partial<ComboBoxText.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ComboBoxText.ConstructorProperties>, ...args: any[] ): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; editing_canceled: boolean; editingCanceled: boolean; // Constructors static ['new'](): ComboBoxText; static new_with_entry(): ComboBoxText; // Members append(id: string | null, text: string): void; append_text(text: string): void; get_active_text(): string | null; insert(position: number, id: string | null, text: string): void; insert_text(position: number, text: string): void; prepend(id: string | null, text: string): void; prepend_text(text: string): void; remove(position: number): void; remove_all(): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; editing_done(): void; remove_widget(): void; start_editing(event?: Gdk.Event | null): void; vfunc_editing_done(): void; vfunc_remove_widget(): void; vfunc_start_editing(event?: Gdk.Event | null): void; add_attribute(cell: CellRenderer, attribute: string, column: number): void; clear(): void; clear_attributes(cell: CellRenderer): void; get_area(): CellArea | null; get_cells(): CellRenderer[]; pack_end(cell: CellRenderer, expand: boolean): void; pack_start(cell: CellRenderer, expand: boolean): void; reorder(cell: CellRenderer, position: number): void; set_cell_data_func( cell: CellRenderer, func?: CellLayoutDataFunc | null ): void; vfunc_add_attribute( cell: CellRenderer, attribute: string, column: number ): void; vfunc_clear(): void; vfunc_clear_attributes(cell: CellRenderer): void; vfunc_get_area(): CellArea | null; vfunc_get_cells(): CellRenderer[]; vfunc_pack_end(cell: CellRenderer, expand: boolean): void; vfunc_pack_start(cell: CellRenderer, expand: boolean): void; vfunc_reorder(cell: CellRenderer, position: number): void; vfunc_set_cell_data_func( cell: CellRenderer, func?: CellLayoutDataFunc | null ): void; } export namespace ConstantExpression { export interface ConstructorProperties extends Expression.ConstructorProperties { [key: string]: any; } } export class ConstantExpression extends Expression { static $gtype: GObject.GType<ConstantExpression>; constructor( properties?: Partial<ConstantExpression.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ConstantExpression.ConstructorProperties>, ...args: any[] ): void; // Constructors static new_for_value(value: any): ConstantExpression; // Members get_value(): unknown; } export namespace Constraint { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; constant: number; multiplier: number; relation: ConstraintRelation; source: ConstraintTarget; source_attribute: ConstraintAttribute; sourceAttribute: ConstraintAttribute; strength: number; target: ConstraintTarget; target_attribute: ConstraintAttribute; targetAttribute: ConstraintAttribute; } } export class Constraint extends GObject.Object { static $gtype: GObject.GType<Constraint>; constructor( properties?: Partial<Constraint.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Constraint.ConstructorProperties>, ...args: any[] ): void; // Properties constant: number; multiplier: number; relation: ConstraintRelation; source: ConstraintTarget; source_attribute: ConstraintAttribute; sourceAttribute: ConstraintAttribute; strength: number; target: ConstraintTarget; target_attribute: ConstraintAttribute; targetAttribute: ConstraintAttribute; // Constructors static ['new']( target: ConstraintTarget | null, target_attribute: ConstraintAttribute, relation: ConstraintRelation, source: ConstraintTarget | null, source_attribute: ConstraintAttribute, multiplier: number, constant: number, strength: number ): Constraint; static new_constant( target: ConstraintTarget | null, target_attribute: ConstraintAttribute, relation: ConstraintRelation, constant: number, strength: number ): Constraint; // Members get_constant(): number; get_multiplier(): number; get_relation(): ConstraintRelation; get_source(): ConstraintTarget | null; get_source_attribute(): ConstraintAttribute; get_strength(): number; get_target(): ConstraintTarget | null; get_target_attribute(): ConstraintAttribute; is_attached(): boolean; is_constant(): boolean; is_required(): boolean; } export namespace ConstraintGuide { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; max_height: number; maxHeight: number; max_width: number; maxWidth: number; min_height: number; minHeight: number; min_width: number; minWidth: number; name: string; nat_height: number; natHeight: number; nat_width: number; natWidth: number; strength: ConstraintStrength; } } export class ConstraintGuide extends GObject.Object implements ConstraintTarget { static $gtype: GObject.GType<ConstraintGuide>; constructor( properties?: Partial<ConstraintGuide.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ConstraintGuide.ConstructorProperties>, ...args: any[] ): void; // Properties max_height: number; maxHeight: number; max_width: number; maxWidth: number; min_height: number; minHeight: number; min_width: number; minWidth: number; name: string; nat_height: number; natHeight: number; nat_width: number; natWidth: number; strength: ConstraintStrength; // Constructors static ['new'](): ConstraintGuide; // Members get_max_size(width?: number | null, height?: number | null): void; get_min_size(width?: number | null, height?: number | null): void; get_name(): string | null; get_nat_size(width?: number | null, height?: number | null): void; get_strength(): ConstraintStrength; set_max_size(width: number, height: number): void; set_min_size(width: number, height: number): void; set_name(name?: string | null): void; set_nat_size(width: number, height: number): void; set_strength(strength: ConstraintStrength): void; } export namespace ConstraintLayout { export interface ConstructorProperties extends LayoutManager.ConstructorProperties { [key: string]: any; } } export class ConstraintLayout extends LayoutManager implements Buildable { static $gtype: GObject.GType<ConstraintLayout>; constructor( properties?: Partial<ConstraintLayout.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ConstraintLayout.ConstructorProperties>, ...args: any[] ): void; // Constructors static ['new'](): ConstraintLayout; // Members add_constraint(constraint: Constraint): void; add_constraints_from_description( lines: string[], hspacing: number, vspacing: number, views: GLib.HashTable<string, ConstraintTarget> ): Constraint[]; add_guide(guide: ConstraintGuide): void; observe_constraints(): Gio.ListModel; observe_guides(): Gio.ListModel; remove_all_constraints(): void; remove_constraint(constraint: Constraint): void; remove_guide(guide: ConstraintGuide): void; // Implemented Members get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace ConstraintLayoutChild { export interface ConstructorProperties extends LayoutChild.ConstructorProperties { [key: string]: any; } } export class ConstraintLayoutChild extends LayoutChild { static $gtype: GObject.GType<ConstraintLayoutChild>; constructor( properties?: Partial<ConstraintLayoutChild.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ConstraintLayoutChild.ConstructorProperties>, ...args: any[] ): void; } export namespace CssProvider { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class CssProvider extends GObject.Object implements StyleProvider { static $gtype: GObject.GType<CssProvider>; constructor( properties?: Partial<CssProvider.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<CssProvider.ConstructorProperties>, ...args: any[] ): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'parsing-error', callback: ( _source: this, section: CssSection, error: GLib.Error ) => void ): number; connect_after( signal: 'parsing-error', callback: ( _source: this, section: CssSection, error: GLib.Error ) => void ): number; emit(signal: 'parsing-error', section: CssSection, error: GLib.Error): void; // Constructors static ['new'](): CssProvider; // Members load_from_data(data: Uint8Array | string): void; load_from_file(file: Gio.File): void; load_from_path(path: string): void; load_from_resource(resource_path: string): void; load_named(name: string, variant?: string | null): void; to_string(): string; } export namespace CustomFilter { export interface ConstructorProperties extends Filter.ConstructorProperties { [key: string]: any; } } export class CustomFilter extends Filter { static $gtype: GObject.GType<CustomFilter>; constructor( properties?: Partial<CustomFilter.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<CustomFilter.ConstructorProperties>, ...args: any[] ): void; // Constructors static ['new'](match_func?: CustomFilterFunc | null): CustomFilter; // Members set_filter_func(match_func?: CustomFilterFunc | null): void; } export namespace CustomLayout { export interface ConstructorProperties extends LayoutManager.ConstructorProperties { [key: string]: any; } } export class CustomLayout extends LayoutManager { static $gtype: GObject.GType<CustomLayout>; constructor( properties?: Partial<CustomLayout.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<CustomLayout.ConstructorProperties>, ...args: any[] ): void; // Constructors static ['new']( request_mode: CustomRequestModeFunc | null, measure: CustomMeasureFunc, allocate: CustomAllocateFunc ): CustomLayout; } export namespace CustomSorter { export interface ConstructorProperties extends Sorter.ConstructorProperties { [key: string]: any; } } export class CustomSorter extends Sorter { static $gtype: GObject.GType<CustomSorter>; constructor( properties?: Partial<CustomSorter.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<CustomSorter.ConstructorProperties>, ...args: any[] ): void; // Constructors static ['new']( sort_func?: GLib.CompareDataFunc | null, user_destroy?: GLib.DestroyNotify | null ): CustomSorter; // Members set_sort_func(sort_func?: GLib.CompareDataFunc | null): void; } export namespace Dialog { export interface ConstructorProperties extends Window.ConstructorProperties { [key: string]: any; use_header_bar: number; useHeaderBar: number; } } export class Dialog extends Window implements Accessible, Buildable, ConstraintTarget, Native, Root, ShortcutManager { static $gtype: GObject.GType<Dialog>; constructor( properties?: Partial<Dialog.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Dialog.ConstructorProperties>, ...args: any[] ): void; // Properties use_header_bar: number; useHeaderBar: number; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'close', callback: (_source: this) => void): number; connect_after(signal: 'close', callback: (_source: this) => void): number; emit(signal: 'close'): void; connect( signal: 'response', callback: (_source: this, response_id: number) => void ): number; connect_after( signal: 'response', callback: (_source: this, response_id: number) => void ): number; emit(signal: 'response', response_id: number): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](): Dialog; // Members add_action_widget(child: Widget, response_id: number): void; add_button(button_text: string, response_id: number): Widget; get_content_area(): Box; get_header_bar(): HeaderBar; get_response_for_widget(widget: Widget): number; get_widget_for_response(response_id: number): Widget | null; response(response_id: number): void; set_default_response(response_id: number): void; set_response_sensitive(response_id: number, setting: boolean): void; vfunc_close(): void; vfunc_response(response_id: number): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_renderer(): Gsk.Renderer; get_surface(): Gdk.Surface; get_surface_transform(): [number, number]; realize(): void; unrealize(): void; get_display(): Gdk.Display; get_focus(): Widget | null; set_focus(focus?: Widget | null): void; vfunc_add_controller(controller: ShortcutController): void; vfunc_remove_controller(controller: ShortcutController): void; } export namespace DirectoryList { export interface ConstructorProperties< A extends GObject.Object = GObject.Object > extends GObject.Object.ConstructorProperties { [key: string]: any; attributes: string; error: GLib.Error; file: Gio.File; io_priority: number; ioPriority: number; loading: boolean; monitored: boolean; } } export class DirectoryList<A extends GObject.Object = GObject.Object> extends GObject.Object implements Gio.ListModel<A> { static $gtype: GObject.GType<DirectoryList>; constructor( properties?: Partial<DirectoryList.ConstructorProperties<A>>, ...args: any[] ); _init( properties?: Partial<DirectoryList.ConstructorProperties<A>>, ...args: any[] ): void; // Properties attributes: string; error: GLib.Error; file: Gio.File; io_priority: number; ioPriority: number; loading: boolean; monitored: boolean; // Constructors static ['new']( attributes?: string | null, file?: Gio.File | null ): DirectoryList; // Members get_attributes(): string | null; get_error(): GLib.Error | null; get_file(): Gio.File | null; get_io_priority(): number; get_monitored(): boolean; is_loading(): boolean; set_attributes(attributes?: string | null): void; set_file(file?: Gio.File | null): void; set_io_priority(io_priority: number): void; set_monitored(monitored: boolean): void; // Implemented Members get_item_type(): GObject.GType; get_n_items(): number; get_item(position: number): A | null; items_changed(position: number, removed: number, added: number): void; vfunc_get_item(position: number): A | null; vfunc_get_item_type(): GObject.GType; vfunc_get_n_items(): number; } export namespace DragIcon { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; child: Widget; } } export class DragIcon extends Widget implements Accessible, Buildable, ConstraintTarget, Native, Root { static $gtype: GObject.GType<DragIcon>; constructor( properties?: Partial<DragIcon.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<DragIcon.ConstructorProperties>, ...args: any[] ): void; // Properties child: Widget; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Members get_child(): Widget | null; set_child(child?: Widget | null): void; static create_widget_for_value(value: any): Widget | null; static get_for_drag(drag: Gdk.Drag): Widget; static set_from_paintable( drag: Gdk.Drag, paintable: Gdk.Paintable, hot_x: number, hot_y: number ): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_renderer(): Gsk.Renderer; get_surface(): Gdk.Surface; get_surface_transform(): [number, number]; realize(): void; unrealize(): void; get_display(): Gdk.Display; get_focus(): Widget | null; set_focus(focus?: Widget | null): void; } export namespace DragSource { export interface ConstructorProperties extends GestureSingle.ConstructorProperties { [key: string]: any; actions: Gdk.DragAction; content: Gdk.ContentProvider; } } export class DragSource extends GestureSingle { static $gtype: GObject.GType<DragSource>; constructor( properties?: Partial<DragSource.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<DragSource.ConstructorProperties>, ...args: any[] ): void; // Properties actions: Gdk.DragAction; content: Gdk.ContentProvider; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'drag-begin', callback: (_source: this, drag: Gdk.Drag) => void ): number; connect_after( signal: 'drag-begin', callback: (_source: this, drag: Gdk.Drag) => void ): number; emit(signal: 'drag-begin', drag: Gdk.Drag): void; connect( signal: 'drag-cancel', callback: ( _source: this, drag: Gdk.Drag, reason: Gdk.DragCancelReason ) => boolean ): number; connect_after( signal: 'drag-cancel', callback: ( _source: this, drag: Gdk.Drag, reason: Gdk.DragCancelReason ) => boolean ): number; emit( signal: 'drag-cancel', drag: Gdk.Drag, reason: Gdk.DragCancelReason ): void; connect( signal: 'drag-end', callback: (_source: this, drag: Gdk.Drag, delete_data: boolean) => void ): number; connect_after( signal: 'drag-end', callback: (_source: this, drag: Gdk.Drag, delete_data: boolean) => void ): number; emit(signal: 'drag-end', drag: Gdk.Drag, delete_data: boolean): void; connect( signal: 'prepare', callback: ( _source: this, x: number, y: number ) => Gdk.ContentProvider | null ): number; connect_after( signal: 'prepare', callback: ( _source: this, x: number, y: number ) => Gdk.ContentProvider | null ): number; emit(signal: 'prepare', x: number, y: number): void; // Constructors static ['new'](): DragSource; // Members drag_cancel(): void; get_actions(): Gdk.DragAction; get_content(): Gdk.ContentProvider | null; get_drag(): Gdk.Drag | null; set_actions(actions: Gdk.DragAction): void; set_content(content?: Gdk.ContentProvider | null): void; set_icon( paintable: Gdk.Paintable | null, hot_x: number, hot_y: number ): void; } export namespace DrawingArea { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; content_height: number; contentHeight: number; content_width: number; contentWidth: number; } } export class DrawingArea extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<DrawingArea>; constructor( properties?: Partial<DrawingArea.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<DrawingArea.ConstructorProperties>, ...args: any[] ): void; // Properties content_height: number; contentHeight: number; content_width: number; contentWidth: number; // Fields widget: Widget; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'resize', callback: (_source: this, width: number, height: number) => void ): number; connect_after( signal: 'resize', callback: (_source: this, width: number, height: number) => void ): number; emit(signal: 'resize', width: number, height: number): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](): DrawingArea; // Members get_content_height(): number; get_content_width(): number; set_content_height(height: number): void; set_content_width(width: number): void; set_draw_func(draw_func?: DrawingAreaDrawFunc | null): void; vfunc_resize(width: number, height: number): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace DropControllerMotion { export interface ConstructorProperties extends EventController.ConstructorProperties { [key: string]: any; contains_pointer: boolean; containsPointer: boolean; drop: Gdk.Drop; is_pointer: boolean; isPointer: boolean; } } export class DropControllerMotion extends EventController { static $gtype: GObject.GType<DropControllerMotion>; constructor( properties?: Partial<DropControllerMotion.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<DropControllerMotion.ConstructorProperties>, ...args: any[] ): void; // Properties contains_pointer: boolean; containsPointer: boolean; drop: Gdk.Drop; is_pointer: boolean; isPointer: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'enter', callback: (_source: this, x: number, y: number) => void ): number; connect_after( signal: 'enter', callback: (_source: this, x: number, y: number) => void ): number; emit(signal: 'enter', x: number, y: number): void; connect(signal: 'leave', callback: (_source: this) => void): number; connect_after(signal: 'leave', callback: (_source: this) => void): number; emit(signal: 'leave'): void; connect( signal: 'motion', callback: (_source: this, x: number, y: number) => void ): number; connect_after( signal: 'motion', callback: (_source: this, x: number, y: number) => void ): number; emit(signal: 'motion', x: number, y: number): void; // Constructors static ['new'](): DropControllerMotion; // Members get_drop(): Gdk.Drop | null; } export namespace DropDown { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; enable_search: boolean; enableSearch: boolean; expression: Expression; factory: ListItemFactory; list_factory: ListItemFactory; listFactory: ListItemFactory; model: Gio.ListModel; selected: number; selected_item: GObject.Object; selectedItem: GObject.Object; } } export class DropDown extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<DropDown>; constructor( properties?: Partial<DropDown.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<DropDown.ConstructorProperties>, ...args: any[] ): void; // Properties enable_search: boolean; enableSearch: boolean; expression: Expression; factory: ListItemFactory; list_factory: ListItemFactory; listFactory: ListItemFactory; model: Gio.ListModel; selected: number; selected_item: GObject.Object; selectedItem: GObject.Object; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new']( model?: Gio.ListModel | null, expression?: Expression | null ): DropDown; static new_from_strings(strings: string[]): DropDown; // Members get_enable_search(): boolean; get_expression(): Expression | null; get_factory(): ListItemFactory | null; get_list_factory(): ListItemFactory | null; get_model(): Gio.ListModel | null; get_selected(): number; get_selected_item<T = GObject.Object>(): T; set_enable_search(enable_search: boolean): void; set_expression(expression?: Expression | null): void; set_factory(factory?: ListItemFactory | null): void; set_list_factory(factory?: ListItemFactory | null): void; set_model(model?: Gio.ListModel | null): void; set_selected(position: number): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace DropTarget { export interface ConstructorProperties extends EventController.ConstructorProperties { [key: string]: any; actions: Gdk.DragAction; drop: Gdk.Drop; formats: Gdk.ContentFormats; preload: boolean; value: GObject.Value; } } export class DropTarget extends EventController { static $gtype: GObject.GType<DropTarget>; constructor( properties?: Partial<DropTarget.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<DropTarget.ConstructorProperties>, ...args: any[] ): void; // Properties actions: Gdk.DragAction; drop: Gdk.Drop; formats: Gdk.ContentFormats; preload: boolean; value: GObject.Value; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'accept', callback: (_source: this, drop: Gdk.Drop) => boolean ): number; connect_after( signal: 'accept', callback: (_source: this, drop: Gdk.Drop) => boolean ): number; emit(signal: 'accept', drop: Gdk.Drop): void; connect( signal: 'drop', callback: ( _source: this, value: GObject.Value, x: number, y: number ) => boolean ): number; connect_after( signal: 'drop', callback: ( _source: this, value: GObject.Value, x: number, y: number ) => boolean ): number; emit(signal: 'drop', value: any, x: number, y: number): void; connect( signal: 'enter', callback: (_source: this, x: number, y: number) => Gdk.DragAction ): number; connect_after( signal: 'enter', callback: (_source: this, x: number, y: number) => Gdk.DragAction ): number; emit(signal: 'enter', x: number, y: number): void; connect(signal: 'leave', callback: (_source: this) => void): number; connect_after(signal: 'leave', callback: (_source: this) => void): number; emit(signal: 'leave'): void; connect( signal: 'motion', callback: (_source: this, x: number, y: number) => Gdk.DragAction ): number; connect_after( signal: 'motion', callback: (_source: this, x: number, y: number) => Gdk.DragAction ): number; emit(signal: 'motion', x: number, y: number): void; // Constructors static ['new'](type: GObject.GType, actions: Gdk.DragAction): DropTarget; // Members get_actions(): Gdk.DragAction; get_drop(): Gdk.Drop | null; get_formats(): Gdk.ContentFormats | null; get_gtypes(): GObject.GType[] | null; get_preload(): boolean; get_value(): GObject.Value | null; reject(): void; set_actions(actions: Gdk.DragAction): void; set_gtypes(types?: GObject.GType[] | null): void; set_preload(preload: boolean): void; } export namespace DropTargetAsync { export interface ConstructorProperties extends EventController.ConstructorProperties { [key: string]: any; actions: Gdk.DragAction; formats: Gdk.ContentFormats; } } export class DropTargetAsync extends EventController { static $gtype: GObject.GType<DropTargetAsync>; constructor( properties?: Partial<DropTargetAsync.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<DropTargetAsync.ConstructorProperties>, ...args: any[] ): void; // Properties actions: Gdk.DragAction; formats: Gdk.ContentFormats; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'accept', callback: (_source: this, drop: Gdk.Drop) => boolean ): number; connect_after( signal: 'accept', callback: (_source: this, drop: Gdk.Drop) => boolean ): number; emit(signal: 'accept', drop: Gdk.Drop): void; connect( signal: 'drag-enter', callback: ( _source: this, drop: Gdk.Drop, x: number, y: number ) => Gdk.DragAction ): number; connect_after( signal: 'drag-enter', callback: ( _source: this, drop: Gdk.Drop, x: number, y: number ) => Gdk.DragAction ): number; emit(signal: 'drag-enter', drop: Gdk.Drop, x: number, y: number): void; connect( signal: 'drag-leave', callback: (_source: this, drop: Gdk.Drop) => void ): number; connect_after( signal: 'drag-leave', callback: (_source: this, drop: Gdk.Drop) => void ): number; emit(signal: 'drag-leave', drop: Gdk.Drop): void; connect( signal: 'drag-motion', callback: ( _source: this, drop: Gdk.Drop, x: number, y: number ) => Gdk.DragAction ): number; connect_after( signal: 'drag-motion', callback: ( _source: this, drop: Gdk.Drop, x: number, y: number ) => Gdk.DragAction ): number; emit(signal: 'drag-motion', drop: Gdk.Drop, x: number, y: number): void; connect( signal: 'drop', callback: ( _source: this, drop: Gdk.Drop, x: number, y: number ) => boolean ): number; connect_after( signal: 'drop', callback: ( _source: this, drop: Gdk.Drop, x: number, y: number ) => boolean ): number; emit(signal: 'drop', drop: Gdk.Drop, x: number, y: number): void; // Constructors static ['new']( formats: Gdk.ContentFormats | null, actions: Gdk.DragAction ): DropTargetAsync; // Members get_actions(): Gdk.DragAction; get_formats(): Gdk.ContentFormats | null; reject_drop(drop: Gdk.Drop): void; set_actions(actions: Gdk.DragAction): void; set_formats(formats?: Gdk.ContentFormats | null): void; } export namespace EditableLabel { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; editing: boolean; } } export class EditableLabel extends Widget implements Accessible, Buildable, ConstraintTarget, Editable { static $gtype: GObject.GType<EditableLabel>; constructor( properties?: Partial<EditableLabel.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<EditableLabel.ConstructorProperties>, ...args: any[] ): void; // Properties editing: boolean; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; cursor_position: number; cursorPosition: number; editable: boolean; enable_undo: boolean; enableUndo: boolean; max_width_chars: number; maxWidthChars: number; selection_bound: number; selectionBound: number; text: string; width_chars: number; widthChars: number; xalign: number; // Constructors static ['new'](str: string): EditableLabel; // Members get_editing(): boolean; start_editing(): void; stop_editing(commit: boolean): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; delete_selection(): void; delete_text(start_pos: number, end_pos: number): void; finish_delegate(): void; get_alignment(): number; get_chars(start_pos: number, end_pos: number): string; get_delegate(): Editable | null; get_editable(): boolean; get_enable_undo(): boolean; get_max_width_chars(): number; get_position(): number; get_selection_bounds(): [boolean, number | null, number | null]; get_text(): string; get_width_chars(): number; init_delegate(): void; insert_text(text: string, length: number, position: number): number; select_region(start_pos: number, end_pos: number): void; set_alignment(xalign: number): void; set_editable(is_editable: boolean): void; set_enable_undo(enable_undo: boolean): void; set_max_width_chars(n_chars: number): void; set_position(position: number): void; set_text(text: string): void; set_width_chars(n_chars: number): void; vfunc_changed(): void; vfunc_delete_text(start_pos: number, end_pos: number): void; vfunc_do_delete_text(start_pos: number, end_pos: number): void; vfunc_do_insert_text( text: string, length: number, position: number ): number; vfunc_get_delegate(): Editable | null; vfunc_get_selection_bounds(): [boolean, number | null, number | null]; vfunc_get_text(): string; vfunc_insert_text(text: string, length: number, position: number): number; vfunc_set_selection_bounds(start_pos: number, end_pos: number): void; } export namespace EmojiChooser { export interface ConstructorProperties extends Popover.ConstructorProperties { [key: string]: any; } } export class EmojiChooser extends Popover implements Accessible, Buildable, ConstraintTarget, Native, ShortcutManager { static $gtype: GObject.GType<EmojiChooser>; constructor( properties?: Partial<EmojiChooser.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<EmojiChooser.ConstructorProperties>, ...args: any[] ): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'emoji-picked', callback: (_source: this, text: string) => void ): number; connect_after( signal: 'emoji-picked', callback: (_source: this, text: string) => void ): number; emit(signal: 'emoji-picked', text: string): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](): EmojiChooser; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_renderer(): Gsk.Renderer; get_surface(): Gdk.Surface; get_surface_transform(): [number, number]; realize(): void; unrealize(): void; vfunc_add_controller(controller: ShortcutController): void; vfunc_remove_controller(controller: ShortcutController): void; } export namespace Entry { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; activates_default: boolean; activatesDefault: boolean; attributes: Pango.AttrList; buffer: EntryBuffer; completion: EntryCompletion; enable_emoji_completion: boolean; enableEmojiCompletion: boolean; extra_menu: Gio.MenuModel; extraMenu: Gio.MenuModel; has_frame: boolean; hasFrame: boolean; im_module: string; imModule: string; input_hints: InputHints; inputHints: InputHints; input_purpose: InputPurpose; inputPurpose: InputPurpose; invisible_char: number; invisibleChar: number; invisible_char_set: boolean; invisibleCharSet: boolean; max_length: number; maxLength: number; overwrite_mode: boolean; overwriteMode: boolean; placeholder_text: string; placeholderText: string; primary_icon_activatable: boolean; primaryIconActivatable: boolean; primary_icon_gicon: Gio.Icon; primaryIconGicon: Gio.Icon; primary_icon_name: string; primaryIconName: string; primary_icon_paintable: Gdk.Paintable; primaryIconPaintable: Gdk.Paintable; primary_icon_sensitive: boolean; primaryIconSensitive: boolean; primary_icon_storage_type: ImageType; primaryIconStorageType: ImageType; primary_icon_tooltip_markup: string; primaryIconTooltipMarkup: string; primary_icon_tooltip_text: string; primaryIconTooltipText: string; progress_fraction: number; progressFraction: number; progress_pulse_step: number; progressPulseStep: number; scroll_offset: number; scrollOffset: number; secondary_icon_activatable: boolean; secondaryIconActivatable: boolean; secondary_icon_gicon: Gio.Icon; secondaryIconGicon: Gio.Icon; secondary_icon_name: string; secondaryIconName: string; secondary_icon_paintable: Gdk.Paintable; secondaryIconPaintable: Gdk.Paintable; secondary_icon_sensitive: boolean; secondaryIconSensitive: boolean; secondary_icon_storage_type: ImageType; secondaryIconStorageType: ImageType; secondary_icon_tooltip_markup: string; secondaryIconTooltipMarkup: string; secondary_icon_tooltip_text: string; secondaryIconTooltipText: string; show_emoji_icon: boolean; showEmojiIcon: boolean; tabs: Pango.TabArray; text_length: number; textLength: number; truncate_multiline: boolean; truncateMultiline: boolean; visibility: boolean; } } export class Entry extends Widget implements Accessible, Buildable, CellEditable, ConstraintTarget, Editable { static $gtype: GObject.GType<Entry>; constructor( properties?: Partial<Entry.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Entry.ConstructorProperties>, ...args: any[] ): void; // Properties activates_default: boolean; activatesDefault: boolean; attributes: Pango.AttrList; buffer: EntryBuffer; completion: EntryCompletion; enable_emoji_completion: boolean; enableEmojiCompletion: boolean; extra_menu: Gio.MenuModel; extraMenu: Gio.MenuModel; has_frame: boolean; hasFrame: boolean; im_module: string; imModule: string; input_hints: InputHints; inputHints: InputHints; input_purpose: InputPurpose; inputPurpose: InputPurpose; invisible_char: number; invisibleChar: number; invisible_char_set: boolean; invisibleCharSet: boolean; max_length: number; maxLength: number; overwrite_mode: boolean; overwriteMode: boolean; placeholder_text: string; placeholderText: string; primary_icon_activatable: boolean; primaryIconActivatable: boolean; primary_icon_gicon: Gio.Icon; primaryIconGicon: Gio.Icon; primary_icon_name: string; primaryIconName: string; primary_icon_paintable: Gdk.Paintable; primaryIconPaintable: Gdk.Paintable; primary_icon_sensitive: boolean; primaryIconSensitive: boolean; primary_icon_storage_type: ImageType; primaryIconStorageType: ImageType; primary_icon_tooltip_markup: string; primaryIconTooltipMarkup: string; primary_icon_tooltip_text: string; primaryIconTooltipText: string; progress_fraction: number; progressFraction: number; progress_pulse_step: number; progressPulseStep: number; scroll_offset: number; scrollOffset: number; secondary_icon_activatable: boolean; secondaryIconActivatable: boolean; secondary_icon_gicon: Gio.Icon; secondaryIconGicon: Gio.Icon; secondary_icon_name: string; secondaryIconName: string; secondary_icon_paintable: Gdk.Paintable; secondaryIconPaintable: Gdk.Paintable; secondary_icon_sensitive: boolean; secondaryIconSensitive: boolean; secondary_icon_storage_type: ImageType; secondaryIconStorageType: ImageType; secondary_icon_tooltip_markup: string; secondaryIconTooltipMarkup: string; secondary_icon_tooltip_text: string; secondaryIconTooltipText: string; show_emoji_icon: boolean; showEmojiIcon: boolean; tabs: Pango.TabArray; text_length: number; textLength: number; truncate_multiline: boolean; truncateMultiline: boolean; visibility: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'activate', callback: (_source: this) => void): number; connect_after( signal: 'activate', callback: (_source: this) => void ): number; emit(signal: 'activate'): void; connect( signal: 'icon-press', callback: (_source: this, icon_pos: EntryIconPosition) => void ): number; connect_after( signal: 'icon-press', callback: (_source: this, icon_pos: EntryIconPosition) => void ): number; emit(signal: 'icon-press', icon_pos: EntryIconPosition): void; connect( signal: 'icon-release', callback: (_source: this, icon_pos: EntryIconPosition) => void ): number; connect_after( signal: 'icon-release', callback: (_source: this, icon_pos: EntryIconPosition) => void ): number; emit(signal: 'icon-release', icon_pos: EntryIconPosition): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; editing_canceled: boolean; editingCanceled: boolean; cursor_position: number; cursorPosition: number; editable: boolean; enable_undo: boolean; enableUndo: boolean; max_width_chars: number; maxWidthChars: number; selection_bound: number; selectionBound: number; text: string; width_chars: number; widthChars: number; xalign: number; // Constructors static ['new'](): Entry; static new_with_buffer(buffer: EntryBuffer): Entry; // Members get_activates_default(): boolean; get_alignment(): number; get_attributes(): Pango.AttrList | null; get_buffer(): EntryBuffer; get_completion(): EntryCompletion | null; get_current_icon_drag_source(): number; get_extra_menu(): Gio.MenuModel | null; get_has_frame(): boolean; get_icon_activatable(icon_pos: EntryIconPosition): boolean; get_icon_area(icon_pos: EntryIconPosition): Gdk.Rectangle; get_icon_at_pos(x: number, y: number): number; get_icon_gicon(icon_pos: EntryIconPosition): Gio.Icon | null; get_icon_name(icon_pos: EntryIconPosition): string | null; get_icon_paintable(icon_pos: EntryIconPosition): Gdk.Paintable | null; get_icon_sensitive(icon_pos: EntryIconPosition): boolean; get_icon_storage_type(icon_pos: EntryIconPosition): ImageType; get_icon_tooltip_markup(icon_pos: EntryIconPosition): string | null; get_icon_tooltip_text(icon_pos: EntryIconPosition): string | null; get_input_hints(): InputHints; get_input_purpose(): InputPurpose; get_invisible_char(): number; get_max_length(): number; get_overwrite_mode(): boolean; get_placeholder_text(): string | null; get_progress_fraction(): number; get_progress_pulse_step(): number; get_tabs(): Pango.TabArray | null; get_text_length(): number; get_visibility(): boolean; grab_focus_without_selecting(): boolean; progress_pulse(): void; reset_im_context(): void; set_activates_default(setting: boolean): void; set_alignment(xalign: number): void; set_attributes(attrs: Pango.AttrList): void; set_buffer(buffer: EntryBuffer): void; set_completion(completion?: EntryCompletion | null): void; set_extra_menu(model?: Gio.MenuModel | null): void; set_has_frame(setting: boolean): void; set_icon_activatable( icon_pos: EntryIconPosition, activatable: boolean ): void; set_icon_drag_source( icon_pos: EntryIconPosition, provider: Gdk.ContentProvider, actions: Gdk.DragAction ): void; set_icon_from_gicon( icon_pos: EntryIconPosition, icon?: Gio.Icon | null ): void; set_icon_from_icon_name( icon_pos: EntryIconPosition, icon_name?: string | null ): void; set_icon_from_paintable( icon_pos: EntryIconPosition, paintable?: Gdk.Paintable | null ): void; set_icon_sensitive(icon_pos: EntryIconPosition, sensitive: boolean): void; set_icon_tooltip_markup( icon_pos: EntryIconPosition, tooltip?: string | null ): void; set_icon_tooltip_text( icon_pos: EntryIconPosition, tooltip?: string | null ): void; set_input_hints(hints: InputHints): void; set_input_purpose(purpose: InputPurpose): void; set_invisible_char(ch: number): void; set_max_length(max: number): void; set_overwrite_mode(overwrite: boolean): void; set_placeholder_text(text?: string | null): void; set_progress_fraction(fraction: number): void; set_progress_pulse_step(fraction: number): void; set_tabs(tabs?: Pango.TabArray | null): void; set_visibility(visible: boolean): void; unset_invisible_char(): void; vfunc_activate(): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; editing_done(): void; remove_widget(): void; start_editing(event?: Gdk.Event | null): void; vfunc_editing_done(): void; vfunc_remove_widget(): void; vfunc_start_editing(event?: Gdk.Event | null): void; delete_selection(): void; delete_text(start_pos: number, end_pos: number): void; finish_delegate(): void; get_chars(start_pos: number, end_pos: number): string; get_delegate(): Editable | null; get_editable(): boolean; get_enable_undo(): boolean; get_max_width_chars(): number; get_position(): number; get_selection_bounds(): [boolean, number | null, number | null]; get_text(): string; get_width_chars(): number; init_delegate(): void; insert_text(text: string, length: number, position: number): number; select_region(start_pos: number, end_pos: number): void; set_editable(is_editable: boolean): void; set_enable_undo(enable_undo: boolean): void; set_max_width_chars(n_chars: number): void; set_position(position: number): void; set_text(text: string): void; set_width_chars(n_chars: number): void; vfunc_changed(): void; vfunc_delete_text(start_pos: number, end_pos: number): void; vfunc_do_delete_text(start_pos: number, end_pos: number): void; vfunc_do_insert_text( text: string, length: number, position: number ): number; vfunc_get_delegate(): Editable | null; vfunc_get_selection_bounds(): [boolean, number | null, number | null]; vfunc_get_text(): string; vfunc_insert_text(text: string, length: number, position: number): number; vfunc_set_selection_bounds(start_pos: number, end_pos: number): void; } export namespace EntryBuffer { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; length: number; max_length: number; maxLength: number; text: string; } } export class EntryBuffer extends GObject.Object { static $gtype: GObject.GType<EntryBuffer>; constructor( properties?: Partial<EntryBuffer.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<EntryBuffer.ConstructorProperties>, ...args: any[] ): void; // Properties length: number; max_length: number; maxLength: number; text: string; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'deleted-text', callback: (_source: this, position: number, n_chars: number) => void ): number; connect_after( signal: 'deleted-text', callback: (_source: this, position: number, n_chars: number) => void ): number; emit(signal: 'deleted-text', position: number, n_chars: number): void; connect( signal: 'inserted-text', callback: ( _source: this, position: number, chars: string, n_chars: number ) => void ): number; connect_after( signal: 'inserted-text', callback: ( _source: this, position: number, chars: string, n_chars: number ) => void ): number; emit( signal: 'inserted-text', position: number, chars: string, n_chars: number ): void; // Constructors static ['new']( initial_chars: string | null, n_initial_chars: number ): EntryBuffer; // Members delete_text(position: number, n_chars: number): number; emit_deleted_text(position: number, n_chars: number): void; emit_inserted_text(position: number, chars: string, n_chars: number): void; get_bytes(): number; get_length(): number; get_max_length(): number; get_text(): string; insert_text(position: number, chars: string, n_chars: number): number; set_max_length(max_length: number): void; set_text(chars: string, n_chars: number): void; vfunc_delete_text(position: number, n_chars: number): number; vfunc_deleted_text(position: number, n_chars: number): void; vfunc_get_length(): number; vfunc_get_text(n_bytes: number): string; vfunc_insert_text(position: number, chars: string, n_chars: number): number; vfunc_inserted_text(position: number, chars: string, n_chars: number): void; } export namespace EntryCompletion { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; cell_area: CellArea; cellArea: CellArea; inline_completion: boolean; inlineCompletion: boolean; inline_selection: boolean; inlineSelection: boolean; minimum_key_length: number; minimumKeyLength: number; model: TreeModel; popup_completion: boolean; popupCompletion: boolean; popup_set_width: boolean; popupSetWidth: boolean; popup_single_match: boolean; popupSingleMatch: boolean; text_column: number; textColumn: number; } } export class EntryCompletion extends GObject.Object implements Buildable, CellLayout { static $gtype: GObject.GType<EntryCompletion>; constructor( properties?: Partial<EntryCompletion.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<EntryCompletion.ConstructorProperties>, ...args: any[] ): void; // Properties cell_area: CellArea; cellArea: CellArea; inline_completion: boolean; inlineCompletion: boolean; inline_selection: boolean; inlineSelection: boolean; minimum_key_length: number; minimumKeyLength: number; model: TreeModel; popup_completion: boolean; popupCompletion: boolean; popup_set_width: boolean; popupSetWidth: boolean; popup_single_match: boolean; popupSingleMatch: boolean; text_column: number; textColumn: number; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'cursor-on-match', callback: (_source: this, model: TreeModel, iter: TreeIter) => boolean ): number; connect_after( signal: 'cursor-on-match', callback: (_source: this, model: TreeModel, iter: TreeIter) => boolean ): number; emit(signal: 'cursor-on-match', model: TreeModel, iter: TreeIter): void; connect( signal: 'insert-prefix', callback: (_source: this, prefix: string) => boolean ): number; connect_after( signal: 'insert-prefix', callback: (_source: this, prefix: string) => boolean ): number; emit(signal: 'insert-prefix', prefix: string): void; connect( signal: 'match-selected', callback: (_source: this, model: TreeModel, iter: TreeIter) => boolean ): number; connect_after( signal: 'match-selected', callback: (_source: this, model: TreeModel, iter: TreeIter) => boolean ): number; emit(signal: 'match-selected', model: TreeModel, iter: TreeIter): void; connect(signal: 'no-matches', callback: (_source: this) => void): number; connect_after( signal: 'no-matches', callback: (_source: this) => void ): number; emit(signal: 'no-matches'): void; // Constructors static ['new'](): EntryCompletion; static new_with_area(area: CellArea): EntryCompletion; // Members complete(): void; compute_prefix(key: string): string | null; get_completion_prefix(): string | null; get_entry(): Widget; get_inline_completion(): boolean; get_inline_selection(): boolean; get_minimum_key_length(): number; get_model(): TreeModel | null; get_popup_completion(): boolean; get_popup_set_width(): boolean; get_popup_single_match(): boolean; get_text_column(): number; insert_prefix(): void; set_inline_completion(inline_completion: boolean): void; set_inline_selection(inline_selection: boolean): void; set_match_func(func: EntryCompletionMatchFunc): void; set_minimum_key_length(length: number): void; set_model(model?: TreeModel | null): void; set_popup_completion(popup_completion: boolean): void; set_popup_set_width(popup_set_width: boolean): void; set_popup_single_match(popup_single_match: boolean): void; set_text_column(column: number): void; // Implemented Members get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; add_attribute(cell: CellRenderer, attribute: string, column: number): void; clear(): void; clear_attributes(cell: CellRenderer): void; get_area(): CellArea | null; get_cells(): CellRenderer[]; pack_end(cell: CellRenderer, expand: boolean): void; pack_start(cell: CellRenderer, expand: boolean): void; reorder(cell: CellRenderer, position: number): void; set_cell_data_func( cell: CellRenderer, func?: CellLayoutDataFunc | null ): void; vfunc_add_attribute( cell: CellRenderer, attribute: string, column: number ): void; vfunc_clear(): void; vfunc_clear_attributes(cell: CellRenderer): void; vfunc_get_area(): CellArea | null; vfunc_get_cells(): CellRenderer[]; vfunc_pack_end(cell: CellRenderer, expand: boolean): void; vfunc_pack_start(cell: CellRenderer, expand: boolean): void; vfunc_reorder(cell: CellRenderer, position: number): void; vfunc_set_cell_data_func( cell: CellRenderer, func?: CellLayoutDataFunc | null ): void; } export namespace EventController { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; name: string; propagation_limit: PropagationLimit; propagationLimit: PropagationLimit; propagation_phase: PropagationPhase; propagationPhase: PropagationPhase; widget: Widget; } } export abstract class EventController extends GObject.Object { static $gtype: GObject.GType<EventController>; constructor( properties?: Partial<EventController.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<EventController.ConstructorProperties>, ...args: any[] ): void; // Properties name: string; propagation_limit: PropagationLimit; propagationLimit: PropagationLimit; propagation_phase: PropagationPhase; propagationPhase: PropagationPhase; widget: Widget; // Members get_current_event(): Gdk.Event | null; get_current_event_device(): Gdk.Device | null; get_current_event_state(): Gdk.ModifierType; get_current_event_time(): number; get_name(): string; get_propagation_limit(): PropagationLimit; get_propagation_phase(): PropagationPhase; get_widget(): Widget; reset(): void; set_name(name: string): void; set_propagation_limit(limit: PropagationLimit): void; set_propagation_phase(phase: PropagationPhase): void; } export namespace EventControllerFocus { export interface ConstructorProperties extends EventController.ConstructorProperties { [key: string]: any; contains_focus: boolean; containsFocus: boolean; is_focus: boolean; isFocus: boolean; } } export class EventControllerFocus extends EventController { static $gtype: GObject.GType<EventControllerFocus>; constructor( properties?: Partial<EventControllerFocus.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<EventControllerFocus.ConstructorProperties>, ...args: any[] ): void; // Properties contains_focus: boolean; containsFocus: boolean; is_focus: boolean; isFocus: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'enter', callback: (_source: this) => void): number; connect_after(signal: 'enter', callback: (_source: this) => void): number; emit(signal: 'enter'): void; connect(signal: 'leave', callback: (_source: this) => void): number; connect_after(signal: 'leave', callback: (_source: this) => void): number; emit(signal: 'leave'): void; // Constructors static ['new'](): EventControllerFocus; } export namespace EventControllerKey { export interface ConstructorProperties extends EventController.ConstructorProperties { [key: string]: any; } } export class EventControllerKey extends EventController { static $gtype: GObject.GType<EventControllerKey>; constructor( properties?: Partial<EventControllerKey.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<EventControllerKey.ConstructorProperties>, ...args: any[] ): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'im-update', callback: (_source: this) => void): number; connect_after( signal: 'im-update', callback: (_source: this) => void ): number; emit(signal: 'im-update'): void; connect( signal: 'key-pressed', callback: ( _source: this, keyval: number, keycode: number, state: Gdk.ModifierType ) => boolean ): number; connect_after( signal: 'key-pressed', callback: ( _source: this, keyval: number, keycode: number, state: Gdk.ModifierType ) => boolean ): number; emit( signal: 'key-pressed', keyval: number, keycode: number, state: Gdk.ModifierType ): void; connect( signal: 'key-released', callback: ( _source: this, keyval: number, keycode: number, state: Gdk.ModifierType ) => void ): number; connect_after( signal: 'key-released', callback: ( _source: this, keyval: number, keycode: number, state: Gdk.ModifierType ) => void ): number; emit( signal: 'key-released', keyval: number, keycode: number, state: Gdk.ModifierType ): void; connect( signal: 'modifiers', callback: (_source: this, keyval: Gdk.ModifierType) => boolean ): number; connect_after( signal: 'modifiers', callback: (_source: this, keyval: Gdk.ModifierType) => boolean ): number; emit(signal: 'modifiers', keyval: Gdk.ModifierType): void; // Constructors static ['new'](): EventControllerKey; // Members forward(widget: Widget): boolean; get_group(): number; get_im_context(): IMContext; set_im_context(im_context: IMContext): void; } export namespace EventControllerLegacy { export interface ConstructorProperties extends EventController.ConstructorProperties { [key: string]: any; } } export class EventControllerLegacy extends EventController { static $gtype: GObject.GType<EventControllerLegacy>; constructor( properties?: Partial<EventControllerLegacy.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<EventControllerLegacy.ConstructorProperties>, ...args: any[] ): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'event', callback: (_source: this, event: Gdk.Event) => boolean ): number; connect_after( signal: 'event', callback: (_source: this, event: Gdk.Event) => boolean ): number; emit(signal: 'event', event: Gdk.Event): void; // Constructors static ['new'](): EventControllerLegacy; } export namespace EventControllerMotion { export interface ConstructorProperties extends EventController.ConstructorProperties { [key: string]: any; contains_pointer: boolean; containsPointer: boolean; is_pointer: boolean; isPointer: boolean; } } export class EventControllerMotion extends EventController { static $gtype: GObject.GType<EventControllerMotion>; constructor( properties?: Partial<EventControllerMotion.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<EventControllerMotion.ConstructorProperties>, ...args: any[] ): void; // Properties contains_pointer: boolean; containsPointer: boolean; is_pointer: boolean; isPointer: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'enter', callback: (_source: this, x: number, y: number) => void ): number; connect_after( signal: 'enter', callback: (_source: this, x: number, y: number) => void ): number; emit(signal: 'enter', x: number, y: number): void; connect(signal: 'leave', callback: (_source: this) => void): number; connect_after(signal: 'leave', callback: (_source: this) => void): number; emit(signal: 'leave'): void; connect( signal: 'motion', callback: (_source: this, x: number, y: number) => void ): number; connect_after( signal: 'motion', callback: (_source: this, x: number, y: number) => void ): number; emit(signal: 'motion', x: number, y: number): void; // Constructors static ['new'](): EventControllerMotion; } export namespace EventControllerScroll { export interface ConstructorProperties extends EventController.ConstructorProperties { [key: string]: any; flags: EventControllerScrollFlags; } } export class EventControllerScroll extends EventController { static $gtype: GObject.GType<EventControllerScroll>; constructor( properties?: Partial<EventControllerScroll.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<EventControllerScroll.ConstructorProperties>, ...args: any[] ): void; // Properties flags: EventControllerScrollFlags; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'decelerate', callback: (_source: this, vel_x: number, vel_y: number) => void ): number; connect_after( signal: 'decelerate', callback: (_source: this, vel_x: number, vel_y: number) => void ): number; emit(signal: 'decelerate', vel_x: number, vel_y: number): void; connect( signal: 'scroll', callback: (_source: this, dx: number, dy: number) => boolean ): number; connect_after( signal: 'scroll', callback: (_source: this, dx: number, dy: number) => boolean ): number; emit(signal: 'scroll', dx: number, dy: number): void; connect(signal: 'scroll-begin', callback: (_source: this) => void): number; connect_after( signal: 'scroll-begin', callback: (_source: this) => void ): number; emit(signal: 'scroll-begin'): void; connect(signal: 'scroll-end', callback: (_source: this) => void): number; connect_after( signal: 'scroll-end', callback: (_source: this) => void ): number; emit(signal: 'scroll-end'): void; // Constructors static ['new'](flags: EventControllerScrollFlags): EventControllerScroll; // Members get_flags(): EventControllerScrollFlags; set_flags(flags: EventControllerScrollFlags): void; } export namespace EveryFilter { export interface ConstructorProperties< A extends GObject.Object = GObject.Object > extends MultiFilter.ConstructorProperties<A> { [key: string]: any; } } export class EveryFilter<A extends GObject.Object = GObject.Object> extends MultiFilter<A> implements Gio.ListModel<A>, Buildable { static $gtype: GObject.GType<EveryFilter>; constructor( properties?: Partial<EveryFilter.ConstructorProperties<A>>, ...args: any[] ); _init( properties?: Partial<EveryFilter.ConstructorProperties<A>>, ...args: any[] ): void; // Constructors static ['new'](): EveryFilter; // Implemented Members get_item_type(): GObject.GType; get_n_items(): number; get_item(position: number): A | null; items_changed(position: number, removed: number, added: number): void; vfunc_get_item(position: number): A | null; vfunc_get_item_type(): GObject.GType; vfunc_get_n_items(): number; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace Expander { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; child: Widget; expanded: boolean; label: string; label_widget: Widget; labelWidget: Widget; resize_toplevel: boolean; resizeToplevel: boolean; use_markup: boolean; useMarkup: boolean; use_underline: boolean; useUnderline: boolean; } } export class Expander extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<Expander>; constructor( properties?: Partial<Expander.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Expander.ConstructorProperties>, ...args: any[] ): void; // Properties child: Widget; expanded: boolean; label: string; label_widget: Widget; labelWidget: Widget; resize_toplevel: boolean; resizeToplevel: boolean; use_markup: boolean; useMarkup: boolean; use_underline: boolean; useUnderline: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'activate', callback: (_source: this) => void): number; connect_after( signal: 'activate', callback: (_source: this) => void ): number; emit(signal: 'activate'): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](label?: string | null): Expander; static new_with_mnemonic(label?: string | null): Expander; // Members get_child(): Widget | null; get_expanded(): boolean; get_label(): string | null; get_label_widget(): Widget | null; get_resize_toplevel(): boolean; get_use_markup(): boolean; get_use_underline(): boolean; set_child(child?: Widget | null): void; set_expanded(expanded: boolean): void; set_label(label?: string | null): void; set_label_widget(label_widget?: Widget | null): void; set_resize_toplevel(resize_toplevel: boolean): void; set_use_markup(use_markup: boolean): void; set_use_underline(use_underline: boolean): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace Expression { export interface ConstructorProperties { [key: string]: any; } } export abstract class Expression { static $gtype: GObject.GType<Expression>; constructor( properties?: Partial<Expression.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Expression.ConstructorProperties>, ...args: any[] ): void; // Members bind( target: GObject.Object, property: string, this_?: GObject.Object | null ): ExpressionWatch; evaluate(this_: GObject.Object | null, value: any): boolean; get_value_type(): GObject.GType; is_static(): boolean; ref(): Expression; unref(): void; watch( this_: GObject.Object | null, notify: ExpressionNotify ): ExpressionWatch; } export namespace FileChooserDialog { export interface ConstructorProperties extends Dialog.ConstructorProperties { [key: string]: any; } } export class FileChooserDialog extends Dialog implements Accessible, Buildable, ConstraintTarget, FileChooser, Native, Root, ShortcutManager { static $gtype: GObject.GType<FileChooserDialog>; constructor( properties?: Partial<FileChooserDialog.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<FileChooserDialog.ConstructorProperties>, ...args: any[] ): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; action: FileChooserAction; create_folders: boolean; createFolders: boolean; filter: FileFilter; filters: Gio.ListModel; select_multiple: boolean; selectMultiple: boolean; shortcut_folders: Gio.ListModel; shortcutFolders: Gio.ListModel; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; add_choice( id: string, label: string, options?: string[] | null, option_labels?: string[] | null ): void; add_filter(filter: FileFilter): void; add_shortcut_folder(folder: Gio.File): boolean; get_action(): FileChooserAction; get_choice(id: string): string; get_create_folders(): boolean; get_current_folder(): Gio.File; get_current_name(): string; get_file(): Gio.File; get_files(): Gio.ListModel; get_filter(): FileFilter | null; get_filters(): Gio.ListModel; get_select_multiple(): boolean; get_shortcut_folders(): Gio.ListModel; remove_choice(id: string): void; remove_filter(filter: FileFilter): void; remove_shortcut_folder(folder: Gio.File): boolean; set_action(action: FileChooserAction): void; set_choice(id: string, option: string): void; set_create_folders(create_folders: boolean): void; set_current_folder(file: Gio.File): boolean; set_current_name(name: string): void; set_file(file: Gio.File): boolean; set_filter(filter: FileFilter): void; set_select_multiple(select_multiple: boolean): void; get_renderer(): Gsk.Renderer; get_surface(): Gdk.Surface; get_surface_transform(): [number, number]; realize(): void; unrealize(): void; get_display(): Gdk.Display; get_focus(): Widget | null; set_focus(focus?: Widget | null): void; vfunc_add_controller(controller: ShortcutController): void; vfunc_remove_controller(controller: ShortcutController): void; } export namespace FileChooserNative { export interface ConstructorProperties extends NativeDialog.ConstructorProperties { [key: string]: any; accept_label: string; acceptLabel: string; cancel_label: string; cancelLabel: string; } } export class FileChooserNative extends NativeDialog implements FileChooser { static $gtype: GObject.GType<FileChooserNative>; constructor( properties?: Partial<FileChooserNative.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<FileChooserNative.ConstructorProperties>, ...args: any[] ): void; // Properties accept_label: string; acceptLabel: string; cancel_label: string; cancelLabel: string; // Implemented Properties action: FileChooserAction; create_folders: boolean; createFolders: boolean; filter: FileFilter; filters: Gio.ListModel; select_multiple: boolean; selectMultiple: boolean; shortcut_folders: Gio.ListModel; shortcutFolders: Gio.ListModel; // Constructors static ['new']( title: string | null, parent: Window | null, action: FileChooserAction, accept_label?: string | null, cancel_label?: string | null ): FileChooserNative; // Members get_accept_label(): string | null; get_cancel_label(): string | null; set_accept_label(accept_label?: string | null): void; set_cancel_label(cancel_label?: string | null): void; // Implemented Members add_choice( id: string, label: string, options?: string[] | null, option_labels?: string[] | null ): void; add_filter(filter: FileFilter): void; add_shortcut_folder(folder: Gio.File): boolean; get_action(): FileChooserAction; get_choice(id: string): string; get_create_folders(): boolean; get_current_folder(): Gio.File; get_current_name(): string; get_file(): Gio.File; get_files(): Gio.ListModel; get_filter(): FileFilter | null; get_filters(): Gio.ListModel; get_select_multiple(): boolean; get_shortcut_folders(): Gio.ListModel; remove_choice(id: string): void; remove_filter(filter: FileFilter): void; remove_shortcut_folder(folder: Gio.File): boolean; set_action(action: FileChooserAction): void; set_choice(id: string, option: string): void; set_create_folders(create_folders: boolean): void; set_current_folder(file: Gio.File): boolean; set_current_name(name: string): void; set_file(file: Gio.File): boolean; set_filter(filter: FileFilter): void; set_select_multiple(select_multiple: boolean): void; } export namespace FileChooserWidget { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; search_mode: boolean; searchMode: boolean; subtitle: string; } } export class FileChooserWidget extends Widget implements Accessible, Buildable, ConstraintTarget, FileChooser { static $gtype: GObject.GType<FileChooserWidget>; constructor( properties?: Partial<FileChooserWidget.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<FileChooserWidget.ConstructorProperties>, ...args: any[] ): void; // Properties search_mode: boolean; searchMode: boolean; subtitle: string; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'desktop-folder', callback: (_source: this) => void ): number; connect_after( signal: 'desktop-folder', callback: (_source: this) => void ): number; emit(signal: 'desktop-folder'): void; connect(signal: 'down-folder', callback: (_source: this) => void): number; connect_after( signal: 'down-folder', callback: (_source: this) => void ): number; emit(signal: 'down-folder'): void; connect(signal: 'home-folder', callback: (_source: this) => void): number; connect_after( signal: 'home-folder', callback: (_source: this) => void ): number; emit(signal: 'home-folder'): void; connect( signal: 'location-popup', callback: (_source: this, path: string) => void ): number; connect_after( signal: 'location-popup', callback: (_source: this, path: string) => void ): number; emit(signal: 'location-popup', path: string): void; connect( signal: 'location-popup-on-paste', callback: (_source: this) => void ): number; connect_after( signal: 'location-popup-on-paste', callback: (_source: this) => void ): number; emit(signal: 'location-popup-on-paste'): void; connect( signal: 'location-toggle-popup', callback: (_source: this) => void ): number; connect_after( signal: 'location-toggle-popup', callback: (_source: this) => void ): number; emit(signal: 'location-toggle-popup'): void; connect( signal: 'places-shortcut', callback: (_source: this) => void ): number; connect_after( signal: 'places-shortcut', callback: (_source: this) => void ): number; emit(signal: 'places-shortcut'): void; connect( signal: 'quick-bookmark', callback: (_source: this, bookmark_index: number) => void ): number; connect_after( signal: 'quick-bookmark', callback: (_source: this, bookmark_index: number) => void ): number; emit(signal: 'quick-bookmark', bookmark_index: number): void; connect( signal: 'recent-shortcut', callback: (_source: this) => void ): number; connect_after( signal: 'recent-shortcut', callback: (_source: this) => void ): number; emit(signal: 'recent-shortcut'): void; connect( signal: 'search-shortcut', callback: (_source: this) => void ): number; connect_after( signal: 'search-shortcut', callback: (_source: this) => void ): number; emit(signal: 'search-shortcut'): void; connect(signal: 'show-hidden', callback: (_source: this) => void): number; connect_after( signal: 'show-hidden', callback: (_source: this) => void ): number; emit(signal: 'show-hidden'): void; connect(signal: 'up-folder', callback: (_source: this) => void): number; connect_after( signal: 'up-folder', callback: (_source: this) => void ): number; emit(signal: 'up-folder'): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; action: FileChooserAction; create_folders: boolean; createFolders: boolean; filter: FileFilter; filters: Gio.ListModel; select_multiple: boolean; selectMultiple: boolean; shortcut_folders: Gio.ListModel; shortcutFolders: Gio.ListModel; // Constructors static ['new'](action: FileChooserAction): FileChooserWidget; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; add_choice( id: string, label: string, options?: string[] | null, option_labels?: string[] | null ): void; add_filter(filter: FileFilter): void; add_shortcut_folder(folder: Gio.File): boolean; get_action(): FileChooserAction; get_choice(id: string): string; get_create_folders(): boolean; get_current_folder(): Gio.File; get_current_name(): string; get_file(): Gio.File; get_files(): Gio.ListModel; get_filter(): FileFilter | null; get_filters(): Gio.ListModel; get_select_multiple(): boolean; get_shortcut_folders(): Gio.ListModel; remove_choice(id: string): void; remove_filter(filter: FileFilter): void; remove_shortcut_folder(folder: Gio.File): boolean; set_action(action: FileChooserAction): void; set_choice(id: string, option: string): void; set_create_folders(create_folders: boolean): void; set_current_folder(file: Gio.File): boolean; set_current_name(name: string): void; set_file(file: Gio.File): boolean; set_filter(filter: FileFilter): void; set_select_multiple(select_multiple: boolean): void; } export namespace FileFilter { export interface ConstructorProperties extends Filter.ConstructorProperties { [key: string]: any; name: string; } } export class FileFilter extends Filter implements Buildable { static $gtype: GObject.GType<FileFilter>; constructor( properties?: Partial<FileFilter.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<FileFilter.ConstructorProperties>, ...args: any[] ): void; // Properties name: string; // Constructors static ['new'](): FileFilter; static new_from_gvariant(variant: GLib.Variant): FileFilter; // Members add_mime_type(mime_type: string): void; add_pattern(pattern: string): void; add_pixbuf_formats(): void; get_attributes(): string[]; get_name(): string | null; set_name(name?: string | null): void; to_gvariant(): GLib.Variant; // Implemented Members get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace Filter { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class Filter extends GObject.Object { static $gtype: GObject.GType<Filter>; constructor( properties?: Partial<Filter.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Filter.ConstructorProperties>, ...args: any[] ): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'changed', callback: (_source: this, change: FilterChange) => void ): number; connect_after( signal: 'changed', callback: (_source: this, change: FilterChange) => void ): number; emit(signal: 'changed', change: FilterChange): void; // Members changed(change: FilterChange): void; get_strictness(): FilterMatch; match(item: GObject.Object): boolean; vfunc_get_strictness(): FilterMatch; vfunc_match(item?: GObject.Object | null): boolean; } export namespace FilterListModel { export interface ConstructorProperties< A extends GObject.Object = GObject.Object > extends GObject.Object.ConstructorProperties { [key: string]: any; filter: Filter; incremental: boolean; model: Gio.ListModel; pending: number; } } export class FilterListModel<A extends GObject.Object = GObject.Object> extends GObject.Object implements Gio.ListModel<A> { static $gtype: GObject.GType<FilterListModel>; constructor( properties?: Partial<FilterListModel.ConstructorProperties<A>>, ...args: any[] ); _init( properties?: Partial<FilterListModel.ConstructorProperties<A>>, ...args: any[] ): void; // Properties filter: Filter; incremental: boolean; model: Gio.ListModel; pending: number; // Constructors static ['new']( model?: Gio.ListModel | null, filter?: Filter | null ): FilterListModel; // Members get_filter(): Filter | null; get_incremental(): boolean; get_model(): Gio.ListModel | null; get_pending(): number; set_filter(filter?: Filter | null): void; set_incremental(incremental: boolean): void; set_model(model?: Gio.ListModel | null): void; // Implemented Members get_item_type(): GObject.GType; get_n_items(): number; get_item(position: number): A | null; items_changed(position: number, removed: number, added: number): void; vfunc_get_item(position: number): A | null; vfunc_get_item_type(): GObject.GType; vfunc_get_n_items(): number; } export namespace Fixed { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; } } export class Fixed extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<Fixed>; constructor( properties?: Partial<Fixed.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Fixed.ConstructorProperties>, ...args: any[] ): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](): Fixed; // Members get_child_position(widget: Widget): [number, number]; get_child_transform(widget: Widget): Gsk.Transform | null; move(widget: Widget, x: number, y: number): void; put(widget: Widget, x: number, y: number): void; remove(widget: Widget): void; set_child_transform(widget: Widget, transform?: Gsk.Transform | null): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace FixedLayout { export interface ConstructorProperties extends LayoutManager.ConstructorProperties { [key: string]: any; } } export class FixedLayout extends LayoutManager { static $gtype: GObject.GType<FixedLayout>; constructor( properties?: Partial<FixedLayout.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<FixedLayout.ConstructorProperties>, ...args: any[] ): void; // Constructors static ['new'](): FixedLayout; } export namespace FixedLayoutChild { export interface ConstructorProperties extends LayoutChild.ConstructorProperties { [key: string]: any; transform: Gsk.Transform; } } export class FixedLayoutChild extends LayoutChild { static $gtype: GObject.GType<FixedLayoutChild>; constructor( properties?: Partial<FixedLayoutChild.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<FixedLayoutChild.ConstructorProperties>, ...args: any[] ): void; // Properties transform: Gsk.Transform; // Members get_transform(): Gsk.Transform | null; set_transform(transform: Gsk.Transform): void; } export namespace FlattenListModel { export interface ConstructorProperties< A extends GObject.Object = GObject.Object > extends GObject.Object.ConstructorProperties { [key: string]: any; model: Gio.ListModel; } } export class FlattenListModel<A extends GObject.Object = GObject.Object> extends GObject.Object implements Gio.ListModel<A> { static $gtype: GObject.GType<FlattenListModel>; constructor( properties?: Partial<FlattenListModel.ConstructorProperties<A>>, ...args: any[] ); _init( properties?: Partial<FlattenListModel.ConstructorProperties<A>>, ...args: any[] ): void; // Properties model: Gio.ListModel; // Constructors static ['new'](model?: Gio.ListModel | null): FlattenListModel; // Members get_model(): Gio.ListModel | null; get_model_for_item(position: number): Gio.ListModel; set_model(model?: Gio.ListModel | null): void; // Implemented Members get_item_type(): GObject.GType; get_n_items(): number; get_item(position: number): A | null; items_changed(position: number, removed: number, added: number): void; vfunc_get_item(position: number): A | null; vfunc_get_item_type(): GObject.GType; vfunc_get_n_items(): number; } export namespace FlowBox { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; accept_unpaired_release: boolean; acceptUnpairedRelease: boolean; activate_on_single_click: boolean; activateOnSingleClick: boolean; column_spacing: number; columnSpacing: number; homogeneous: boolean; max_children_per_line: number; maxChildrenPerLine: number; min_children_per_line: number; minChildrenPerLine: number; row_spacing: number; rowSpacing: number; selection_mode: SelectionMode; selectionMode: SelectionMode; } } export class FlowBox extends Widget implements Accessible, Buildable, ConstraintTarget, Orientable { static $gtype: GObject.GType<FlowBox>; constructor( properties?: Partial<FlowBox.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<FlowBox.ConstructorProperties>, ...args: any[] ): void; // Properties accept_unpaired_release: boolean; acceptUnpairedRelease: boolean; activate_on_single_click: boolean; activateOnSingleClick: boolean; column_spacing: number; columnSpacing: number; homogeneous: boolean; max_children_per_line: number; maxChildrenPerLine: number; min_children_per_line: number; minChildrenPerLine: number; row_spacing: number; rowSpacing: number; selection_mode: SelectionMode; selectionMode: SelectionMode; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'activate-cursor-child', callback: (_source: this) => void ): number; connect_after( signal: 'activate-cursor-child', callback: (_source: this) => void ): number; emit(signal: 'activate-cursor-child'): void; connect( signal: 'child-activated', callback: (_source: this, child: FlowBoxChild) => void ): number; connect_after( signal: 'child-activated', callback: (_source: this, child: FlowBoxChild) => void ): number; emit(signal: 'child-activated', child: FlowBoxChild): void; connect( signal: 'move-cursor', callback: ( _source: this, step: MovementStep, count: number, extend: boolean, modify: boolean ) => boolean ): number; connect_after( signal: 'move-cursor', callback: ( _source: this, step: MovementStep, count: number, extend: boolean, modify: boolean ) => boolean ): number; emit( signal: 'move-cursor', step: MovementStep, count: number, extend: boolean, modify: boolean ): void; connect(signal: 'select-all', callback: (_source: this) => void): number; connect_after( signal: 'select-all', callback: (_source: this) => void ): number; emit(signal: 'select-all'): void; connect( signal: 'selected-children-changed', callback: (_source: this) => void ): number; connect_after( signal: 'selected-children-changed', callback: (_source: this) => void ): number; emit(signal: 'selected-children-changed'): void; connect( signal: 'toggle-cursor-child', callback: (_source: this) => void ): number; connect_after( signal: 'toggle-cursor-child', callback: (_source: this) => void ): number; emit(signal: 'toggle-cursor-child'): void; connect(signal: 'unselect-all', callback: (_source: this) => void): number; connect_after( signal: 'unselect-all', callback: (_source: this) => void ): number; emit(signal: 'unselect-all'): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; orientation: Orientation; // Constructors static ['new'](): FlowBox; // Members bind_model( model: Gio.ListModel | null, create_widget_func: FlowBoxCreateWidgetFunc ): void; get_activate_on_single_click(): boolean; get_child_at_index(idx: number): FlowBoxChild | null; get_child_at_pos(x: number, y: number): FlowBoxChild | null; get_column_spacing(): number; get_homogeneous(): boolean; get_max_children_per_line(): number; get_min_children_per_line(): number; get_row_spacing(): number; get_selected_children(): FlowBoxChild[]; get_selection_mode(): SelectionMode; insert(widget: Widget, position: number): void; invalidate_filter(): void; invalidate_sort(): void; remove(widget: Widget): void; select_all(): void; select_child(child: FlowBoxChild): void; selected_foreach(func: FlowBoxForeachFunc): void; set_activate_on_single_click(single: boolean): void; set_column_spacing(spacing: number): void; set_filter_func(filter_func?: FlowBoxFilterFunc | null): void; set_hadjustment(adjustment: Adjustment): void; set_homogeneous(homogeneous: boolean): void; set_max_children_per_line(n_children: number): void; set_min_children_per_line(n_children: number): void; set_row_spacing(spacing: number): void; set_selection_mode(mode: SelectionMode): void; set_sort_func(sort_func?: FlowBoxSortFunc | null): void; set_vadjustment(adjustment: Adjustment): void; unselect_all(): void; unselect_child(child: FlowBoxChild): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_orientation(): Orientation; set_orientation(orientation: Orientation): void; } export namespace FlowBoxChild { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; child: Widget; } } export class FlowBoxChild extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<FlowBoxChild>; constructor( properties?: Partial<FlowBoxChild.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<FlowBoxChild.ConstructorProperties>, ...args: any[] ): void; // Properties child: Widget; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'activate', callback: (_source: this) => void): number; connect_after( signal: 'activate', callback: (_source: this) => void ): number; emit(signal: 'activate'): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](): FlowBoxChild; // Members changed(): void; get_child(): Widget | null; get_index(): number; is_selected(): boolean; set_child(child?: Widget | null): void; vfunc_activate(): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace FontButton { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; modal: boolean; title: string; use_font: boolean; useFont: boolean; use_size: boolean; useSize: boolean; } } export class FontButton extends Widget implements Accessible, Buildable, ConstraintTarget, FontChooser { static $gtype: GObject.GType<FontButton>; constructor( properties?: Partial<FontButton.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<FontButton.ConstructorProperties>, ...args: any[] ): void; // Properties modal: boolean; title: string; use_font: boolean; useFont: boolean; use_size: boolean; useSize: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'font-set', callback: (_source: this) => void): number; connect_after( signal: 'font-set', callback: (_source: this) => void ): number; emit(signal: 'font-set'): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; font: string; font_desc: Pango.FontDescription; fontDesc: Pango.FontDescription; font_features: string; fontFeatures: string; language: string; level: FontChooserLevel; preview_text: string; previewText: string; show_preview_entry: boolean; showPreviewEntry: boolean; // Constructors static ['new'](): FontButton; static new_with_font(fontname: string): FontButton; // Members get_modal(): boolean; get_title(): string; get_use_font(): boolean; get_use_size(): boolean; set_modal(modal: boolean): void; set_title(title: string): void; set_use_font(use_font: boolean): void; set_use_size(use_size: boolean): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_font(): string | null; get_font_desc(): Pango.FontDescription | null; get_font_face(): Pango.FontFace | null; get_font_family(): Pango.FontFamily | null; get_font_features(): string; get_font_map(): Pango.FontMap | null; get_font_size(): number; get_language(): string; get_level(): FontChooserLevel; get_preview_text(): string; get_show_preview_entry(): boolean; set_filter_func(filter?: FontFilterFunc | null): void; set_font(fontname: string): void; set_font_desc(font_desc: Pango.FontDescription): void; set_font_map(fontmap?: Pango.FontMap | null): void; set_language(language: string): void; set_level(level: FontChooserLevel): void; set_preview_text(text: string): void; set_show_preview_entry(show_preview_entry: boolean): void; vfunc_font_activated(fontname: string): void; vfunc_get_font_face(): Pango.FontFace | null; vfunc_get_font_family(): Pango.FontFamily | null; vfunc_get_font_map(): Pango.FontMap | null; vfunc_get_font_size(): number; vfunc_set_filter_func(filter?: FontFilterFunc | null): void; vfunc_set_font_map(fontmap?: Pango.FontMap | null): void; } export namespace FontChooserDialog { export interface ConstructorProperties extends Dialog.ConstructorProperties { [key: string]: any; } } export class FontChooserDialog extends Dialog implements Accessible, Buildable, ConstraintTarget, FontChooser, Native, Root, ShortcutManager { static $gtype: GObject.GType<FontChooserDialog>; constructor( properties?: Partial<FontChooserDialog.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<FontChooserDialog.ConstructorProperties>, ...args: any[] ): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; font: string; font_desc: Pango.FontDescription; fontDesc: Pango.FontDescription; font_features: string; fontFeatures: string; language: string; level: FontChooserLevel; preview_text: string; previewText: string; show_preview_entry: boolean; showPreviewEntry: boolean; // Constructors static ['new']( title?: string | null, parent?: Window | null ): FontChooserDialog; static ['new'](...args: never[]): never; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_font(): string | null; get_font_desc(): Pango.FontDescription | null; get_font_face(): Pango.FontFace | null; get_font_family(): Pango.FontFamily | null; get_font_features(): string; get_font_map(): Pango.FontMap | null; get_font_size(): number; get_language(): string; get_level(): FontChooserLevel; get_preview_text(): string; get_show_preview_entry(): boolean; set_filter_func(filter?: FontFilterFunc | null): void; set_font(fontname: string): void; set_font_desc(font_desc: Pango.FontDescription): void; set_font_map(fontmap?: Pango.FontMap | null): void; set_language(language: string): void; set_level(level: FontChooserLevel): void; set_preview_text(text: string): void; set_show_preview_entry(show_preview_entry: boolean): void; vfunc_font_activated(fontname: string): void; vfunc_get_font_face(): Pango.FontFace | null; vfunc_get_font_family(): Pango.FontFamily | null; vfunc_get_font_map(): Pango.FontMap | null; vfunc_get_font_size(): number; vfunc_set_filter_func(filter?: FontFilterFunc | null): void; vfunc_set_font_map(fontmap?: Pango.FontMap | null): void; get_renderer(): Gsk.Renderer; get_surface(): Gdk.Surface; get_surface_transform(): [number, number]; realize(): void; unrealize(): void; get_display(): Gdk.Display; get_focus(): Widget | null; set_focus(focus?: Widget | null): void; vfunc_add_controller(controller: ShortcutController): void; vfunc_remove_controller(controller: ShortcutController): void; } export namespace FontChooserWidget { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; tweak_action: Gio.Action; tweakAction: Gio.Action; } } export class FontChooserWidget extends Widget implements Accessible, Buildable, ConstraintTarget, FontChooser { static $gtype: GObject.GType<FontChooserWidget>; constructor( properties?: Partial<FontChooserWidget.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<FontChooserWidget.ConstructorProperties>, ...args: any[] ): void; // Properties tweak_action: Gio.Action; tweakAction: Gio.Action; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; font: string; font_desc: Pango.FontDescription; fontDesc: Pango.FontDescription; font_features: string; fontFeatures: string; language: string; level: FontChooserLevel; preview_text: string; previewText: string; show_preview_entry: boolean; showPreviewEntry: boolean; // Constructors static ['new'](): FontChooserWidget; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_font(): string | null; get_font_desc(): Pango.FontDescription | null; get_font_face(): Pango.FontFace | null; get_font_family(): Pango.FontFamily | null; get_font_features(): string; get_font_map(): Pango.FontMap | null; get_font_size(): number; get_language(): string; get_level(): FontChooserLevel; get_preview_text(): string; get_show_preview_entry(): boolean; set_filter_func(filter?: FontFilterFunc | null): void; set_font(fontname: string): void; set_font_desc(font_desc: Pango.FontDescription): void; set_font_map(fontmap?: Pango.FontMap | null): void; set_language(language: string): void; set_level(level: FontChooserLevel): void; set_preview_text(text: string): void; set_show_preview_entry(show_preview_entry: boolean): void; vfunc_font_activated(fontname: string): void; vfunc_get_font_face(): Pango.FontFace | null; vfunc_get_font_family(): Pango.FontFamily | null; vfunc_get_font_map(): Pango.FontMap | null; vfunc_get_font_size(): number; vfunc_set_filter_func(filter?: FontFilterFunc | null): void; vfunc_set_font_map(fontmap?: Pango.FontMap | null): void; } export namespace Frame { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; child: Widget; label: string; label_widget: Widget; labelWidget: Widget; label_xalign: number; labelXalign: number; } } export class Frame extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<Frame>; constructor( properties?: Partial<Frame.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Frame.ConstructorProperties>, ...args: any[] ): void; // Properties child: Widget; label: string; label_widget: Widget; labelWidget: Widget; label_xalign: number; labelXalign: number; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](label?: string | null): Frame; // Members get_child(): Widget | null; get_label(): string | null; get_label_align(): number; get_label_widget(): Widget | null; set_child(child?: Widget | null): void; set_label(label?: string | null): void; set_label_align(xalign: number): void; set_label_widget(label_widget?: Widget | null): void; vfunc_compute_child_allocation(allocation: Allocation): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace GLArea { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; auto_render: boolean; autoRender: boolean; context: Gdk.GLContext; has_depth_buffer: boolean; hasDepthBuffer: boolean; has_stencil_buffer: boolean; hasStencilBuffer: boolean; use_es: boolean; useEs: boolean; } } export class GLArea extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<GLArea>; constructor( properties?: Partial<GLArea.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<GLArea.ConstructorProperties>, ...args: any[] ): void; // Properties auto_render: boolean; autoRender: boolean; context: Gdk.GLContext; has_depth_buffer: boolean; hasDepthBuffer: boolean; has_stencil_buffer: boolean; hasStencilBuffer: boolean; use_es: boolean; useEs: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'create-context', callback: (_source: this) => Gdk.GLContext ): number; connect_after( signal: 'create-context', callback: (_source: this) => Gdk.GLContext ): number; emit(signal: 'create-context'): void; connect( signal: 'render', callback: (_source: this, context: Gdk.GLContext) => boolean ): number; connect_after( signal: 'render', callback: (_source: this, context: Gdk.GLContext) => boolean ): number; emit(signal: 'render', context: Gdk.GLContext): void; connect( signal: 'resize', callback: (_source: this, width: number, height: number) => void ): number; connect_after( signal: 'resize', callback: (_source: this, width: number, height: number) => void ): number; emit(signal: 'resize', width: number, height: number): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](): GLArea; // Members attach_buffers(): void; get_auto_render(): boolean; get_context(): Gdk.GLContext; get_error(): GLib.Error | null; get_has_depth_buffer(): boolean; get_has_stencil_buffer(): boolean; get_required_version(): [number, number]; get_use_es(): boolean; make_current(): void; queue_render(): void; set_auto_render(auto_render: boolean): void; set_error(error?: GLib.Error | null): void; set_has_depth_buffer(has_depth_buffer: boolean): void; set_has_stencil_buffer(has_stencil_buffer: boolean): void; set_required_version(major: number, minor: number): void; set_use_es(use_es: boolean): void; vfunc_render(context: Gdk.GLContext): boolean; vfunc_resize(width: number, height: number): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace Gesture { export interface ConstructorProperties extends EventController.ConstructorProperties { [key: string]: any; n_points: number; nPoints: number; } } export abstract class Gesture extends EventController { static $gtype: GObject.GType<Gesture>; constructor( properties?: Partial<Gesture.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Gesture.ConstructorProperties>, ...args: any[] ): void; // Properties n_points: number; nPoints: number; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'begin', callback: (_source: this, sequence: Gdk.EventSequence | null) => void ): number; connect_after( signal: 'begin', callback: (_source: this, sequence: Gdk.EventSequence | null) => void ): number; emit(signal: 'begin', sequence: Gdk.EventSequence | null): void; connect( signal: 'cancel', callback: (_source: this, sequence: Gdk.EventSequence | null) => void ): number; connect_after( signal: 'cancel', callback: (_source: this, sequence: Gdk.EventSequence | null) => void ): number; emit(signal: 'cancel', sequence: Gdk.EventSequence | null): void; connect( signal: 'end', callback: (_source: this, sequence: Gdk.EventSequence | null) => void ): number; connect_after( signal: 'end', callback: (_source: this, sequence: Gdk.EventSequence | null) => void ): number; emit(signal: 'end', sequence: Gdk.EventSequence | null): void; connect( signal: 'sequence-state-changed', callback: ( _source: this, sequence: Gdk.EventSequence | null, state: EventSequenceState ) => void ): number; connect_after( signal: 'sequence-state-changed', callback: ( _source: this, sequence: Gdk.EventSequence | null, state: EventSequenceState ) => void ): number; emit( signal: 'sequence-state-changed', sequence: Gdk.EventSequence | null, state: EventSequenceState ): void; connect( signal: 'update', callback: (_source: this, sequence: Gdk.EventSequence | null) => void ): number; connect_after( signal: 'update', callback: (_source: this, sequence: Gdk.EventSequence | null) => void ): number; emit(signal: 'update', sequence: Gdk.EventSequence | null): void; // Members get_bounding_box(): [boolean, Gdk.Rectangle]; get_bounding_box_center(): [boolean, number, number]; get_device(): Gdk.Device | null; get_group(): Gesture[]; get_last_event(sequence?: Gdk.EventSequence | null): Gdk.Event | null; get_last_updated_sequence(): Gdk.EventSequence | null; get_point( sequence?: Gdk.EventSequence | null ): [boolean, number | null, number | null]; get_sequence_state(sequence: Gdk.EventSequence): EventSequenceState; get_sequences(): Gdk.EventSequence[]; group(gesture: Gesture): void; handles_sequence(sequence?: Gdk.EventSequence | null): boolean; is_active(): boolean; is_grouped_with(other: Gesture): boolean; is_recognized(): boolean; set_sequence_state( sequence: Gdk.EventSequence, state: EventSequenceState ): boolean; set_state(state: EventSequenceState): boolean; ungroup(): void; } export namespace GestureClick { export interface ConstructorProperties extends GestureSingle.ConstructorProperties { [key: string]: any; } } export class GestureClick extends GestureSingle { static $gtype: GObject.GType<GestureClick>; constructor( properties?: Partial<GestureClick.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<GestureClick.ConstructorProperties>, ...args: any[] ): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'pressed', callback: (_source: this, n_press: number, x: number, y: number) => void ): number; connect_after( signal: 'pressed', callback: (_source: this, n_press: number, x: number, y: number) => void ): number; emit(signal: 'pressed', n_press: number, x: number, y: number): void; connect( signal: 'released', callback: (_source: this, n_press: number, x: number, y: number) => void ): number; connect_after( signal: 'released', callback: (_source: this, n_press: number, x: number, y: number) => void ): number; emit(signal: 'released', n_press: number, x: number, y: number): void; connect(signal: 'stopped', callback: (_source: this) => void): number; connect_after(signal: 'stopped', callback: (_source: this) => void): number; emit(signal: 'stopped'): void; connect( signal: 'unpaired-release', callback: ( _source: this, x: number, y: number, button: number, sequence: Gdk.EventSequence ) => void ): number; connect_after( signal: 'unpaired-release', callback: ( _source: this, x: number, y: number, button: number, sequence: Gdk.EventSequence ) => void ): number; emit( signal: 'unpaired-release', x: number, y: number, button: number, sequence: Gdk.EventSequence ): void; // Constructors static ['new'](): GestureClick; } export namespace GestureDrag { export interface ConstructorProperties extends GestureSingle.ConstructorProperties { [key: string]: any; } } export class GestureDrag extends GestureSingle { static $gtype: GObject.GType<GestureDrag>; constructor( properties?: Partial<GestureDrag.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<GestureDrag.ConstructorProperties>, ...args: any[] ): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'drag-begin', callback: (_source: this, start_x: number, start_y: number) => void ): number; connect_after( signal: 'drag-begin', callback: (_source: this, start_x: number, start_y: number) => void ): number; emit(signal: 'drag-begin', start_x: number, start_y: number): void; connect( signal: 'drag-end', callback: (_source: this, offset_x: number, offset_y: number) => void ): number; connect_after( signal: 'drag-end', callback: (_source: this, offset_x: number, offset_y: number) => void ): number; emit(signal: 'drag-end', offset_x: number, offset_y: number): void; connect( signal: 'drag-update', callback: (_source: this, offset_x: number, offset_y: number) => void ): number; connect_after( signal: 'drag-update', callback: (_source: this, offset_x: number, offset_y: number) => void ): number; emit(signal: 'drag-update', offset_x: number, offset_y: number): void; // Constructors static ['new'](): GestureDrag; // Members get_offset(): [boolean, number | null, number | null]; get_start_point(): [boolean, number | null, number | null]; } export namespace GestureLongPress { export interface ConstructorProperties extends GestureSingle.ConstructorProperties { [key: string]: any; delay_factor: number; delayFactor: number; } } export class GestureLongPress extends GestureSingle { static $gtype: GObject.GType<GestureLongPress>; constructor( properties?: Partial<GestureLongPress.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<GestureLongPress.ConstructorProperties>, ...args: any[] ): void; // Properties delay_factor: number; delayFactor: number; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'cancelled', callback: (_source: this) => void): number; connect_after( signal: 'cancelled', callback: (_source: this) => void ): number; emit(signal: 'cancelled'): void; connect( signal: 'pressed', callback: (_source: this, x: number, y: number) => void ): number; connect_after( signal: 'pressed', callback: (_source: this, x: number, y: number) => void ): number; emit(signal: 'pressed', x: number, y: number): void; // Constructors static ['new'](): GestureLongPress; // Members get_delay_factor(): number; set_delay_factor(delay_factor: number): void; } export namespace GesturePan { export interface ConstructorProperties extends GestureDrag.ConstructorProperties { [key: string]: any; orientation: Orientation; } } export class GesturePan extends GestureDrag { static $gtype: GObject.GType<GesturePan>; constructor( properties?: Partial<GesturePan.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<GesturePan.ConstructorProperties>, ...args: any[] ): void; // Properties orientation: Orientation; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'pan', callback: ( _source: this, direction: PanDirection, offset: number ) => void ): number; connect_after( signal: 'pan', callback: ( _source: this, direction: PanDirection, offset: number ) => void ): number; emit(signal: 'pan', direction: PanDirection, offset: number): void; // Constructors static ['new'](orientation: Orientation): GesturePan; static ['new'](...args: never[]): never; // Members get_orientation(): Orientation; set_orientation(orientation: Orientation): void; } export namespace GestureRotate { export interface ConstructorProperties extends Gesture.ConstructorProperties { [key: string]: any; } } export class GestureRotate extends Gesture { static $gtype: GObject.GType<GestureRotate>; constructor( properties?: Partial<GestureRotate.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<GestureRotate.ConstructorProperties>, ...args: any[] ): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'angle-changed', callback: (_source: this, angle: number, angle_delta: number) => void ): number; connect_after( signal: 'angle-changed', callback: (_source: this, angle: number, angle_delta: number) => void ): number; emit(signal: 'angle-changed', angle: number, angle_delta: number): void; // Constructors static ['new'](): GestureRotate; // Members get_angle_delta(): number; } export namespace GestureSingle { export interface ConstructorProperties extends Gesture.ConstructorProperties { [key: string]: any; button: number; exclusive: boolean; touch_only: boolean; touchOnly: boolean; } } export class GestureSingle extends Gesture { static $gtype: GObject.GType<GestureSingle>; constructor( properties?: Partial<GestureSingle.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<GestureSingle.ConstructorProperties>, ...args: any[] ): void; // Properties button: number; exclusive: boolean; touch_only: boolean; touchOnly: boolean; // Members get_button(): number; get_current_button(): number; get_current_sequence(): Gdk.EventSequence | null; get_exclusive(): boolean; get_touch_only(): boolean; set_button(button: number): void; set_exclusive(exclusive: boolean): void; set_touch_only(touch_only: boolean): void; } export namespace GestureStylus { export interface ConstructorProperties extends GestureSingle.ConstructorProperties { [key: string]: any; } } export class GestureStylus extends GestureSingle { static $gtype: GObject.GType<GestureStylus>; constructor( properties?: Partial<GestureStylus.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<GestureStylus.ConstructorProperties>, ...args: any[] ): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'down', callback: (_source: this, x: number, y: number) => void ): number; connect_after( signal: 'down', callback: (_source: this, x: number, y: number) => void ): number; emit(signal: 'down', x: number, y: number): void; connect( signal: 'motion', callback: (_source: this, x: number, y: number) => void ): number; connect_after( signal: 'motion', callback: (_source: this, x: number, y: number) => void ): number; emit(signal: 'motion', x: number, y: number): void; connect( signal: 'proximity', callback: (_source: this, x: number, y: number) => void ): number; connect_after( signal: 'proximity', callback: (_source: this, x: number, y: number) => void ): number; emit(signal: 'proximity', x: number, y: number): void; connect( signal: 'up', callback: (_source: this, x: number, y: number) => void ): number; connect_after( signal: 'up', callback: (_source: this, x: number, y: number) => void ): number; emit(signal: 'up', x: number, y: number): void; // Constructors static ['new'](): GestureStylus; // Members get_axes(axes: Gdk.AxisUse[]): [boolean, number[]]; get_axis(axis: Gdk.AxisUse): [boolean, number]; get_backlog(): [boolean, Gdk.TimeCoord[]]; get_device_tool(): Gdk.DeviceTool | null; } export namespace GestureSwipe { export interface ConstructorProperties extends GestureSingle.ConstructorProperties { [key: string]: any; } } export class GestureSwipe extends GestureSingle { static $gtype: GObject.GType<GestureSwipe>; constructor( properties?: Partial<GestureSwipe.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<GestureSwipe.ConstructorProperties>, ...args: any[] ): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'swipe', callback: ( _source: this, velocity_x: number, velocity_y: number ) => void ): number; connect_after( signal: 'swipe', callback: ( _source: this, velocity_x: number, velocity_y: number ) => void ): number; emit(signal: 'swipe', velocity_x: number, velocity_y: number): void; // Constructors static ['new'](): GestureSwipe; // Members get_velocity(): [boolean, number, number]; } export namespace GestureZoom { export interface ConstructorProperties extends Gesture.ConstructorProperties { [key: string]: any; } } export class GestureZoom extends Gesture { static $gtype: GObject.GType<GestureZoom>; constructor( properties?: Partial<GestureZoom.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<GestureZoom.ConstructorProperties>, ...args: any[] ): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'scale-changed', callback: (_source: this, scale: number) => void ): number; connect_after( signal: 'scale-changed', callback: (_source: this, scale: number) => void ): number; emit(signal: 'scale-changed', scale: number): void; // Constructors static ['new'](): GestureZoom; // Members get_scale_delta(): number; } export namespace Grid { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; baseline_row: number; baselineRow: number; column_homogeneous: boolean; columnHomogeneous: boolean; column_spacing: number; columnSpacing: number; row_homogeneous: boolean; rowHomogeneous: boolean; row_spacing: number; rowSpacing: number; } } export class Grid extends Widget implements Accessible, Buildable, ConstraintTarget, Orientable { static $gtype: GObject.GType<Grid>; constructor( properties?: Partial<Grid.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Grid.ConstructorProperties>, ...args: any[] ): void; // Properties baseline_row: number; baselineRow: number; column_homogeneous: boolean; columnHomogeneous: boolean; column_spacing: number; columnSpacing: number; row_homogeneous: boolean; rowHomogeneous: boolean; row_spacing: number; rowSpacing: number; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; orientation: Orientation; // Constructors static ['new'](): Grid; // Members attach( child: Widget, column: number, row: number, width: number, height: number ): void; attach_next_to( child: Widget, sibling: Widget | null, side: PositionType, width: number, height: number ): void; get_baseline_row(): number; get_child_at(column: number, row: number): Widget | null; get_column_homogeneous(): boolean; get_column_spacing(): number; get_row_baseline_position(row: number): BaselinePosition; get_row_homogeneous(): boolean; get_row_spacing(): number; insert_column(position: number): void; insert_next_to(sibling: Widget, side: PositionType): void; insert_row(position: number): void; query_child( child: Widget ): [number | null, number | null, number | null, number | null]; remove(child: Widget): void; remove_column(position: number): void; remove_row(position: number): void; set_baseline_row(row: number): void; set_column_homogeneous(homogeneous: boolean): void; set_column_spacing(spacing: number): void; set_row_baseline_position(row: number, pos: BaselinePosition): void; set_row_homogeneous(homogeneous: boolean): void; set_row_spacing(spacing: number): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_orientation(): Orientation; set_orientation(orientation: Orientation): void; } export namespace GridLayout { export interface ConstructorProperties extends LayoutManager.ConstructorProperties { [key: string]: any; baseline_row: number; baselineRow: number; column_homogeneous: boolean; columnHomogeneous: boolean; column_spacing: number; columnSpacing: number; row_homogeneous: boolean; rowHomogeneous: boolean; row_spacing: number; rowSpacing: number; } } export class GridLayout extends LayoutManager { static $gtype: GObject.GType<GridLayout>; constructor( properties?: Partial<GridLayout.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<GridLayout.ConstructorProperties>, ...args: any[] ): void; // Properties baseline_row: number; baselineRow: number; column_homogeneous: boolean; columnHomogeneous: boolean; column_spacing: number; columnSpacing: number; row_homogeneous: boolean; rowHomogeneous: boolean; row_spacing: number; rowSpacing: number; // Constructors static ['new'](): GridLayout; // Members get_baseline_row(): number; get_column_homogeneous(): boolean; get_column_spacing(): number; get_row_baseline_position(row: number): BaselinePosition; get_row_homogeneous(): boolean; get_row_spacing(): number; set_baseline_row(row: number): void; set_column_homogeneous(homogeneous: boolean): void; set_column_spacing(spacing: number): void; set_row_baseline_position(row: number, pos: BaselinePosition): void; set_row_homogeneous(homogeneous: boolean): void; set_row_spacing(spacing: number): void; } export namespace GridLayoutChild { export interface ConstructorProperties extends LayoutChild.ConstructorProperties { [key: string]: any; column: number; column_span: number; columnSpan: number; row: number; row_span: number; rowSpan: number; } } export class GridLayoutChild extends LayoutChild { static $gtype: GObject.GType<GridLayoutChild>; constructor( properties?: Partial<GridLayoutChild.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<GridLayoutChild.ConstructorProperties>, ...args: any[] ): void; // Properties column: number; column_span: number; columnSpan: number; row: number; row_span: number; rowSpan: number; // Members get_column(): number; get_column_span(): number; get_row(): number; get_row_span(): number; set_column(column: number): void; set_column_span(span: number): void; set_row(row: number): void; set_row_span(span: number): void; } export namespace GridView { export interface ConstructorProperties extends ListBase.ConstructorProperties { [key: string]: any; enable_rubberband: boolean; enableRubberband: boolean; factory: ListItemFactory; max_columns: number; maxColumns: number; min_columns: number; minColumns: number; model: SelectionModel; single_click_activate: boolean; singleClickActivate: boolean; } } export class GridView extends ListBase implements Accessible, Buildable, ConstraintTarget, Orientable, Scrollable { static $gtype: GObject.GType<GridView>; constructor( properties?: Partial<GridView.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<GridView.ConstructorProperties>, ...args: any[] ): void; // Properties enable_rubberband: boolean; enableRubberband: boolean; factory: ListItemFactory; max_columns: number; maxColumns: number; min_columns: number; minColumns: number; model: SelectionModel; single_click_activate: boolean; singleClickActivate: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'activate', callback: (_source: this, position: number) => void ): number; connect_after( signal: 'activate', callback: (_source: this, position: number) => void ): number; emit(signal: 'activate', position: number): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; orientation: Orientation; hadjustment: Adjustment; hscroll_policy: ScrollablePolicy; hscrollPolicy: ScrollablePolicy; vadjustment: Adjustment; vscroll_policy: ScrollablePolicy; vscrollPolicy: ScrollablePolicy; // Constructors static ['new']( model?: SelectionModel | null, factory?: ListItemFactory | null ): GridView; // Members get_enable_rubberband(): boolean; get_factory(): ListItemFactory | null; get_max_columns(): number; get_min_columns(): number; get_model(): SelectionModel | null; get_single_click_activate(): boolean; set_enable_rubberband(enable_rubberband: boolean): void; set_factory(factory?: ListItemFactory | null): void; set_max_columns(max_columns: number): void; set_min_columns(min_columns: number): void; set_model(model?: SelectionModel | null): void; set_single_click_activate(single_click_activate: boolean): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_orientation(): Orientation; set_orientation(orientation: Orientation): void; get_border(): [boolean, Border]; get_hadjustment(): Adjustment; get_hscroll_policy(): ScrollablePolicy; get_vadjustment(): Adjustment; get_vscroll_policy(): ScrollablePolicy; set_hadjustment(hadjustment?: Adjustment | null): void; set_hscroll_policy(policy: ScrollablePolicy): void; set_vadjustment(vadjustment?: Adjustment | null): void; set_vscroll_policy(policy: ScrollablePolicy): void; vfunc_get_border(): [boolean, Border]; } export namespace HeaderBar { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; decoration_layout: string; decorationLayout: string; show_title_buttons: boolean; showTitleButtons: boolean; title_widget: Widget; titleWidget: Widget; } } export class HeaderBar extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<HeaderBar>; constructor( properties?: Partial<HeaderBar.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<HeaderBar.ConstructorProperties>, ...args: any[] ): void; // Properties decoration_layout: string; decorationLayout: string; show_title_buttons: boolean; showTitleButtons: boolean; title_widget: Widget; titleWidget: Widget; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](): HeaderBar; // Members get_decoration_layout(): string | null; get_show_title_buttons(): boolean; get_title_widget(): Widget | null; pack_end(child: Widget): void; pack_start(child: Widget): void; remove(child: Widget): void; set_decoration_layout(layout?: string | null): void; set_show_title_buttons(setting: boolean): void; set_title_widget(title_widget?: Widget | null): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace IMContext { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; input_hints: InputHints; inputHints: InputHints; input_purpose: InputPurpose; inputPurpose: InputPurpose; } } export abstract class IMContext extends GObject.Object { static $gtype: GObject.GType<IMContext>; constructor( properties?: Partial<IMContext.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<IMContext.ConstructorProperties>, ...args: any[] ): void; // Properties input_hints: InputHints; inputHints: InputHints; input_purpose: InputPurpose; inputPurpose: InputPurpose; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'commit', callback: (_source: this, str: string) => void ): number; connect_after( signal: 'commit', callback: (_source: this, str: string) => void ): number; emit(signal: 'commit', str: string): void; connect( signal: 'delete-surrounding', callback: (_source: this, offset: number, n_chars: number) => boolean ): number; connect_after( signal: 'delete-surrounding', callback: (_source: this, offset: number, n_chars: number) => boolean ): number; emit(signal: 'delete-surrounding', offset: number, n_chars: number): void; connect( signal: 'preedit-changed', callback: (_source: this) => void ): number; connect_after( signal: 'preedit-changed', callback: (_source: this) => void ): number; emit(signal: 'preedit-changed'): void; connect(signal: 'preedit-end', callback: (_source: this) => void): number; connect_after( signal: 'preedit-end', callback: (_source: this) => void ): number; emit(signal: 'preedit-end'): void; connect(signal: 'preedit-start', callback: (_source: this) => void): number; connect_after( signal: 'preedit-start', callback: (_source: this) => void ): number; emit(signal: 'preedit-start'): void; connect( signal: 'retrieve-surrounding', callback: (_source: this) => boolean ): number; connect_after( signal: 'retrieve-surrounding', callback: (_source: this) => boolean ): number; emit(signal: 'retrieve-surrounding'): void; // Members delete_surrounding(offset: number, n_chars: number): boolean; filter_key( press: boolean, surface: Gdk.Surface, device: Gdk.Device, time: number, keycode: number, state: Gdk.ModifierType, group: number ): boolean; filter_keypress(event: Gdk.Event): boolean; focus_in(): void; focus_out(): void; get_preedit_string(): [string, Pango.AttrList, number]; get_surrounding(): [boolean, string, number]; reset(): void; set_client_widget(widget?: Widget | null): void; set_cursor_location(area: Gdk.Rectangle): void; set_surrounding(text: string, len: number, cursor_index: number): void; set_use_preedit(use_preedit: boolean): void; vfunc_commit(str: string): void; vfunc_delete_surrounding(offset: number, n_chars: number): boolean; vfunc_filter_keypress(event: Gdk.Event): boolean; vfunc_focus_in(): void; vfunc_focus_out(): void; vfunc_get_preedit_string(): [string, Pango.AttrList, number]; vfunc_get_surrounding(): [boolean, string, number]; vfunc_preedit_changed(): void; vfunc_preedit_end(): void; vfunc_preedit_start(): void; vfunc_reset(): void; vfunc_retrieve_surrounding(): boolean; vfunc_set_client_widget(widget?: Widget | null): void; vfunc_set_cursor_location(area: Gdk.Rectangle): void; vfunc_set_surrounding( text: string, len: number, cursor_index: number ): void; vfunc_set_use_preedit(use_preedit: boolean): void; } export namespace IMContextSimple { export interface ConstructorProperties extends IMContext.ConstructorProperties { [key: string]: any; } } export class IMContextSimple extends IMContext { static $gtype: GObject.GType<IMContextSimple>; constructor( properties?: Partial<IMContextSimple.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<IMContextSimple.ConstructorProperties>, ...args: any[] ): void; // Fields object: IMContext; // Constructors static ['new'](): IMContextSimple; // Members add_compose_file(compose_file: string): void; } export namespace IMMulticontext { export interface ConstructorProperties extends IMContext.ConstructorProperties { [key: string]: any; } } export class IMMulticontext extends IMContext { static $gtype: GObject.GType<IMMulticontext>; constructor( properties?: Partial<IMMulticontext.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<IMMulticontext.ConstructorProperties>, ...args: any[] ): void; // Fields object: IMContext; // Constructors static ['new'](): IMMulticontext; // Members get_context_id(): string; set_context_id(context_id: string): void; } export namespace IconPaintable { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; file: Gio.File; icon_name: string; iconName: string; is_symbolic: boolean; isSymbolic: boolean; } } export class IconPaintable extends GObject.Object implements Gdk.Paintable { static $gtype: GObject.GType<IconPaintable>; constructor( properties?: Partial<IconPaintable.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<IconPaintable.ConstructorProperties>, ...args: any[] ): void; // Properties file: Gio.File; icon_name: string; iconName: string; is_symbolic: boolean; isSymbolic: boolean; // Constructors static new_for_file( file: Gio.File, size: number, scale: number ): IconPaintable; // Members get_file(): Gio.File | null; get_icon_name(): string | null; // Implemented Members compute_concrete_size( specified_width: number, specified_height: number, default_width: number, default_height: number ): [number, number]; get_current_image(): Gdk.Paintable; get_flags(): Gdk.PaintableFlags; get_intrinsic_aspect_ratio(): number; get_intrinsic_height(): number; get_intrinsic_width(): number; invalidate_contents(): void; invalidate_size(): void; snapshot(snapshot: Gdk.Snapshot, width: number, height: number): void; vfunc_get_current_image(): Gdk.Paintable; vfunc_get_flags(): Gdk.PaintableFlags; vfunc_get_intrinsic_aspect_ratio(): number; vfunc_get_intrinsic_height(): number; vfunc_get_intrinsic_width(): number; vfunc_snapshot(snapshot: Gdk.Snapshot, width: number, height: number): void; } export namespace IconTheme { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; display: Gdk.Display; icon_names: string[]; iconNames: string[]; resource_path: string[]; resourcePath: string[]; search_path: string[]; searchPath: string[]; theme_name: string; themeName: string; } } export class IconTheme extends GObject.Object { static $gtype: GObject.GType<IconTheme>; constructor( properties?: Partial<IconTheme.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<IconTheme.ConstructorProperties>, ...args: any[] ): void; // Properties display: Gdk.Display; icon_names: string[]; iconNames: string[]; resource_path: string[]; resourcePath: string[]; search_path: string[]; searchPath: string[]; theme_name: string; themeName: string; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'changed', callback: (_source: this) => void): number; connect_after(signal: 'changed', callback: (_source: this) => void): number; emit(signal: 'changed'): void; // Constructors static ['new'](): IconTheme; // Members add_resource_path(path: string): void; add_search_path(path: string): void; get_display(): Gdk.Display | null; get_icon_names(): string[]; get_icon_sizes(icon_name: string): number[]; get_resource_path(): string[] | null; get_search_path(): string[] | null; get_theme_name(): string; has_icon(icon_name: string): boolean; lookup_by_gicon( icon: Gio.Icon, size: number, scale: number, direction: TextDirection, flags: IconLookupFlags ): IconPaintable; lookup_icon( icon_name: string, fallbacks: string[] | null, size: number, scale: number, direction: TextDirection, flags: IconLookupFlags ): IconPaintable; set_resource_path(path: string): void; set_search_path(path?: string[] | null): void; set_theme_name(theme_name?: string | null): void; static get_for_display(display: Gdk.Display): IconTheme; } export namespace IconView { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; activate_on_single_click: boolean; activateOnSingleClick: boolean; cell_area: CellArea; cellArea: CellArea; column_spacing: number; columnSpacing: number; columns: number; item_orientation: Orientation; itemOrientation: Orientation; item_padding: number; itemPadding: number; item_width: number; itemWidth: number; margin: number; markup_column: number; markupColumn: number; model: TreeModel; pixbuf_column: number; pixbufColumn: number; reorderable: boolean; row_spacing: number; rowSpacing: number; selection_mode: SelectionMode; selectionMode: SelectionMode; spacing: number; text_column: number; textColumn: number; tooltip_column: number; tooltipColumn: number; } } export class IconView extends Widget implements Accessible, Buildable, CellLayout, ConstraintTarget, Scrollable { static $gtype: GObject.GType<IconView>; constructor( properties?: Partial<IconView.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<IconView.ConstructorProperties>, ...args: any[] ): void; // Properties activate_on_single_click: boolean; activateOnSingleClick: boolean; cell_area: CellArea; cellArea: CellArea; column_spacing: number; columnSpacing: number; columns: number; item_orientation: Orientation; itemOrientation: Orientation; item_padding: number; itemPadding: number; item_width: number; itemWidth: number; margin: number; markup_column: number; markupColumn: number; model: TreeModel; pixbuf_column: number; pixbufColumn: number; reorderable: boolean; row_spacing: number; rowSpacing: number; selection_mode: SelectionMode; selectionMode: SelectionMode; spacing: number; text_column: number; textColumn: number; tooltip_column: number; tooltipColumn: number; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'activate-cursor-item', callback: (_source: this) => boolean ): number; connect_after( signal: 'activate-cursor-item', callback: (_source: this) => boolean ): number; emit(signal: 'activate-cursor-item'): void; connect( signal: 'item-activated', callback: (_source: this, path: TreePath) => void ): number; connect_after( signal: 'item-activated', callback: (_source: this, path: TreePath) => void ): number; emit(signal: 'item-activated', path: TreePath): void; connect( signal: 'move-cursor', callback: ( _source: this, step: MovementStep, count: number, extend: boolean, modify: boolean ) => boolean ): number; connect_after( signal: 'move-cursor', callback: ( _source: this, step: MovementStep, count: number, extend: boolean, modify: boolean ) => boolean ): number; emit( signal: 'move-cursor', step: MovementStep, count: number, extend: boolean, modify: boolean ): void; connect(signal: 'select-all', callback: (_source: this) => void): number; connect_after( signal: 'select-all', callback: (_source: this) => void ): number; emit(signal: 'select-all'): void; connect( signal: 'select-cursor-item', callback: (_source: this) => void ): number; connect_after( signal: 'select-cursor-item', callback: (_source: this) => void ): number; emit(signal: 'select-cursor-item'): void; connect( signal: 'selection-changed', callback: (_source: this) => void ): number; connect_after( signal: 'selection-changed', callback: (_source: this) => void ): number; emit(signal: 'selection-changed'): void; connect( signal: 'toggle-cursor-item', callback: (_source: this) => void ): number; connect_after( signal: 'toggle-cursor-item', callback: (_source: this) => void ): number; emit(signal: 'toggle-cursor-item'): void; connect(signal: 'unselect-all', callback: (_source: this) => void): number; connect_after( signal: 'unselect-all', callback: (_source: this) => void ): number; emit(signal: 'unselect-all'): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; hadjustment: Adjustment; hscroll_policy: ScrollablePolicy; hscrollPolicy: ScrollablePolicy; vadjustment: Adjustment; vscroll_policy: ScrollablePolicy; vscrollPolicy: ScrollablePolicy; // Constructors static ['new'](): IconView; static new_with_area(area: CellArea): IconView; static new_with_model(model: TreeModel): IconView; // Members create_drag_icon(path: TreePath): Gdk.Paintable; enable_model_drag_dest( formats: Gdk.ContentFormats, actions: Gdk.DragAction ): void; enable_model_drag_source( start_button_mask: Gdk.ModifierType, formats: Gdk.ContentFormats, actions: Gdk.DragAction ): void; get_activate_on_single_click(): boolean; get_cell_rect( path: TreePath, cell: CellRenderer | null ): [boolean, Gdk.Rectangle]; get_column_spacing(): number; get_columns(): number; get_cursor(): [boolean, TreePath | null, CellRenderer | null]; get_cursor(...args: never[]): never; get_dest_item_at_pos( drag_x: number, drag_y: number ): [boolean, TreePath | null, IconViewDropPosition | null]; get_drag_dest_item(): [TreePath | null, IconViewDropPosition | null]; get_item_at_pos( x: number, y: number ): [boolean, TreePath | null, CellRenderer | null]; get_item_column(path: TreePath): number; get_item_orientation(): Orientation; get_item_padding(): number; get_item_row(path: TreePath): number; get_item_width(): number; get_margin(): number; get_markup_column(): number; get_model(): TreeModel | null; get_path_at_pos(x: number, y: number): TreePath | null; get_pixbuf_column(): number; get_reorderable(): boolean; get_row_spacing(): number; get_selected_items(): TreePath[]; get_selection_mode(): SelectionMode; get_spacing(): number; get_text_column(): number; get_tooltip_column(): number; get_tooltip_context( x: number, y: number, keyboard_tip: boolean ): [boolean, TreeModel | null, TreePath | null, TreeIter | null]; get_visible_range(): [boolean, TreePath | null, TreePath | null]; item_activated(path: TreePath): void; path_is_selected(path: TreePath): boolean; scroll_to_path( path: TreePath, use_align: boolean, row_align: number, col_align: number ): void; select_all(): void; select_path(path: TreePath): void; selected_foreach(func: IconViewForeachFunc): void; set_activate_on_single_click(single: boolean): void; set_column_spacing(column_spacing: number): void; set_columns(columns: number): void; set_cursor( path: TreePath, cell: CellRenderer | null, start_editing: boolean ): void; set_cursor(...args: never[]): never; set_drag_dest_item(path: TreePath | null, pos: IconViewDropPosition): void; set_item_orientation(orientation: Orientation): void; set_item_padding(item_padding: number): void; set_item_width(item_width: number): void; set_margin(margin: number): void; set_markup_column(column: number): void; set_model(model?: TreeModel | null): void; set_pixbuf_column(column: number): void; set_reorderable(reorderable: boolean): void; set_row_spacing(row_spacing: number): void; set_selection_mode(mode: SelectionMode): void; set_spacing(spacing: number): void; set_text_column(column: number): void; set_tooltip_cell( tooltip: Tooltip, path: TreePath, cell?: CellRenderer | null ): void; set_tooltip_column(column: number): void; set_tooltip_item(tooltip: Tooltip, path: TreePath): void; unselect_all(): void; unselect_path(path: TreePath): void; unset_model_drag_dest(): void; unset_model_drag_source(): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; add_attribute(cell: CellRenderer, attribute: string, column: number): void; clear(): void; clear_attributes(cell: CellRenderer): void; get_area(): CellArea | null; get_cells(): CellRenderer[]; pack_end(cell: CellRenderer, expand: boolean): void; pack_start(cell: CellRenderer, expand: boolean): void; reorder(cell: CellRenderer, position: number): void; set_cell_data_func( cell: CellRenderer, func?: CellLayoutDataFunc | null ): void; vfunc_add_attribute( cell: CellRenderer, attribute: string, column: number ): void; vfunc_clear(): void; vfunc_clear_attributes(cell: CellRenderer): void; vfunc_get_area(): CellArea | null; vfunc_get_cells(): CellRenderer[]; vfunc_pack_end(cell: CellRenderer, expand: boolean): void; vfunc_pack_start(cell: CellRenderer, expand: boolean): void; vfunc_reorder(cell: CellRenderer, position: number): void; vfunc_set_cell_data_func( cell: CellRenderer, func?: CellLayoutDataFunc | null ): void; get_border(): [boolean, Border]; get_hadjustment(): Adjustment; get_hscroll_policy(): ScrollablePolicy; get_vadjustment(): Adjustment; get_vscroll_policy(): ScrollablePolicy; set_hadjustment(hadjustment?: Adjustment | null): void; set_hscroll_policy(policy: ScrollablePolicy): void; set_vadjustment(vadjustment?: Adjustment | null): void; set_vscroll_policy(policy: ScrollablePolicy): void; vfunc_get_border(): [boolean, Border]; } export namespace Image { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; file: string; gicon: Gio.Icon; icon_name: string; iconName: string; icon_size: IconSize; iconSize: IconSize; paintable: Gdk.Paintable; pixel_size: number; pixelSize: number; resource: string; storage_type: ImageType; storageType: ImageType; use_fallback: boolean; useFallback: boolean; } } export class Image extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<Image>; constructor( properties?: Partial<Image.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Image.ConstructorProperties>, ...args: any[] ): void; // Properties file: string; gicon: Gio.Icon; icon_name: string; iconName: string; icon_size: IconSize; iconSize: IconSize; paintable: Gdk.Paintable; pixel_size: number; pixelSize: number; resource: string; storage_type: ImageType; storageType: ImageType; use_fallback: boolean; useFallback: boolean; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](): Image; static new_from_file(filename: string): Image; static new_from_gicon(icon: Gio.Icon): Image; static new_from_icon_name(icon_name?: string | null): Image; static new_from_paintable(paintable?: Gdk.Paintable | null): Image; static new_from_pixbuf(pixbuf?: GdkPixbuf.Pixbuf | null): Image; static new_from_resource(resource_path: string): Image; // Members clear(): void; get_gicon(): Gio.Icon | null; get_icon_name(): string | null; get_icon_size(): IconSize; get_paintable(): Gdk.Paintable | null; get_pixel_size(): number; get_storage_type(): ImageType; set_from_file(filename?: string | null): void; set_from_gicon(icon: Gio.Icon): void; set_from_icon_name(icon_name?: string | null): void; set_from_paintable(paintable?: Gdk.Paintable | null): void; set_from_pixbuf(pixbuf?: GdkPixbuf.Pixbuf | null): void; set_from_resource(resource_path?: string | null): void; set_icon_size(icon_size: IconSize): void; set_pixel_size(pixel_size: number): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace InfoBar { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; message_type: MessageType; messageType: MessageType; revealed: boolean; show_close_button: boolean; showCloseButton: boolean; } } export class InfoBar extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<InfoBar>; constructor( properties?: Partial<InfoBar.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<InfoBar.ConstructorProperties>, ...args: any[] ): void; // Properties message_type: MessageType; messageType: MessageType; revealed: boolean; show_close_button: boolean; showCloseButton: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'close', callback: (_source: this) => void): number; connect_after(signal: 'close', callback: (_source: this) => void): number; emit(signal: 'close'): void; connect( signal: 'response', callback: (_source: this, response_id: number) => void ): number; connect_after( signal: 'response', callback: (_source: this, response_id: number) => void ): number; emit(signal: 'response', response_id: number): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](): InfoBar; // Members add_action_widget(child: Widget, response_id: number): void; add_button(button_text: string, response_id: number): Button; add_child(widget: Widget): void; get_message_type(): MessageType; get_revealed(): boolean; get_show_close_button(): boolean; remove_action_widget(widget: Widget): void; remove_child(widget: Widget): void; response(response_id: number): void; set_default_response(response_id: number): void; set_message_type(message_type: MessageType): void; set_response_sensitive(response_id: number, setting: boolean): void; set_revealed(revealed: boolean): void; set_show_close_button(setting: boolean): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace KeyvalTrigger { export interface ConstructorProperties extends ShortcutTrigger.ConstructorProperties { [key: string]: any; keyval: number; modifiers: Gdk.ModifierType; } } export class KeyvalTrigger extends ShortcutTrigger { static $gtype: GObject.GType<KeyvalTrigger>; constructor( properties?: Partial<KeyvalTrigger.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<KeyvalTrigger.ConstructorProperties>, ...args: any[] ): void; // Properties keyval: number; modifiers: Gdk.ModifierType; // Constructors static ['new'](keyval: number, modifiers: Gdk.ModifierType): KeyvalTrigger; // Members get_keyval(): number; get_modifiers(): Gdk.ModifierType; } export namespace Label { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; attributes: Pango.AttrList; ellipsize: Pango.EllipsizeMode; extra_menu: Gio.MenuModel; extraMenu: Gio.MenuModel; justify: Justification; label: string; lines: number; max_width_chars: number; maxWidthChars: number; mnemonic_keyval: number; mnemonicKeyval: number; mnemonic_widget: Widget; mnemonicWidget: Widget; selectable: boolean; single_line_mode: boolean; singleLineMode: boolean; use_markup: boolean; useMarkup: boolean; use_underline: boolean; useUnderline: boolean; width_chars: number; widthChars: number; wrap: boolean; wrap_mode: Pango.WrapMode; wrapMode: Pango.WrapMode; xalign: number; yalign: number; } } export class Label extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<Label>; constructor( properties?: Partial<Label.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Label.ConstructorProperties>, ...args: any[] ): void; // Properties attributes: Pango.AttrList; ellipsize: Pango.EllipsizeMode; extra_menu: Gio.MenuModel; extraMenu: Gio.MenuModel; justify: Justification; label: string; lines: number; max_width_chars: number; maxWidthChars: number; mnemonic_keyval: number; mnemonicKeyval: number; mnemonic_widget: Widget; mnemonicWidget: Widget; selectable: boolean; single_line_mode: boolean; singleLineMode: boolean; use_markup: boolean; useMarkup: boolean; use_underline: boolean; useUnderline: boolean; width_chars: number; widthChars: number; wrap: boolean; wrap_mode: Pango.WrapMode; wrapMode: Pango.WrapMode; xalign: number; yalign: number; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'activate-current-link', callback: (_source: this) => void ): number; connect_after( signal: 'activate-current-link', callback: (_source: this) => void ): number; emit(signal: 'activate-current-link'): void; connect( signal: 'activate-link', callback: (_source: this, uri: string) => boolean ): number; connect_after( signal: 'activate-link', callback: (_source: this, uri: string) => boolean ): number; emit(signal: 'activate-link', uri: string): void; connect( signal: 'copy-clipboard', callback: (_source: this) => void ): number; connect_after( signal: 'copy-clipboard', callback: (_source: this) => void ): number; emit(signal: 'copy-clipboard'): void; connect( signal: 'move-cursor', callback: ( _source: this, step: MovementStep, count: number, extend_selection: boolean ) => void ): number; connect_after( signal: 'move-cursor', callback: ( _source: this, step: MovementStep, count: number, extend_selection: boolean ) => void ): number; emit( signal: 'move-cursor', step: MovementStep, count: number, extend_selection: boolean ): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](str?: string | null): Label; static new_with_mnemonic(str?: string | null): Label; // Members get_attributes(): Pango.AttrList | null; get_current_uri(): string | null; get_ellipsize(): Pango.EllipsizeMode; get_extra_menu(): Gio.MenuModel | null; get_justify(): Justification; get_label(): string; get_layout(): Pango.Layout; get_layout_offsets(): [number | null, number | null]; get_lines(): number; get_max_width_chars(): number; get_mnemonic_keyval(): number; get_mnemonic_widget(): Widget | null; get_selectable(): boolean; get_selection_bounds(): [boolean, number, number]; get_single_line_mode(): boolean; get_text(): string; get_use_markup(): boolean; get_use_underline(): boolean; get_width_chars(): number; get_wrap(): boolean; get_wrap_mode(): Pango.WrapMode; get_xalign(): number; get_yalign(): number; select_region(start_offset: number, end_offset: number): void; set_attributes(attrs?: Pango.AttrList | null): void; set_ellipsize(mode: Pango.EllipsizeMode): void; set_extra_menu(model?: Gio.MenuModel | null): void; set_justify(jtype: Justification): void; set_label(str: string): void; set_lines(lines: number): void; set_markup(str: string): void; set_markup_with_mnemonic(str: string): void; set_max_width_chars(n_chars: number): void; set_mnemonic_widget(widget?: Widget | null): void; set_selectable(setting: boolean): void; set_single_line_mode(single_line_mode: boolean): void; set_text(str: string): void; set_text_with_mnemonic(str: string): void; set_use_markup(setting: boolean): void; set_use_underline(setting: boolean): void; set_width_chars(n_chars: number): void; set_wrap(wrap: boolean): void; set_wrap_mode(wrap_mode: Pango.WrapMode): void; set_xalign(xalign: number): void; set_yalign(yalign: number): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace LayoutChild { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; child_widget: Widget; childWidget: Widget; layout_manager: LayoutManager; layoutManager: LayoutManager; } } export abstract class LayoutChild extends GObject.Object { static $gtype: GObject.GType<LayoutChild>; constructor( properties?: Partial<LayoutChild.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<LayoutChild.ConstructorProperties>, ...args: any[] ): void; // Properties child_widget: Widget; childWidget: Widget; layout_manager: LayoutManager; layoutManager: LayoutManager; // Members get_child_widget(): Widget; get_layout_manager(): LayoutManager; } export namespace LayoutManager { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export abstract class LayoutManager extends GObject.Object { static $gtype: GObject.GType<LayoutManager>; constructor( properties?: Partial<LayoutManager.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<LayoutManager.ConstructorProperties>, ...args: any[] ): void; // Members allocate( widget: Widget, width: number, height: number, baseline: number ): void; get_layout_child(child: Widget): LayoutChild; get_request_mode(): SizeRequestMode; get_widget(): Widget | null; layout_changed(): void; measure( widget: Widget, orientation: Orientation, for_size: number ): [number | null, number | null, number | null, number | null]; vfunc_allocate( widget: Widget, width: number, height: number, baseline: number ): void; vfunc_create_layout_child(widget: Widget, for_child: Widget): LayoutChild; vfunc_get_request_mode(widget: Widget): SizeRequestMode; vfunc_measure( widget: Widget, orientation: Orientation, for_size: number ): [number | null, number | null, number | null, number | null]; vfunc_root(): void; vfunc_unroot(): void; } export namespace LevelBar { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; inverted: boolean; max_value: number; maxValue: number; min_value: number; minValue: number; mode: LevelBarMode; value: number; } } export class LevelBar extends Widget implements Accessible, Buildable, ConstraintTarget, Orientable { static $gtype: GObject.GType<LevelBar>; constructor( properties?: Partial<LevelBar.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<LevelBar.ConstructorProperties>, ...args: any[] ): void; // Properties inverted: boolean; max_value: number; maxValue: number; min_value: number; minValue: number; mode: LevelBarMode; value: number; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'offset-changed', callback: (_source: this, name: string) => void ): number; connect_after( signal: 'offset-changed', callback: (_source: this, name: string) => void ): number; emit(signal: 'offset-changed', name: string): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; orientation: Orientation; // Constructors static ['new'](): LevelBar; static new_for_interval(min_value: number, max_value: number): LevelBar; // Members add_offset_value(name: string, value: number): void; get_inverted(): boolean; get_max_value(): number; get_min_value(): number; get_mode(): LevelBarMode; get_offset_value(name: string | null): [boolean, number]; get_value(): number; remove_offset_value(name?: string | null): void; set_inverted(inverted: boolean): void; set_max_value(value: number): void; set_min_value(value: number): void; set_mode(mode: LevelBarMode): void; set_value(value: number): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_orientation(): Orientation; set_orientation(orientation: Orientation): void; } export namespace LinkButton { export interface ConstructorProperties extends Button.ConstructorProperties { [key: string]: any; uri: string; visited: boolean; } } export class LinkButton extends Button implements Accessible, Actionable, Buildable, ConstraintTarget { static $gtype: GObject.GType<LinkButton>; constructor( properties?: Partial<LinkButton.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<LinkButton.ConstructorProperties>, ...args: any[] ): void; // Properties uri: string; visited: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'activate-link', callback: (_source: this) => boolean ): number; connect_after( signal: 'activate-link', callback: (_source: this) => boolean ): number; emit(signal: 'activate-link'): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; action_name: string; actionName: string; action_target: GLib.Variant; actionTarget: GLib.Variant; // Constructors static ['new'](uri: string): LinkButton; static ['new'](...args: never[]): never; static new_with_label(uri: string, label?: string | null): LinkButton; static new_with_label(...args: never[]): never; // Members get_uri(): string; get_visited(): boolean; set_uri(uri: string): void; set_visited(visited: boolean): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_action_name(): string | null; get_action_target_value(): GLib.Variant | null; set_action_name(action_name?: string | null): void; set_action_target_value(target_value?: GLib.Variant | null): void; set_detailed_action_name(detailed_action_name: string): void; vfunc_get_action_name(): string | null; vfunc_get_action_target_value(): GLib.Variant | null; vfunc_set_action_name(action_name?: string | null): void; vfunc_set_action_target_value(target_value?: GLib.Variant | null): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace ListBase { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; orientation: Orientation; } } export abstract class ListBase extends Widget implements Accessible, Buildable, ConstraintTarget, Orientable, Scrollable { static $gtype: GObject.GType<ListBase>; constructor( properties?: Partial<ListBase.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ListBase.ConstructorProperties>, ...args: any[] ): void; // Properties orientation: Orientation; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; hadjustment: Adjustment; hscroll_policy: ScrollablePolicy; hscrollPolicy: ScrollablePolicy; vadjustment: Adjustment; vscroll_policy: ScrollablePolicy; vscrollPolicy: ScrollablePolicy; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_orientation(): Orientation; set_orientation(orientation: Orientation): void; get_border(): [boolean, Border]; get_hadjustment(): Adjustment; get_hscroll_policy(): ScrollablePolicy; get_vadjustment(): Adjustment; get_vscroll_policy(): ScrollablePolicy; set_hadjustment(hadjustment?: Adjustment | null): void; set_hscroll_policy(policy: ScrollablePolicy): void; set_vadjustment(vadjustment?: Adjustment | null): void; set_vscroll_policy(policy: ScrollablePolicy): void; vfunc_get_border(): [boolean, Border]; } export namespace ListBox { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; accept_unpaired_release: boolean; acceptUnpairedRelease: boolean; activate_on_single_click: boolean; activateOnSingleClick: boolean; selection_mode: SelectionMode; selectionMode: SelectionMode; show_separators: boolean; showSeparators: boolean; } } export class ListBox extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<ListBox>; constructor( properties?: Partial<ListBox.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ListBox.ConstructorProperties>, ...args: any[] ): void; // Properties accept_unpaired_release: boolean; acceptUnpairedRelease: boolean; activate_on_single_click: boolean; activateOnSingleClick: boolean; selection_mode: SelectionMode; selectionMode: SelectionMode; show_separators: boolean; showSeparators: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'activate-cursor-row', callback: (_source: this) => void ): number; connect_after( signal: 'activate-cursor-row', callback: (_source: this) => void ): number; emit(signal: 'activate-cursor-row'): void; connect( signal: 'move-cursor', callback: ( _source: this, object: MovementStep, p0: number, p1: boolean, p2: boolean ) => void ): number; connect_after( signal: 'move-cursor', callback: ( _source: this, object: MovementStep, p0: number, p1: boolean, p2: boolean ) => void ): number; emit( signal: 'move-cursor', object: MovementStep, p0: number, p1: boolean, p2: boolean ): void; connect( signal: 'row-activated', callback: (_source: this, row: ListBoxRow) => void ): number; connect_after( signal: 'row-activated', callback: (_source: this, row: ListBoxRow) => void ): number; emit(signal: 'row-activated', row: ListBoxRow): void; connect( signal: 'row-selected', callback: (_source: this, row: ListBoxRow | null) => void ): number; connect_after( signal: 'row-selected', callback: (_source: this, row: ListBoxRow | null) => void ): number; emit(signal: 'row-selected', row: ListBoxRow | null): void; connect(signal: 'select-all', callback: (_source: this) => void): number; connect_after( signal: 'select-all', callback: (_source: this) => void ): number; emit(signal: 'select-all'): void; connect( signal: 'selected-rows-changed', callback: (_source: this) => void ): number; connect_after( signal: 'selected-rows-changed', callback: (_source: this) => void ): number; emit(signal: 'selected-rows-changed'): void; connect( signal: 'toggle-cursor-row', callback: (_source: this) => void ): number; connect_after( signal: 'toggle-cursor-row', callback: (_source: this) => void ): number; emit(signal: 'toggle-cursor-row'): void; connect(signal: 'unselect-all', callback: (_source: this) => void): number; connect_after( signal: 'unselect-all', callback: (_source: this) => void ): number; emit(signal: 'unselect-all'): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](): ListBox; // Members append(child: Widget): void; bind_model( model?: Gio.ListModel | null, create_widget_func?: ListBoxCreateWidgetFunc | null ): void; drag_highlight_row(row: ListBoxRow): void; drag_unhighlight_row(): void; get_activate_on_single_click(): boolean; get_adjustment(): Adjustment; get_row_at_index(index_: number): ListBoxRow | null; get_row_at_y(y: number): ListBoxRow | null; get_selected_row(): ListBoxRow; get_selected_rows(): ListBoxRow[]; get_selection_mode(): SelectionMode; get_show_separators(): boolean; insert(child: Widget, position: number): void; invalidate_filter(): void; invalidate_headers(): void; invalidate_sort(): void; prepend(child: Widget): void; remove(child: Widget): void; select_all(): void; select_row(row?: ListBoxRow | null): void; selected_foreach(func: ListBoxForeachFunc): void; set_activate_on_single_click(single: boolean): void; set_adjustment(adjustment?: Adjustment | null): void; set_filter_func(filter_func?: ListBoxFilterFunc | null): void; set_header_func(update_header?: ListBoxUpdateHeaderFunc | null): void; set_placeholder(placeholder?: Widget | null): void; set_selection_mode(mode: SelectionMode): void; set_show_separators(show_separators: boolean): void; set_sort_func(sort_func?: ListBoxSortFunc | null): void; unselect_all(): void; unselect_row(row: ListBoxRow): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace ListBoxRow { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; activatable: boolean; child: Widget; selectable: boolean; } } export class ListBoxRow extends Widget implements Accessible, Actionable, Buildable, ConstraintTarget { static $gtype: GObject.GType<ListBoxRow>; constructor( properties?: Partial<ListBoxRow.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ListBoxRow.ConstructorProperties>, ...args: any[] ): void; // Properties activatable: boolean; child: Widget; selectable: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'activate', callback: (_source: this) => void): number; connect_after( signal: 'activate', callback: (_source: this) => void ): number; emit(signal: 'activate'): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; action_name: string; actionName: string; action_target: GLib.Variant; actionTarget: GLib.Variant; // Constructors static ['new'](): ListBoxRow; // Members changed(): void; get_activatable(): boolean; get_child(): Widget | null; get_header(): Widget | null; get_index(): number; get_selectable(): boolean; is_selected(): boolean; set_activatable(activatable: boolean): void; set_child(child?: Widget | null): void; set_header(header?: Widget | null): void; set_selectable(selectable: boolean): void; vfunc_activate(): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_action_name(): string | null; get_action_target_value(): GLib.Variant | null; set_action_name(action_name?: string | null): void; set_action_target_value(target_value?: GLib.Variant | null): void; set_detailed_action_name(detailed_action_name: string): void; vfunc_get_action_name(): string | null; vfunc_get_action_target_value(): GLib.Variant | null; vfunc_set_action_name(action_name?: string | null): void; vfunc_set_action_target_value(target_value?: GLib.Variant | null): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace ListItem { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; activatable: boolean; child: Widget; item: GObject.Object; position: number; selectable: boolean; selected: boolean; } } export class ListItem extends GObject.Object { static $gtype: GObject.GType<ListItem>; constructor( properties?: Partial<ListItem.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ListItem.ConstructorProperties>, ...args: any[] ): void; // Properties activatable: boolean; child: Widget; item: GObject.Object; position: number; selectable: boolean; selected: boolean; // Members get_activatable(): boolean; get_child(): Widget | null; get_item<T = GObject.Object>(): T; get_position(): number; get_selectable(): boolean; get_selected(): boolean; set_activatable(activatable: boolean): void; set_child(child?: Widget | null): void; set_selectable(selectable: boolean): void; } export namespace ListItemFactory { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class ListItemFactory extends GObject.Object { static $gtype: GObject.GType<ListItemFactory>; constructor( properties?: Partial<ListItemFactory.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ListItemFactory.ConstructorProperties>, ...args: any[] ): void; } export namespace ListStore { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class ListStore extends GObject.Object implements Buildable, TreeDragDest, TreeDragSource, TreeModel, TreeSortable { static $gtype: GObject.GType<ListStore>; constructor( properties?: Partial<ListStore.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ListStore.ConstructorProperties>, ...args: any[] ): void; // Constructors static ['new'](types: GObject.GType[]): ListStore; // Members append(): TreeIter; clear(): void; insert(position: number): TreeIter; insert_after(sibling?: TreeIter | null): TreeIter; insert_before(sibling?: TreeIter | null): TreeIter; insert_with_valuesv( position: number, columns: number[], values: GObject.Value[] ): TreeIter | null; iter_is_valid(iter: TreeIter): boolean; move_after(iter: TreeIter, position?: TreeIter | null): void; move_before(iter: TreeIter, position?: TreeIter | null): void; prepend(): TreeIter; remove(iter: TreeIter): boolean; reorder(new_order: number[]): void; set_column_types(types: GObject.GType[]): void; set_value(iter: TreeIter, column: number, value: any): void; set(iter: TreeIter, columns: number[], values: GObject.Value[]): void; set(...args: never[]): never; swap(a: TreeIter, b: TreeIter): void; // Implemented Members get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; drag_data_received(dest: TreePath, value: any): boolean; row_drop_possible(dest_path: TreePath, value: any): boolean; vfunc_drag_data_received(dest: TreePath, value: any): boolean; vfunc_row_drop_possible(dest_path: TreePath, value: any): boolean; drag_data_delete(path: TreePath): boolean; drag_data_get(path: TreePath): Gdk.ContentProvider | null; row_draggable(path: TreePath): boolean; vfunc_drag_data_delete(path: TreePath): boolean; vfunc_drag_data_get(path: TreePath): Gdk.ContentProvider | null; vfunc_row_draggable(path: TreePath): boolean; filter_new(root?: TreePath | null): TreeModel; foreach(func: TreeModelForeachFunc): void; get_column_type(index_: number): GObject.GType; get_flags(): TreeModelFlags; get_iter(path: TreePath): [boolean, TreeIter]; get_iter_first(): [boolean, TreeIter]; get_iter_from_string(path_string: string): [boolean, TreeIter]; get_n_columns(): number; get_path(iter: TreeIter): TreePath; get_string_from_iter(iter: TreeIter): string | null; get_value(iter: TreeIter, column: number): unknown; iter_children(parent?: TreeIter | null): [boolean, TreeIter]; iter_has_child(iter: TreeIter): boolean; iter_n_children(iter?: TreeIter | null): number; iter_next(iter: TreeIter): boolean; iter_nth_child(parent: TreeIter | null, n: number): [boolean, TreeIter]; iter_parent(child: TreeIter): [boolean, TreeIter]; iter_previous(iter: TreeIter): boolean; ref_node(iter: TreeIter): void; row_changed(path: TreePath, iter: TreeIter): void; row_deleted(path: TreePath): void; row_has_child_toggled(path: TreePath, iter: TreeIter): void; row_inserted(path: TreePath, iter: TreeIter): void; rows_reordered( path: TreePath, iter: TreeIter | null, new_order: number[] ): void; unref_node(iter: TreeIter): void; vfunc_get_column_type(index_: number): GObject.GType; vfunc_get_flags(): TreeModelFlags; vfunc_get_iter(path: TreePath): [boolean, TreeIter]; vfunc_get_n_columns(): number; vfunc_get_path(iter: TreeIter): TreePath; vfunc_get_value(iter: TreeIter, column: number): unknown; vfunc_iter_children(parent?: TreeIter | null): [boolean, TreeIter]; vfunc_iter_has_child(iter: TreeIter): boolean; vfunc_iter_n_children(iter?: TreeIter | null): number; vfunc_iter_next(iter: TreeIter): boolean; vfunc_iter_nth_child( parent: TreeIter | null, n: number ): [boolean, TreeIter]; vfunc_iter_parent(child: TreeIter): [boolean, TreeIter]; vfunc_iter_previous(iter: TreeIter): boolean; vfunc_ref_node(iter: TreeIter): void; vfunc_row_changed(path: TreePath, iter: TreeIter): void; vfunc_row_deleted(path: TreePath): void; vfunc_row_has_child_toggled(path: TreePath, iter: TreeIter): void; vfunc_row_inserted(path: TreePath, iter: TreeIter): void; vfunc_unref_node(iter: TreeIter): void; get_sort_column_id(): [boolean, number, SortType]; has_default_sort_func(): boolean; set_default_sort_func( sort_func: TreeIterCompareFunc, destroy?: GLib.DestroyNotify | null ): void; set_sort_column_id(sort_column_id: number, order: SortType): void; set_sort_func( sort_column_id: number, sort_func: TreeIterCompareFunc, destroy?: GLib.DestroyNotify | null ): void; sort_column_changed(): void; vfunc_get_sort_column_id(): [boolean, number, SortType]; vfunc_has_default_sort_func(): boolean; vfunc_set_default_sort_func( sort_func: TreeIterCompareFunc, destroy?: GLib.DestroyNotify | null ): void; vfunc_set_sort_column_id(sort_column_id: number, order: SortType): void; vfunc_set_sort_func( sort_column_id: number, sort_func: TreeIterCompareFunc, destroy?: GLib.DestroyNotify | null ): void; vfunc_sort_column_changed(): void; } export namespace ListView { export interface ConstructorProperties extends ListBase.ConstructorProperties { [key: string]: any; enable_rubberband: boolean; enableRubberband: boolean; factory: ListItemFactory; model: SelectionModel; show_separators: boolean; showSeparators: boolean; single_click_activate: boolean; singleClickActivate: boolean; } } export class ListView extends ListBase implements Accessible, Buildable, ConstraintTarget, Orientable, Scrollable { static $gtype: GObject.GType<ListView>; constructor( properties?: Partial<ListView.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ListView.ConstructorProperties>, ...args: any[] ): void; // Properties enable_rubberband: boolean; enableRubberband: boolean; factory: ListItemFactory; model: SelectionModel; show_separators: boolean; showSeparators: boolean; single_click_activate: boolean; singleClickActivate: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'activate', callback: (_source: this, position: number) => void ): number; connect_after( signal: 'activate', callback: (_source: this, position: number) => void ): number; emit(signal: 'activate', position: number): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; orientation: Orientation; hadjustment: Adjustment; hscroll_policy: ScrollablePolicy; hscrollPolicy: ScrollablePolicy; vadjustment: Adjustment; vscroll_policy: ScrollablePolicy; vscrollPolicy: ScrollablePolicy; // Constructors static ['new']( model?: SelectionModel | null, factory?: ListItemFactory | null ): ListView; // Members get_enable_rubberband(): boolean; get_factory(): ListItemFactory | null; get_model(): SelectionModel | null; get_show_separators(): boolean; get_single_click_activate(): boolean; set_enable_rubberband(enable_rubberband: boolean): void; set_factory(factory?: ListItemFactory | null): void; set_model(model?: SelectionModel | null): void; set_show_separators(show_separators: boolean): void; set_single_click_activate(single_click_activate: boolean): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_orientation(): Orientation; set_orientation(orientation: Orientation): void; get_border(): [boolean, Border]; get_hadjustment(): Adjustment; get_hscroll_policy(): ScrollablePolicy; get_vadjustment(): Adjustment; get_vscroll_policy(): ScrollablePolicy; set_hadjustment(hadjustment?: Adjustment | null): void; set_hscroll_policy(policy: ScrollablePolicy): void; set_vadjustment(vadjustment?: Adjustment | null): void; set_vscroll_policy(policy: ScrollablePolicy): void; vfunc_get_border(): [boolean, Border]; } export namespace LockButton { export interface ConstructorProperties extends Button.ConstructorProperties { [key: string]: any; permission: Gio.Permission; text_lock: string; textLock: string; text_unlock: string; textUnlock: string; tooltip_lock: string; tooltipLock: string; tooltip_not_authorized: string; tooltipNotAuthorized: string; tooltip_unlock: string; tooltipUnlock: string; } } export class LockButton extends Button implements Accessible, Actionable, Buildable, ConstraintTarget { static $gtype: GObject.GType<LockButton>; constructor( properties?: Partial<LockButton.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<LockButton.ConstructorProperties>, ...args: any[] ): void; // Properties permission: Gio.Permission; text_lock: string; textLock: string; text_unlock: string; textUnlock: string; tooltip_lock: string; tooltipLock: string; tooltip_not_authorized: string; tooltipNotAuthorized: string; tooltip_unlock: string; tooltipUnlock: string; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; action_name: string; actionName: string; action_target: GLib.Variant; actionTarget: GLib.Variant; // Constructors static ['new'](permission?: Gio.Permission | null): LockButton; static ['new'](...args: never[]): never; // Members get_permission(): Gio.Permission; set_permission(permission?: Gio.Permission | null): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_action_name(): string | null; get_action_target_value(): GLib.Variant | null; set_action_name(action_name?: string | null): void; set_action_target_value(target_value?: GLib.Variant | null): void; set_detailed_action_name(detailed_action_name: string): void; vfunc_get_action_name(): string | null; vfunc_get_action_target_value(): GLib.Variant | null; vfunc_set_action_name(action_name?: string | null): void; vfunc_set_action_target_value(target_value?: GLib.Variant | null): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace MapListModel { export interface ConstructorProperties< A extends GObject.Object = GObject.Object > extends GObject.Object.ConstructorProperties { [key: string]: any; has_map: boolean; hasMap: boolean; model: Gio.ListModel; } } export class MapListModel<A extends GObject.Object = GObject.Object> extends GObject.Object implements Gio.ListModel<A> { static $gtype: GObject.GType<MapListModel>; constructor( properties?: Partial<MapListModel.ConstructorProperties<A>>, ...args: any[] ); _init( properties?: Partial<MapListModel.ConstructorProperties<A>>, ...args: any[] ): void; // Properties has_map: boolean; hasMap: boolean; model: Gio.ListModel; // Constructors static ['new']( model?: Gio.ListModel | null, map_func?: MapListModelMapFunc | null ): MapListModel; // Members get_model(): Gio.ListModel | null; set_map_func(map_func?: MapListModelMapFunc | null): void; set_model(model?: Gio.ListModel | null): void; // Implemented Members get_item_type(): GObject.GType; get_n_items(): number; get_item(position: number): A | null; items_changed(position: number, removed: number, added: number): void; vfunc_get_item(position: number): A | null; vfunc_get_item_type(): GObject.GType; vfunc_get_n_items(): number; } export namespace MediaControls { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; media_stream: MediaStream; mediaStream: MediaStream; } } export class MediaControls extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<MediaControls>; constructor( properties?: Partial<MediaControls.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<MediaControls.ConstructorProperties>, ...args: any[] ): void; // Properties media_stream: MediaStream; mediaStream: MediaStream; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](stream?: MediaStream | null): MediaControls; // Members get_media_stream(): MediaStream | null; set_media_stream(stream?: MediaStream | null): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace MediaFile { export interface ConstructorProperties extends MediaStream.ConstructorProperties { [key: string]: any; file: Gio.File; input_stream: Gio.InputStream; inputStream: Gio.InputStream; } } export abstract class MediaFile extends MediaStream implements Gdk.Paintable { static $gtype: GObject.GType<MediaFile>; constructor( properties?: Partial<MediaFile.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<MediaFile.ConstructorProperties>, ...args: any[] ): void; // Properties file: Gio.File; input_stream: Gio.InputStream; inputStream: Gio.InputStream; // Constructors static ['new'](): MediaFile; static new_for_file(file: Gio.File): MediaFile; static new_for_filename(filename: string): MediaFile; static new_for_input_stream(stream: Gio.InputStream): MediaFile; static new_for_resource(resource_path: string): MediaFile; // Members clear(): void; get_file(): Gio.File | null; get_input_stream(): Gio.InputStream | null; set_file(file?: Gio.File | null): void; set_filename(filename?: string | null): void; set_input_stream(stream?: Gio.InputStream | null): void; set_resource(resource_path?: string | null): void; vfunc_close(): void; vfunc_open(): void; // Implemented Members compute_concrete_size( specified_width: number, specified_height: number, default_width: number, default_height: number ): [number, number]; get_current_image(): Gdk.Paintable; get_flags(): Gdk.PaintableFlags; get_intrinsic_aspect_ratio(): number; get_intrinsic_height(): number; get_intrinsic_width(): number; invalidate_contents(): void; invalidate_size(): void; snapshot(snapshot: Gdk.Snapshot, width: number, height: number): void; vfunc_get_current_image(): Gdk.Paintable; vfunc_get_flags(): Gdk.PaintableFlags; vfunc_get_intrinsic_aspect_ratio(): number; vfunc_get_intrinsic_height(): number; vfunc_get_intrinsic_width(): number; vfunc_snapshot(snapshot: Gdk.Snapshot, width: number, height: number): void; } export namespace MediaStream { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; duration: number; ended: boolean; error: GLib.Error; has_audio: boolean; hasAudio: boolean; has_video: boolean; hasVideo: boolean; loop: boolean; muted: boolean; playing: boolean; prepared: boolean; seekable: boolean; seeking: boolean; timestamp: number; volume: number; } } export abstract class MediaStream extends GObject.Object implements Gdk.Paintable { static $gtype: GObject.GType<MediaStream>; constructor( properties?: Partial<MediaStream.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<MediaStream.ConstructorProperties>, ...args: any[] ): void; // Properties duration: number; ended: boolean; error: GLib.Error; has_audio: boolean; hasAudio: boolean; has_video: boolean; hasVideo: boolean; loop: boolean; muted: boolean; playing: boolean; prepared: boolean; seekable: boolean; seeking: boolean; timestamp: number; volume: number; // Members gerror(error: GLib.Error): void; get_duration(): number; get_ended(): boolean; get_error(): GLib.Error | null; get_loop(): boolean; get_muted(): boolean; get_playing(): boolean; get_timestamp(): number; get_volume(): number; is_prepared(): boolean; is_seekable(): boolean; is_seeking(): boolean; pause(): void; play(): void; realize(surface: Gdk.Surface): void; seek(timestamp: number): void; seek_failed(): void; seek_success(): void; set_loop(loop: boolean): void; set_muted(muted: boolean): void; set_playing(playing: boolean): void; set_volume(volume: number): void; unprepared(): void; unrealize(surface: Gdk.Surface): void; update(timestamp: number): void; vfunc_pause(): void; vfunc_play(): boolean; vfunc_realize(surface: Gdk.Surface): void; vfunc_seek(timestamp: number): void; vfunc_unrealize(surface: Gdk.Surface): void; vfunc_update_audio(muted: boolean, volume: number): void; // Implemented Members compute_concrete_size( specified_width: number, specified_height: number, default_width: number, default_height: number ): [number, number]; get_current_image(): Gdk.Paintable; get_flags(): Gdk.PaintableFlags; get_intrinsic_aspect_ratio(): number; get_intrinsic_height(): number; get_intrinsic_width(): number; invalidate_contents(): void; invalidate_size(): void; snapshot(snapshot: Gdk.Snapshot, width: number, height: number): void; vfunc_get_current_image(): Gdk.Paintable; vfunc_get_flags(): Gdk.PaintableFlags; vfunc_get_intrinsic_aspect_ratio(): number; vfunc_get_intrinsic_height(): number; vfunc_get_intrinsic_width(): number; vfunc_snapshot(snapshot: Gdk.Snapshot, width: number, height: number): void; } export namespace MenuButton { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; direction: ArrowType; has_frame: boolean; hasFrame: boolean; icon_name: string; iconName: string; label: string; menu_model: Gio.MenuModel; menuModel: Gio.MenuModel; popover: Popover; use_underline: boolean; useUnderline: boolean; } } export class MenuButton extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<MenuButton>; constructor( properties?: Partial<MenuButton.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<MenuButton.ConstructorProperties>, ...args: any[] ): void; // Properties direction: ArrowType; has_frame: boolean; hasFrame: boolean; icon_name: string; iconName: string; label: string; menu_model: Gio.MenuModel; menuModel: Gio.MenuModel; popover: Popover; use_underline: boolean; useUnderline: boolean; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](): MenuButton; // Members get_direction(): ArrowType; get_direction(...args: never[]): never; get_has_frame(): boolean; get_icon_name(): string; get_label(): string; get_menu_model(): Gio.MenuModel | null; get_popover(): Popover | null; get_use_underline(): boolean; popdown(): void; popup(): void; set_create_popup_func( func?: MenuButtonCreatePopupFunc | null, destroy_notify?: GLib.DestroyNotify | null ): void; set_direction(direction: ArrowType): void; set_direction(...args: never[]): never; set_has_frame(has_frame: boolean): void; set_icon_name(icon_name: string): void; set_label(label: string): void; set_menu_model(menu_model?: Gio.MenuModel | null): void; set_popover(popover?: Widget | null): void; set_use_underline(use_underline: boolean): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace MessageDialog { export interface ConstructorProperties extends Dialog.ConstructorProperties { [key: string]: any; buttons: ButtonsType; message_area: Widget; messageArea: Widget; message_type: MessageType; messageType: MessageType; secondary_text: string; secondaryText: string; secondary_use_markup: boolean; secondaryUseMarkup: boolean; text: string; use_markup: boolean; useMarkup: boolean; } } export class MessageDialog extends Dialog implements Accessible, Buildable, ConstraintTarget, Native, Root, ShortcutManager { static $gtype: GObject.GType<MessageDialog>; constructor( properties?: Partial<MessageDialog.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<MessageDialog.ConstructorProperties>, ...args: any[] ): void; // Properties buttons: ButtonsType; message_area: Widget; messageArea: Widget; message_type: MessageType; messageType: MessageType; secondary_text: string; secondaryText: string; secondary_use_markup: boolean; secondaryUseMarkup: boolean; text: string; use_markup: boolean; useMarkup: boolean; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Members get_message_area(): Widget; set_markup(str: string): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_renderer(): Gsk.Renderer; get_surface(): Gdk.Surface; get_surface_transform(): [number, number]; realize(): void; unrealize(): void; get_display(): Gdk.Display; get_focus(): Widget | null; set_focus(focus?: Widget | null): void; vfunc_add_controller(controller: ShortcutController): void; vfunc_remove_controller(controller: ShortcutController): void; } export namespace MnemonicAction { export interface ConstructorProperties extends ShortcutAction.ConstructorProperties { [key: string]: any; } } export class MnemonicAction extends ShortcutAction { static $gtype: GObject.GType<MnemonicAction>; constructor( properties?: Partial<MnemonicAction.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<MnemonicAction.ConstructorProperties>, ...args: any[] ): void; // Members static get(): MnemonicAction; } export namespace MnemonicTrigger { export interface ConstructorProperties extends ShortcutTrigger.ConstructorProperties { [key: string]: any; keyval: number; } } export class MnemonicTrigger extends ShortcutTrigger { static $gtype: GObject.GType<MnemonicTrigger>; constructor( properties?: Partial<MnemonicTrigger.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<MnemonicTrigger.ConstructorProperties>, ...args: any[] ): void; // Properties keyval: number; // Constructors static ['new'](keyval: number): MnemonicTrigger; // Members get_keyval(): number; } export namespace MountOperation { export interface ConstructorProperties extends Gio.MountOperation.ConstructorProperties { [key: string]: any; display: Gdk.Display; is_showing: boolean; isShowing: boolean; } } export class MountOperation extends Gio.MountOperation { static $gtype: GObject.GType<MountOperation>; constructor( properties?: Partial<MountOperation.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<MountOperation.ConstructorProperties>, ...args: any[] ): void; // Properties display: Gdk.Display; is_showing: boolean; isShowing: boolean; // Fields priv: MountOperationPrivate | any; // Constructors static ['new'](parent?: Window | null): MountOperation; static ['new'](...args: never[]): never; // Members get_display(): Gdk.Display; get_parent(): Window; set_display(display: Gdk.Display): void; set_parent(parent?: Window | null): void; } export namespace MultiFilter { export interface ConstructorProperties< A extends GObject.Object = GObject.Object > extends Filter.ConstructorProperties { [key: string]: any; } } export abstract class MultiFilter<A extends GObject.Object = GObject.Object> extends Filter implements Gio.ListModel<A>, Buildable { static $gtype: GObject.GType<MultiFilter>; constructor( properties?: Partial<MultiFilter.ConstructorProperties<A>>, ...args: any[] ); _init( properties?: Partial<MultiFilter.ConstructorProperties<A>>, ...args: any[] ): void; // Members append(filter: Filter): void; remove(position: number): void; // Implemented Members get_item_type(): GObject.GType; get_n_items(): number; get_item(position: number): A | null; items_changed(position: number, removed: number, added: number): void; vfunc_get_item(position: number): A | null; vfunc_get_item_type(): GObject.GType; vfunc_get_n_items(): number; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace MultiSelection { export interface ConstructorProperties< A extends GObject.Object = GObject.Object > extends GObject.Object.ConstructorProperties { [key: string]: any; model: Gio.ListModel; } } export class MultiSelection<A extends GObject.Object = GObject.Object> extends GObject.Object implements Gio.ListModel<A>, SelectionModel<A> { static $gtype: GObject.GType<MultiSelection>; constructor( properties?: Partial<MultiSelection.ConstructorProperties<A>>, ...args: any[] ); _init( properties?: Partial<MultiSelection.ConstructorProperties<A>>, ...args: any[] ): void; // Properties model: Gio.ListModel; // Constructors static ['new'](model?: Gio.ListModel | null): MultiSelection; // Members get_model(): Gio.ListModel; set_model(model?: Gio.ListModel | null): void; // Implemented Members get_item_type(): GObject.GType; get_n_items(): number; get_item(position: number): A | null; items_changed(position: number, removed: number, added: number): void; vfunc_get_item(position: number): A | null; vfunc_get_item_type(): GObject.GType; vfunc_get_n_items(): number; get_selection(): Bitset; get_selection_in_range(position: number, n_items: number): Bitset; is_selected(position: number): boolean; select_all(): boolean; select_item(position: number, unselect_rest: boolean): boolean; select_range( position: number, n_items: number, unselect_rest: boolean ): boolean; selection_changed(position: number, n_items: number): void; set_selection(selected: Bitset, mask: Bitset): boolean; unselect_all(): boolean; unselect_item(position: number): boolean; unselect_range(position: number, n_items: number): boolean; vfunc_get_selection_in_range(position: number, n_items: number): Bitset; vfunc_is_selected(position: number): boolean; vfunc_select_all(): boolean; vfunc_select_item(position: number, unselect_rest: boolean): boolean; vfunc_select_range( position: number, n_items: number, unselect_rest: boolean ): boolean; vfunc_set_selection(selected: Bitset, mask: Bitset): boolean; vfunc_unselect_all(): boolean; vfunc_unselect_item(position: number): boolean; vfunc_unselect_range(position: number, n_items: number): boolean; } export namespace MultiSorter { export interface ConstructorProperties< A extends GObject.Object = GObject.Object > extends Sorter.ConstructorProperties { [key: string]: any; } } export class MultiSorter<A extends GObject.Object = GObject.Object> extends Sorter implements Gio.ListModel<A>, Buildable { static $gtype: GObject.GType<MultiSorter>; constructor( properties?: Partial<MultiSorter.ConstructorProperties<A>>, ...args: any[] ); _init( properties?: Partial<MultiSorter.ConstructorProperties<A>>, ...args: any[] ): void; // Constructors static ['new'](): MultiSorter; // Members append(sorter: Sorter): void; remove(position: number): void; // Implemented Members get_item_type(): GObject.GType; get_n_items(): number; get_item(position: number): A | null; items_changed(position: number, removed: number, added: number): void; vfunc_get_item(position: number): A | null; vfunc_get_item_type(): GObject.GType; vfunc_get_n_items(): number; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace NamedAction { export interface ConstructorProperties extends ShortcutAction.ConstructorProperties { [key: string]: any; action_name: string; actionName: string; } } export class NamedAction extends ShortcutAction { static $gtype: GObject.GType<NamedAction>; constructor( properties?: Partial<NamedAction.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<NamedAction.ConstructorProperties>, ...args: any[] ): void; // Properties action_name: string; actionName: string; // Constructors static ['new'](name: string): NamedAction; // Members get_action_name(): string; } export namespace NativeDialog { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; modal: boolean; title: string; transient_for: Window; transientFor: Window; visible: boolean; } } export abstract class NativeDialog extends GObject.Object { static $gtype: GObject.GType<NativeDialog>; constructor( properties?: Partial<NativeDialog.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<NativeDialog.ConstructorProperties>, ...args: any[] ): void; // Properties modal: boolean; title: string; transient_for: Window; transientFor: Window; visible: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'response', callback: (_source: this, response_id: number) => void ): number; connect_after( signal: 'response', callback: (_source: this, response_id: number) => void ): number; emit(signal: 'response', response_id: number): void; // Members destroy(): void; get_modal(): boolean; get_title(): string | null; get_transient_for(): Window | null; get_visible(): boolean; hide(): void; set_modal(modal: boolean): void; set_title(title: string): void; set_transient_for(parent?: Window | null): void; show(): void; vfunc_hide(): void; vfunc_response(response_id: number): void; vfunc_show(): void; } export namespace NeverTrigger { export interface ConstructorProperties extends ShortcutTrigger.ConstructorProperties { [key: string]: any; } } export class NeverTrigger extends ShortcutTrigger { static $gtype: GObject.GType<NeverTrigger>; constructor( properties?: Partial<NeverTrigger.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<NeverTrigger.ConstructorProperties>, ...args: any[] ): void; // Members static get(): NeverTrigger; } export namespace NoSelection { export interface ConstructorProperties< A extends GObject.Object = GObject.Object > extends GObject.Object.ConstructorProperties { [key: string]: any; model: Gio.ListModel; } } export class NoSelection<A extends GObject.Object = GObject.Object> extends GObject.Object implements Gio.ListModel<A>, SelectionModel<A> { static $gtype: GObject.GType<NoSelection>; constructor( properties?: Partial<NoSelection.ConstructorProperties<A>>, ...args: any[] ); _init( properties?: Partial<NoSelection.ConstructorProperties<A>>, ...args: any[] ): void; // Properties model: Gio.ListModel; // Constructors static ['new'](model?: Gio.ListModel | null): NoSelection; // Members get_model(): Gio.ListModel; set_model(model?: Gio.ListModel | null): void; // Implemented Members get_item_type(): GObject.GType; get_n_items(): number; get_item(position: number): A | null; items_changed(position: number, removed: number, added: number): void; vfunc_get_item(position: number): A | null; vfunc_get_item_type(): GObject.GType; vfunc_get_n_items(): number; get_selection(): Bitset; get_selection_in_range(position: number, n_items: number): Bitset; is_selected(position: number): boolean; select_all(): boolean; select_item(position: number, unselect_rest: boolean): boolean; select_range( position: number, n_items: number, unselect_rest: boolean ): boolean; selection_changed(position: number, n_items: number): void; set_selection(selected: Bitset, mask: Bitset): boolean; unselect_all(): boolean; unselect_item(position: number): boolean; unselect_range(position: number, n_items: number): boolean; vfunc_get_selection_in_range(position: number, n_items: number): Bitset; vfunc_is_selected(position: number): boolean; vfunc_select_all(): boolean; vfunc_select_item(position: number, unselect_rest: boolean): boolean; vfunc_select_range( position: number, n_items: number, unselect_rest: boolean ): boolean; vfunc_set_selection(selected: Bitset, mask: Bitset): boolean; vfunc_unselect_all(): boolean; vfunc_unselect_item(position: number): boolean; vfunc_unselect_range(position: number, n_items: number): boolean; } export namespace Notebook { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; enable_popup: boolean; enablePopup: boolean; group_name: string; groupName: string; page: number; pages: Gio.ListModel; scrollable: boolean; show_border: boolean; showBorder: boolean; show_tabs: boolean; showTabs: boolean; tab_pos: PositionType; tabPos: PositionType; } } export class Notebook extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<Notebook>; constructor( properties?: Partial<Notebook.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Notebook.ConstructorProperties>, ...args: any[] ): void; // Properties enable_popup: boolean; enablePopup: boolean; group_name: string; groupName: string; page: number; pages: Gio.ListModel; scrollable: boolean; show_border: boolean; showBorder: boolean; show_tabs: boolean; showTabs: boolean; tab_pos: PositionType; tabPos: PositionType; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'change-current-page', callback: (_source: this, object: number) => boolean ): number; connect_after( signal: 'change-current-page', callback: (_source: this, object: number) => boolean ): number; emit(signal: 'change-current-page', object: number): void; connect( signal: 'create-window', callback: (_source: this, page: Widget) => Notebook ): number; connect_after( signal: 'create-window', callback: (_source: this, page: Widget) => Notebook ): number; emit(signal: 'create-window', page: Widget): void; connect( signal: 'focus-tab', callback: (_source: this, object: NotebookTab) => boolean ): number; connect_after( signal: 'focus-tab', callback: (_source: this, object: NotebookTab) => boolean ): number; emit(signal: 'focus-tab', object: NotebookTab): void; connect( signal: 'move-focus-out', callback: (_source: this, object: DirectionType) => void ): number; connect_after( signal: 'move-focus-out', callback: (_source: this, object: DirectionType) => void ): number; emit(signal: 'move-focus-out', object: DirectionType): void; connect( signal: 'page-added', callback: (_source: this, child: Widget, page_num: number) => void ): number; connect_after( signal: 'page-added', callback: (_source: this, child: Widget, page_num: number) => void ): number; emit(signal: 'page-added', child: Widget, page_num: number): void; connect( signal: 'page-removed', callback: (_source: this, child: Widget, page_num: number) => void ): number; connect_after( signal: 'page-removed', callback: (_source: this, child: Widget, page_num: number) => void ): number; emit(signal: 'page-removed', child: Widget, page_num: number): void; connect( signal: 'page-reordered', callback: (_source: this, child: Widget, page_num: number) => void ): number; connect_after( signal: 'page-reordered', callback: (_source: this, child: Widget, page_num: number) => void ): number; emit(signal: 'page-reordered', child: Widget, page_num: number): void; connect( signal: 'reorder-tab', callback: (_source: this, object: DirectionType, p0: boolean) => boolean ): number; connect_after( signal: 'reorder-tab', callback: (_source: this, object: DirectionType, p0: boolean) => boolean ): number; emit(signal: 'reorder-tab', object: DirectionType, p0: boolean): void; connect( signal: 'select-page', callback: (_source: this, object: boolean) => boolean ): number; connect_after( signal: 'select-page', callback: (_source: this, object: boolean) => boolean ): number; emit(signal: 'select-page', object: boolean): void; connect( signal: 'switch-page', callback: (_source: this, page: Widget, page_num: number) => void ): number; connect_after( signal: 'switch-page', callback: (_source: this, page: Widget, page_num: number) => void ): number; emit(signal: 'switch-page', page: Widget, page_num: number): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](): Notebook; // Members append_page(child: Widget, tab_label?: Widget | null): number; append_page_menu( child: Widget, tab_label?: Widget | null, menu_label?: Widget | null ): number; detach_tab(child: Widget): void; get_action_widget(pack_type: PackType): Widget | null; get_current_page(): number; get_group_name(): string | null; get_menu_label(child: Widget): Widget | null; get_menu_label_text(child: Widget): string | null; get_n_pages(): number; get_nth_page(page_num: number): Widget | null; get_page(child: Widget): NotebookPage; get_pages(): Gio.ListModel; get_scrollable(): boolean; get_show_border(): boolean; get_show_tabs(): boolean; get_tab_detachable(child: Widget): boolean; get_tab_label(child: Widget): Widget | null; get_tab_label_text(child: Widget): string | null; get_tab_pos(): PositionType; get_tab_reorderable(child: Widget): boolean; insert_page( child: Widget, tab_label: Widget | null, position: number ): number; insert_page_menu( child: Widget, tab_label: Widget | null, menu_label: Widget | null, position: number ): number; next_page(): void; page_num(child: Widget): number; popup_disable(): void; popup_enable(): void; prepend_page(child: Widget, tab_label?: Widget | null): number; prepend_page_menu( child: Widget, tab_label?: Widget | null, menu_label?: Widget | null ): number; prev_page(): void; remove_page(page_num: number): void; reorder_child(child: Widget, position: number): void; set_action_widget(widget: Widget, pack_type: PackType): void; set_current_page(page_num: number): void; set_group_name(group_name?: string | null): void; set_menu_label(child: Widget, menu_label?: Widget | null): void; set_menu_label_text(child: Widget, menu_text: string): void; set_scrollable(scrollable: boolean): void; set_show_border(show_border: boolean): void; set_show_tabs(show_tabs: boolean): void; set_tab_detachable(child: Widget, detachable: boolean): void; set_tab_label(child: Widget, tab_label?: Widget | null): void; set_tab_label_text(child: Widget, tab_text: string): void; set_tab_pos(pos: PositionType): void; set_tab_reorderable(child: Widget, reorderable: boolean): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace NotebookPage { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; child: Widget; detachable: boolean; menu: Widget; menu_label: string; menuLabel: string; position: number; reorderable: boolean; tab: Widget; tab_expand: boolean; tabExpand: boolean; tab_fill: boolean; tabFill: boolean; tab_label: string; tabLabel: string; } } export class NotebookPage extends GObject.Object { static $gtype: GObject.GType<NotebookPage>; constructor( properties?: Partial<NotebookPage.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<NotebookPage.ConstructorProperties>, ...args: any[] ): void; // Properties child: Widget; detachable: boolean; menu: Widget; menu_label: string; menuLabel: string; position: number; reorderable: boolean; tab: Widget; tab_expand: boolean; tabExpand: boolean; tab_fill: boolean; tabFill: boolean; tab_label: string; tabLabel: string; // Members get_child(): Widget; } export namespace NothingAction { export interface ConstructorProperties extends ShortcutAction.ConstructorProperties { [key: string]: any; } } export class NothingAction extends ShortcutAction { static $gtype: GObject.GType<NothingAction>; constructor( properties?: Partial<NothingAction.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<NothingAction.ConstructorProperties>, ...args: any[] ): void; // Members static get(): NothingAction; } export namespace NumericSorter { export interface ConstructorProperties extends Sorter.ConstructorProperties { [key: string]: any; expression: Expression; sort_order: SortType; sortOrder: SortType; } } export class NumericSorter extends Sorter { static $gtype: GObject.GType<NumericSorter>; constructor( properties?: Partial<NumericSorter.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<NumericSorter.ConstructorProperties>, ...args: any[] ): void; // Properties expression: Expression; sort_order: SortType; sortOrder: SortType; // Constructors static ['new'](expression?: Expression | null): NumericSorter; // Members get_expression(): Expression | null; get_sort_order(): SortType; set_expression(expression?: Expression | null): void; set_sort_order(sort_order: SortType): void; } export namespace ObjectExpression { export interface ConstructorProperties extends Expression.ConstructorProperties { [key: string]: any; } } export class ObjectExpression extends Expression { static $gtype: GObject.GType<ObjectExpression>; constructor( properties?: Partial<ObjectExpression.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ObjectExpression.ConstructorProperties>, ...args: any[] ): void; // Constructors static ['new'](object: GObject.Object): ObjectExpression; // Members get_object<T = GObject.Object>(): T; } export namespace Overlay { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; child: Widget; } } export class Overlay extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<Overlay>; constructor( properties?: Partial<Overlay.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Overlay.ConstructorProperties>, ...args: any[] ): void; // Properties child: Widget; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'get-child-position', callback: ( _source: this, widget: Widget, allocation: Gdk.Rectangle ) => boolean ): number; connect_after( signal: 'get-child-position', callback: ( _source: this, widget: Widget, allocation: Gdk.Rectangle ) => boolean ): number; emit( signal: 'get-child-position', widget: Widget, allocation: Gdk.Rectangle ): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](): Overlay; // Members add_overlay(widget: Widget): void; get_child(): Widget | null; get_clip_overlay(widget: Widget): boolean; get_measure_overlay(widget: Widget): boolean; remove_overlay(widget: Widget): void; set_child(child?: Widget | null): void; set_clip_overlay(widget: Widget, clip_overlay: boolean): void; set_measure_overlay(widget: Widget, measure: boolean): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace OverlayLayout { export interface ConstructorProperties extends LayoutManager.ConstructorProperties { [key: string]: any; } } export class OverlayLayout extends LayoutManager { static $gtype: GObject.GType<OverlayLayout>; constructor( properties?: Partial<OverlayLayout.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<OverlayLayout.ConstructorProperties>, ...args: any[] ): void; // Constructors static ['new'](): OverlayLayout; } export namespace OverlayLayoutChild { export interface ConstructorProperties extends LayoutChild.ConstructorProperties { [key: string]: any; clip_overlay: boolean; clipOverlay: boolean; measure: boolean; } } export class OverlayLayoutChild extends LayoutChild { static $gtype: GObject.GType<OverlayLayoutChild>; constructor( properties?: Partial<OverlayLayoutChild.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<OverlayLayoutChild.ConstructorProperties>, ...args: any[] ): void; // Properties clip_overlay: boolean; clipOverlay: boolean; measure: boolean; // Members get_clip_overlay(): boolean; get_measure(): boolean; set_clip_overlay(clip_overlay: boolean): void; set_measure(measure: boolean): void; } export namespace PadController { export interface ConstructorProperties extends EventController.ConstructorProperties { [key: string]: any; action_group: Gio.ActionGroup; actionGroup: Gio.ActionGroup; pad: Gdk.Device; } } export class PadController extends EventController { static $gtype: GObject.GType<PadController>; constructor( properties?: Partial<PadController.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<PadController.ConstructorProperties>, ...args: any[] ): void; // Properties action_group: Gio.ActionGroup; actionGroup: Gio.ActionGroup; pad: Gdk.Device; // Constructors static ['new']( group: Gio.ActionGroup, pad?: Gdk.Device | null ): PadController; // Members set_action( type: PadActionType, index: number, mode: number, label: string, action_name: string ): void; set_action_entries(entries: PadActionEntry[]): void; } export namespace PageSetup { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class PageSetup extends GObject.Object { static $gtype: GObject.GType<PageSetup>; constructor( properties?: Partial<PageSetup.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<PageSetup.ConstructorProperties>, ...args: any[] ): void; // Constructors static ['new'](): PageSetup; static new_from_file(file_name: string): PageSetup; static new_from_gvariant(variant: GLib.Variant): PageSetup; static new_from_key_file( key_file: GLib.KeyFile, group_name?: string | null ): PageSetup; // Members copy(): PageSetup; get_bottom_margin(unit: Unit): number; get_left_margin(unit: Unit): number; get_orientation(): PageOrientation; get_page_height(unit: Unit): number; get_page_width(unit: Unit): number; get_paper_height(unit: Unit): number; get_paper_size(): PaperSize; get_paper_width(unit: Unit): number; get_right_margin(unit: Unit): number; get_top_margin(unit: Unit): number; load_file(file_name: string): boolean; load_key_file(key_file: GLib.KeyFile, group_name?: string | null): boolean; set_bottom_margin(margin: number, unit: Unit): void; set_left_margin(margin: number, unit: Unit): void; set_orientation(orientation: PageOrientation): void; set_paper_size(size: PaperSize): void; set_paper_size_and_default_margins(size: PaperSize): void; set_right_margin(margin: number, unit: Unit): void; set_top_margin(margin: number, unit: Unit): void; to_file(file_name: string): boolean; to_gvariant(): GLib.Variant; to_key_file(key_file: GLib.KeyFile, group_name?: string | null): void; } export namespace Paned { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; end_child: Widget; endChild: Widget; max_position: number; maxPosition: number; min_position: number; minPosition: number; position: number; position_set: boolean; positionSet: boolean; resize_end_child: boolean; resizeEndChild: boolean; resize_start_child: boolean; resizeStartChild: boolean; shrink_end_child: boolean; shrinkEndChild: boolean; shrink_start_child: boolean; shrinkStartChild: boolean; start_child: Widget; startChild: Widget; wide_handle: boolean; wideHandle: boolean; } } export class Paned extends Widget implements Accessible, Buildable, ConstraintTarget, Orientable { static $gtype: GObject.GType<Paned>; constructor( properties?: Partial<Paned.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Paned.ConstructorProperties>, ...args: any[] ): void; // Properties end_child: Widget; endChild: Widget; max_position: number; maxPosition: number; min_position: number; minPosition: number; position: number; position_set: boolean; positionSet: boolean; resize_end_child: boolean; resizeEndChild: boolean; resize_start_child: boolean; resizeStartChild: boolean; shrink_end_child: boolean; shrinkEndChild: boolean; shrink_start_child: boolean; shrinkStartChild: boolean; start_child: Widget; startChild: Widget; wide_handle: boolean; wideHandle: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'accept-position', callback: (_source: this) => boolean ): number; connect_after( signal: 'accept-position', callback: (_source: this) => boolean ): number; emit(signal: 'accept-position'): void; connect( signal: 'cancel-position', callback: (_source: this) => boolean ): number; connect_after( signal: 'cancel-position', callback: (_source: this) => boolean ): number; emit(signal: 'cancel-position'): void; connect( signal: 'cycle-child-focus', callback: (_source: this, reversed: boolean) => boolean ): number; connect_after( signal: 'cycle-child-focus', callback: (_source: this, reversed: boolean) => boolean ): number; emit(signal: 'cycle-child-focus', reversed: boolean): void; connect( signal: 'cycle-handle-focus', callback: (_source: this, reversed: boolean) => boolean ): number; connect_after( signal: 'cycle-handle-focus', callback: (_source: this, reversed: boolean) => boolean ): number; emit(signal: 'cycle-handle-focus', reversed: boolean): void; connect( signal: 'move-handle', callback: (_source: this, scroll_type: ScrollType) => boolean ): number; connect_after( signal: 'move-handle', callback: (_source: this, scroll_type: ScrollType) => boolean ): number; emit(signal: 'move-handle', scroll_type: ScrollType): void; connect( signal: 'toggle-handle-focus', callback: (_source: this) => boolean ): number; connect_after( signal: 'toggle-handle-focus', callback: (_source: this) => boolean ): number; emit(signal: 'toggle-handle-focus'): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; orientation: Orientation; // Constructors static ['new'](orientation: Orientation): Paned; // Members get_end_child(): Widget | null; get_position(): number; get_resize_end_child(): boolean; get_resize_start_child(): boolean; get_shrink_end_child(): boolean; get_shrink_start_child(): boolean; get_start_child(): Widget | null; get_wide_handle(): boolean; set_end_child(child: Widget): void; set_position(position: number): void; set_resize_end_child(resize: boolean): void; set_resize_start_child(resize: boolean): void; set_shrink_end_child(resize: boolean): void; set_shrink_start_child(resize: boolean): void; set_start_child(child: Widget): void; set_wide_handle(wide: boolean): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_orientation(): Orientation; set_orientation(orientation: Orientation): void; } export namespace ParamSpecExpression { export interface ConstructorProperties extends GObject.ParamSpec.ConstructorProperties { [key: string]: any; } } export class ParamSpecExpression extends GObject.ParamSpec { static $gtype: GObject.GType<ParamSpecExpression>; constructor( properties?: Partial<ParamSpecExpression.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ParamSpecExpression.ConstructorProperties>, ...args: any[] ): void; } export namespace PasswordEntry { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; activates_default: boolean; activatesDefault: boolean; extra_menu: Gio.MenuModel; extraMenu: Gio.MenuModel; placeholder_text: string; placeholderText: string; show_peek_icon: boolean; showPeekIcon: boolean; } } export class PasswordEntry extends Widget implements Accessible, Buildable, ConstraintTarget, Editable { static $gtype: GObject.GType<PasswordEntry>; constructor( properties?: Partial<PasswordEntry.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<PasswordEntry.ConstructorProperties>, ...args: any[] ): void; // Properties activates_default: boolean; activatesDefault: boolean; extra_menu: Gio.MenuModel; extraMenu: Gio.MenuModel; placeholder_text: string; placeholderText: string; show_peek_icon: boolean; showPeekIcon: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'activate', callback: (_source: this) => void): number; connect_after( signal: 'activate', callback: (_source: this) => void ): number; emit(signal: 'activate'): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; cursor_position: number; cursorPosition: number; editable: boolean; enable_undo: boolean; enableUndo: boolean; max_width_chars: number; maxWidthChars: number; selection_bound: number; selectionBound: number; text: string; width_chars: number; widthChars: number; xalign: number; // Constructors static ['new'](): PasswordEntry; // Members get_extra_menu(): Gio.MenuModel; get_show_peek_icon(): boolean; set_extra_menu(model?: Gio.MenuModel | null): void; set_show_peek_icon(show_peek_icon: boolean): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; delete_selection(): void; delete_text(start_pos: number, end_pos: number): void; finish_delegate(): void; get_alignment(): number; get_chars(start_pos: number, end_pos: number): string; get_delegate(): Editable | null; get_editable(): boolean; get_enable_undo(): boolean; get_max_width_chars(): number; get_position(): number; get_selection_bounds(): [boolean, number | null, number | null]; get_text(): string; get_width_chars(): number; init_delegate(): void; insert_text(text: string, length: number, position: number): number; select_region(start_pos: number, end_pos: number): void; set_alignment(xalign: number): void; set_editable(is_editable: boolean): void; set_enable_undo(enable_undo: boolean): void; set_max_width_chars(n_chars: number): void; set_position(position: number): void; set_text(text: string): void; set_width_chars(n_chars: number): void; vfunc_changed(): void; vfunc_delete_text(start_pos: number, end_pos: number): void; vfunc_do_delete_text(start_pos: number, end_pos: number): void; vfunc_do_insert_text( text: string, length: number, position: number ): number; vfunc_get_delegate(): Editable | null; vfunc_get_selection_bounds(): [boolean, number | null, number | null]; vfunc_get_text(): string; vfunc_insert_text(text: string, length: number, position: number): number; vfunc_set_selection_bounds(start_pos: number, end_pos: number): void; } export namespace Picture { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; alternative_text: string; alternativeText: string; can_shrink: boolean; canShrink: boolean; file: Gio.File; keep_aspect_ratio: boolean; keepAspectRatio: boolean; paintable: Gdk.Paintable; } } export class Picture extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<Picture>; constructor( properties?: Partial<Picture.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Picture.ConstructorProperties>, ...args: any[] ): void; // Properties alternative_text: string; alternativeText: string; can_shrink: boolean; canShrink: boolean; file: Gio.File; keep_aspect_ratio: boolean; keepAspectRatio: boolean; paintable: Gdk.Paintable; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](): Picture; static new_for_file(file?: Gio.File | null): Picture; static new_for_filename(filename?: string | null): Picture; static new_for_paintable(paintable?: Gdk.Paintable | null): Picture; static new_for_pixbuf(pixbuf?: GdkPixbuf.Pixbuf | null): Picture; static new_for_resource(resource_path?: string | null): Picture; // Members get_alternative_text(): string | null; get_can_shrink(): boolean; get_file(): Gio.File | null; get_keep_aspect_ratio(): boolean; get_paintable(): Gdk.Paintable | null; set_alternative_text(alternative_text?: string | null): void; set_can_shrink(can_shrink: boolean): void; set_file(file?: Gio.File | null): void; set_filename(filename?: string | null): void; set_keep_aspect_ratio(keep_aspect_ratio: boolean): void; set_paintable(paintable?: Gdk.Paintable | null): void; set_pixbuf(pixbuf?: GdkPixbuf.Pixbuf | null): void; set_resource(resource_path?: string | null): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace Popover { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; autohide: boolean; cascade_popdown: boolean; cascadePopdown: boolean; child: Widget; default_widget: Widget; defaultWidget: Widget; has_arrow: boolean; hasArrow: boolean; mnemonics_visible: boolean; mnemonicsVisible: boolean; pointing_to: Gdk.Rectangle; pointingTo: Gdk.Rectangle; position: PositionType; } } export class Popover extends Widget implements Accessible, Buildable, ConstraintTarget, Native, ShortcutManager { static $gtype: GObject.GType<Popover>; constructor( properties?: Partial<Popover.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Popover.ConstructorProperties>, ...args: any[] ): void; // Properties autohide: boolean; cascade_popdown: boolean; cascadePopdown: boolean; child: Widget; default_widget: Widget; defaultWidget: Widget; has_arrow: boolean; hasArrow: boolean; mnemonics_visible: boolean; mnemonicsVisible: boolean; pointing_to: Gdk.Rectangle; pointingTo: Gdk.Rectangle; position: PositionType; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'activate-default', callback: (_source: this) => void ): number; connect_after( signal: 'activate-default', callback: (_source: this) => void ): number; emit(signal: 'activate-default'): void; connect(signal: 'closed', callback: (_source: this) => void): number; connect_after(signal: 'closed', callback: (_source: this) => void): number; emit(signal: 'closed'): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](): Popover; // Members get_autohide(): boolean; get_cascade_popdown(): boolean; get_child(): Widget | null; get_has_arrow(): boolean; get_mnemonics_visible(): boolean; get_offset(): [number | null, number | null]; get_pointing_to(): [boolean, Gdk.Rectangle]; get_position(): PositionType; popdown(): void; popup(): void; present(): void; set_autohide(autohide: boolean): void; set_cascade_popdown(cascade_popdown: boolean): void; set_child(child?: Widget | null): void; set_default_widget(widget?: Widget | null): void; set_has_arrow(has_arrow: boolean): void; set_mnemonics_visible(mnemonics_visible: boolean): void; set_offset(x_offset: number, y_offset: number): void; set_pointing_to(rect: Gdk.Rectangle): void; set_position(position: PositionType): void; vfunc_activate_default(): void; vfunc_closed(): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_renderer(): Gsk.Renderer; get_surface(): Gdk.Surface; get_surface_transform(): [number, number]; realize(): void; unrealize(): void; vfunc_add_controller(controller: ShortcutController): void; vfunc_remove_controller(controller: ShortcutController): void; } export namespace PopoverMenu { export interface ConstructorProperties extends Popover.ConstructorProperties { [key: string]: any; menu_model: Gio.MenuModel; menuModel: Gio.MenuModel; visible_submenu: string; visibleSubmenu: string; } } export class PopoverMenu extends Popover implements Accessible, Buildable, ConstraintTarget, Native, ShortcutManager { static $gtype: GObject.GType<PopoverMenu>; constructor( properties?: Partial<PopoverMenu.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<PopoverMenu.ConstructorProperties>, ...args: any[] ): void; // Properties menu_model: Gio.MenuModel; menuModel: Gio.MenuModel; visible_submenu: string; visibleSubmenu: string; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static new_from_model(model?: Gio.MenuModel | null): PopoverMenu; static new_from_model_full( model: Gio.MenuModel, flags: PopoverMenuFlags ): PopoverMenu; // Members add_child(child: Widget, id: string): boolean; get_menu_model(): Gio.MenuModel; remove_child(child: Widget): boolean; set_menu_model(model?: Gio.MenuModel | null): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_renderer(): Gsk.Renderer; get_surface(): Gdk.Surface; get_surface_transform(): [number, number]; realize(): void; unrealize(): void; vfunc_add_controller(controller: ShortcutController): void; vfunc_remove_controller(controller: ShortcutController): void; } export namespace PopoverMenuBar { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; menu_model: Gio.MenuModel; menuModel: Gio.MenuModel; } } export class PopoverMenuBar extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<PopoverMenuBar>; constructor( properties?: Partial<PopoverMenuBar.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<PopoverMenuBar.ConstructorProperties>, ...args: any[] ): void; // Properties menu_model: Gio.MenuModel; menuModel: Gio.MenuModel; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static new_from_model(model?: Gio.MenuModel | null): PopoverMenuBar; // Members add_child(child: Widget, id: string): boolean; get_menu_model(): Gio.MenuModel; remove_child(child: Widget): boolean; set_menu_model(model?: Gio.MenuModel | null): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace PrintContext { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class PrintContext extends GObject.Object { static $gtype: GObject.GType<PrintContext>; constructor( properties?: Partial<PrintContext.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<PrintContext.ConstructorProperties>, ...args: any[] ): void; // Members create_pango_context(): Pango.Context; create_pango_layout(): Pango.Layout; get_cairo_context(): cairo.Context; get_dpi_x(): number; get_dpi_y(): number; get_hard_margins(): [boolean, number, number, number, number]; get_height(): number; get_page_setup(): PageSetup; get_pango_fontmap(): Pango.FontMap; get_width(): number; set_cairo_context(cr: cairo.Context, dpi_x: number, dpi_y: number): void; } export namespace PrintOperation { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; allow_async: boolean; allowAsync: boolean; current_page: number; currentPage: number; custom_tab_label: string; customTabLabel: string; default_page_setup: PageSetup; defaultPageSetup: PageSetup; embed_page_setup: boolean; embedPageSetup: boolean; export_filename: string; exportFilename: string; has_selection: boolean; hasSelection: boolean; job_name: string; jobName: string; n_pages: number; nPages: number; n_pages_to_print: number; nPagesToPrint: number; print_settings: PrintSettings; printSettings: PrintSettings; show_progress: boolean; showProgress: boolean; status: PrintStatus; status_string: string; statusString: string; support_selection: boolean; supportSelection: boolean; track_print_status: boolean; trackPrintStatus: boolean; unit: Unit; use_full_page: boolean; useFullPage: boolean; } } export class PrintOperation extends GObject.Object implements PrintOperationPreview { static $gtype: GObject.GType<PrintOperation>; constructor( properties?: Partial<PrintOperation.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<PrintOperation.ConstructorProperties>, ...args: any[] ): void; // Properties allow_async: boolean; allowAsync: boolean; current_page: number; currentPage: number; custom_tab_label: string; customTabLabel: string; default_page_setup: PageSetup; defaultPageSetup: PageSetup; embed_page_setup: boolean; embedPageSetup: boolean; export_filename: string; exportFilename: string; has_selection: boolean; hasSelection: boolean; job_name: string; jobName: string; n_pages: number; nPages: number; n_pages_to_print: number; nPagesToPrint: number; print_settings: PrintSettings; printSettings: PrintSettings; show_progress: boolean; showProgress: boolean; status: PrintStatus; status_string: string; statusString: string; support_selection: boolean; supportSelection: boolean; track_print_status: boolean; trackPrintStatus: boolean; unit: Unit; use_full_page: boolean; useFullPage: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'begin-print', callback: (_source: this, context: PrintContext) => void ): number; connect_after( signal: 'begin-print', callback: (_source: this, context: PrintContext) => void ): number; emit(signal: 'begin-print', context: PrintContext): void; connect( signal: 'create-custom-widget', callback: (_source: this) => GObject.Object ): number; connect_after( signal: 'create-custom-widget', callback: (_source: this) => GObject.Object ): number; emit(signal: 'create-custom-widget'): void; connect( signal: 'custom-widget-apply', callback: (_source: this, widget: Widget) => void ): number; connect_after( signal: 'custom-widget-apply', callback: (_source: this, widget: Widget) => void ): number; emit(signal: 'custom-widget-apply', widget: Widget): void; connect( signal: 'done', callback: (_source: this, result: PrintOperationResult) => void ): number; connect_after( signal: 'done', callback: (_source: this, result: PrintOperationResult) => void ): number; emit(signal: 'done', result: PrintOperationResult): void; connect( signal: 'draw-page', callback: ( _source: this, context: PrintContext, page_nr: number ) => void ): number; connect_after( signal: 'draw-page', callback: ( _source: this, context: PrintContext, page_nr: number ) => void ): number; emit(signal: 'draw-page', context: PrintContext, page_nr: number): void; connect( signal: 'end-print', callback: (_source: this, context: PrintContext) => void ): number; connect_after( signal: 'end-print', callback: (_source: this, context: PrintContext) => void ): number; emit(signal: 'end-print', context: PrintContext): void; connect( signal: 'paginate', callback: (_source: this, context: PrintContext) => boolean ): number; connect_after( signal: 'paginate', callback: (_source: this, context: PrintContext) => boolean ): number; emit(signal: 'paginate', context: PrintContext): void; connect( signal: 'preview', callback: ( _source: this, preview: PrintOperationPreview, context: PrintContext, parent: Window | null ) => boolean ): number; connect_after( signal: 'preview', callback: ( _source: this, preview: PrintOperationPreview, context: PrintContext, parent: Window | null ) => boolean ): number; emit( signal: 'preview', preview: PrintOperationPreview, context: PrintContext, parent: Window | null ): void; connect( signal: 'request-page-setup', callback: ( _source: this, context: PrintContext, page_nr: number, setup: PageSetup ) => void ): number; connect_after( signal: 'request-page-setup', callback: ( _source: this, context: PrintContext, page_nr: number, setup: PageSetup ) => void ): number; emit( signal: 'request-page-setup', context: PrintContext, page_nr: number, setup: PageSetup ): void; connect( signal: 'status-changed', callback: (_source: this) => void ): number; connect_after( signal: 'status-changed', callback: (_source: this) => void ): number; emit(signal: 'status-changed'): void; connect( signal: 'update-custom-widget', callback: ( _source: this, widget: Widget, setup: PageSetup, settings: PrintSettings ) => void ): number; connect_after( signal: 'update-custom-widget', callback: ( _source: this, widget: Widget, setup: PageSetup, settings: PrintSettings ) => void ): number; emit( signal: 'update-custom-widget', widget: Widget, setup: PageSetup, settings: PrintSettings ): void; // Constructors static ['new'](): PrintOperation; // Members cancel(): void; draw_page_finish(): void; get_default_page_setup(): PageSetup; get_embed_page_setup(): boolean; get_error(): void; get_has_selection(): boolean; get_n_pages_to_print(): number; get_print_settings(): PrintSettings; get_status(): PrintStatus; get_status_string(): string; get_support_selection(): boolean; is_finished(): boolean; run( action: PrintOperationAction, parent?: Window | null ): PrintOperationResult; set_allow_async(allow_async: boolean): void; set_current_page(current_page: number): void; set_custom_tab_label(label?: string | null): void; set_default_page_setup(default_page_setup?: PageSetup | null): void; set_defer_drawing(): void; set_embed_page_setup(embed: boolean): void; set_export_filename(filename: string): void; set_has_selection(has_selection: boolean): void; set_job_name(job_name: string): void; set_n_pages(n_pages: number): void; set_print_settings(print_settings?: PrintSettings | null): void; set_show_progress(show_progress: boolean): void; set_support_selection(support_selection: boolean): void; set_track_print_status(track_status: boolean): void; set_unit(unit: Unit): void; set_use_full_page(full_page: boolean): void; vfunc_begin_print(context: PrintContext): void; vfunc_custom_widget_apply(widget: Widget): void; vfunc_done(result: PrintOperationResult): void; vfunc_draw_page(context: PrintContext, page_nr: number): void; vfunc_end_print(context: PrintContext): void; vfunc_paginate(context: PrintContext): boolean; vfunc_preview( preview: PrintOperationPreview, context: PrintContext, parent: Window ): boolean; vfunc_request_page_setup( context: PrintContext, page_nr: number, setup: PageSetup ): void; vfunc_status_changed(): void; vfunc_update_custom_widget( widget: Widget, setup: PageSetup, settings: PrintSettings ): void; // Implemented Members end_preview(): void; is_selected(page_nr: number): boolean; render_page(page_nr: number): void; vfunc_end_preview(): void; vfunc_got_page_size(context: PrintContext, page_setup: PageSetup): void; vfunc_is_selected(page_nr: number): boolean; vfunc_ready(context: PrintContext): void; vfunc_render_page(page_nr: number): void; } export namespace PrintSettings { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class PrintSettings extends GObject.Object { static $gtype: GObject.GType<PrintSettings>; constructor( properties?: Partial<PrintSettings.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<PrintSettings.ConstructorProperties>, ...args: any[] ): void; // Constructors static ['new'](): PrintSettings; static new_from_file(file_name: string): PrintSettings; static new_from_gvariant(variant: GLib.Variant): PrintSettings; static new_from_key_file( key_file: GLib.KeyFile, group_name?: string | null ): PrintSettings; // Members copy(): PrintSettings; foreach(func: PrintSettingsFunc): void; get(key: string): string; get_bool(key: string): boolean; get_collate(): boolean; get_default_source(): string; get_dither(): string; get_double(key: string): number; get_double_with_default(key: string, def: number): number; get_duplex(): PrintDuplex; get_finishings(): string; get_int(key: string): number; get_int_with_default(key: string, def: number): number; get_length(key: string, unit: Unit): number; get_media_type(): string; get_n_copies(): number; get_number_up(): number; get_number_up_layout(): NumberUpLayout; get_orientation(): PageOrientation; get_output_bin(): string; get_page_ranges(): PageRange[]; get_page_set(): PageSet; get_paper_height(unit: Unit): number; get_paper_size(): PaperSize; get_paper_width(unit: Unit): number; get_print_pages(): PrintPages; get_printer(): string; get_printer_lpi(): number; get_quality(): PrintQuality; get_resolution(): number; get_resolution_x(): number; get_resolution_y(): number; get_reverse(): boolean; get_scale(): number; get_use_color(): boolean; has_key(key: string): boolean; load_file(file_name: string): boolean; load_key_file(key_file: GLib.KeyFile, group_name?: string | null): boolean; set(key: string, value?: string | null): void; set(...args: never[]): never; set_bool(key: string, value: boolean): void; set_collate(collate: boolean): void; set_default_source(default_source: string): void; set_dither(dither: string): void; set_double(key: string, value: number): void; set_duplex(duplex: PrintDuplex): void; set_finishings(finishings: string): void; set_int(key: string, value: number): void; set_length(key: string, value: number, unit: Unit): void; set_media_type(media_type: string): void; set_n_copies(num_copies: number): void; set_number_up(number_up: number): void; set_number_up_layout(number_up_layout: NumberUpLayout): void; set_orientation(orientation: PageOrientation): void; set_output_bin(output_bin: string): void; set_page_ranges(page_ranges: PageRange[]): void; set_page_set(page_set: PageSet): void; set_paper_height(height: number, unit: Unit): void; set_paper_size(paper_size: PaperSize): void; set_paper_width(width: number, unit: Unit): void; set_print_pages(pages: PrintPages): void; set_printer(printer: string): void; set_printer_lpi(lpi: number): void; set_quality(quality: PrintQuality): void; set_resolution(resolution: number): void; set_resolution_xy(resolution_x: number, resolution_y: number): void; set_reverse(reverse: boolean): void; set_scale(scale: number): void; set_use_color(use_color: boolean): void; to_file(file_name: string): boolean; to_gvariant(): GLib.Variant; to_key_file(key_file: GLib.KeyFile, group_name?: string | null): void; unset(key: string): void; } export namespace ProgressBar { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; ellipsize: Pango.EllipsizeMode; fraction: number; inverted: boolean; pulse_step: number; pulseStep: number; show_text: boolean; showText: boolean; text: string; } } export class ProgressBar extends Widget implements Accessible, Buildable, ConstraintTarget, Orientable { static $gtype: GObject.GType<ProgressBar>; constructor( properties?: Partial<ProgressBar.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ProgressBar.ConstructorProperties>, ...args: any[] ): void; // Properties ellipsize: Pango.EllipsizeMode; fraction: number; inverted: boolean; pulse_step: number; pulseStep: number; show_text: boolean; showText: boolean; text: string; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; orientation: Orientation; // Constructors static ['new'](): ProgressBar; // Members get_ellipsize(): Pango.EllipsizeMode; get_fraction(): number; get_inverted(): boolean; get_pulse_step(): number; get_show_text(): boolean; get_text(): string | null; pulse(): void; set_ellipsize(mode: Pango.EllipsizeMode): void; set_fraction(fraction: number): void; set_inverted(inverted: boolean): void; set_pulse_step(fraction: number): void; set_show_text(show_text: boolean): void; set_text(text?: string | null): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_orientation(): Orientation; set_orientation(orientation: Orientation): void; } export namespace PropertyExpression { export interface ConstructorProperties extends Expression.ConstructorProperties { [key: string]: any; } } export class PropertyExpression extends Expression { static $gtype: GObject.GType<PropertyExpression>; constructor( properties?: Partial<PropertyExpression.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<PropertyExpression.ConstructorProperties>, ...args: any[] ): void; // Constructors static ['new']( this_type: GObject.GType, expression: Expression | null, property_name: string ): PropertyExpression; static new_for_pspec( expression: Expression | null, pspec: GObject.ParamSpec ): PropertyExpression; // Members get_expression(): Expression; get_pspec(): GObject.ParamSpec; } export namespace Range { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; adjustment: Adjustment; fill_level: number; fillLevel: number; inverted: boolean; restrict_to_fill_level: boolean; restrictToFillLevel: boolean; round_digits: number; roundDigits: number; show_fill_level: boolean; showFillLevel: boolean; } } export class Range extends Widget implements Accessible, Buildable, ConstraintTarget, Orientable { static $gtype: GObject.GType<Range>; constructor( properties?: Partial<Range.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Range.ConstructorProperties>, ...args: any[] ): void; // Properties adjustment: Adjustment; fill_level: number; fillLevel: number; inverted: boolean; restrict_to_fill_level: boolean; restrictToFillLevel: boolean; round_digits: number; roundDigits: number; show_fill_level: boolean; showFillLevel: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'adjust-bounds', callback: (_source: this, value: number) => void ): number; connect_after( signal: 'adjust-bounds', callback: (_source: this, value: number) => void ): number; emit(signal: 'adjust-bounds', value: number): void; connect( signal: 'change-value', callback: (_source: this, scroll: ScrollType, value: number) => boolean ): number; connect_after( signal: 'change-value', callback: (_source: this, scroll: ScrollType, value: number) => boolean ): number; emit(signal: 'change-value', scroll: ScrollType, value: number): void; connect( signal: 'move-slider', callback: (_source: this, step: ScrollType) => void ): number; connect_after( signal: 'move-slider', callback: (_source: this, step: ScrollType) => void ): number; emit(signal: 'move-slider', step: ScrollType): void; connect(signal: 'value-changed', callback: (_source: this) => void): number; connect_after( signal: 'value-changed', callback: (_source: this) => void ): number; emit(signal: 'value-changed'): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; orientation: Orientation; // Members get_adjustment(): Adjustment; get_fill_level(): number; get_flippable(): boolean; get_inverted(): boolean; get_range_rect(): Gdk.Rectangle; get_restrict_to_fill_level(): boolean; get_round_digits(): number; get_show_fill_level(): boolean; get_slider_range(): [number | null, number | null]; get_slider_size_fixed(): boolean; get_value(): number; set_adjustment(adjustment: Adjustment): void; set_fill_level(fill_level: number): void; set_flippable(flippable: boolean): void; set_increments(step: number, page: number): void; set_inverted(setting: boolean): void; set_range(min: number, max: number): void; set_restrict_to_fill_level(restrict_to_fill_level: boolean): void; set_round_digits(round_digits: number): void; set_show_fill_level(show_fill_level: boolean): void; set_slider_size_fixed(size_fixed: boolean): void; set_value(value: number): void; vfunc_adjust_bounds(new_value: number): void; vfunc_change_value(scroll: ScrollType, new_value: number): boolean; vfunc_get_range_border(border_: Border): void; vfunc_move_slider(scroll: ScrollType): void; vfunc_value_changed(): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_orientation(): Orientation; set_orientation(orientation: Orientation): void; } export namespace RecentManager { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; filename: string; size: number; } } export class RecentManager extends GObject.Object { static $gtype: GObject.GType<RecentManager>; constructor( properties?: Partial<RecentManager.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<RecentManager.ConstructorProperties>, ...args: any[] ): void; // Properties filename: string; size: number; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'changed', callback: (_source: this) => void): number; connect_after(signal: 'changed', callback: (_source: this) => void): number; emit(signal: 'changed'): void; // Constructors static ['new'](): RecentManager; // Members add_full(uri: string, recent_data: RecentData): boolean; add_item(uri: string): boolean; get_items(): RecentInfo[]; has_item(uri: string): boolean; lookup_item(uri: string): RecentInfo | null; move_item(uri: string, new_uri?: string | null): boolean; purge_items(): number; remove_item(uri: string): boolean; vfunc_changed(): void; static get_default(): RecentManager; } export namespace Revealer { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; child: Widget; child_revealed: boolean; childRevealed: boolean; reveal_child: boolean; revealChild: boolean; transition_duration: number; transitionDuration: number; transition_type: RevealerTransitionType; transitionType: RevealerTransitionType; } } export class Revealer extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<Revealer>; constructor( properties?: Partial<Revealer.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Revealer.ConstructorProperties>, ...args: any[] ): void; // Properties child: Widget; child_revealed: boolean; childRevealed: boolean; reveal_child: boolean; revealChild: boolean; transition_duration: number; transitionDuration: number; transition_type: RevealerTransitionType; transitionType: RevealerTransitionType; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](): Revealer; // Members get_child(): Widget | null; get_child_revealed(): boolean; get_reveal_child(): boolean; get_transition_duration(): number; get_transition_type(): RevealerTransitionType; set_child(child?: Widget | null): void; set_reveal_child(reveal_child: boolean): void; set_transition_duration(duration: number): void; set_transition_type(transition: RevealerTransitionType): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace Scale { export interface ConstructorProperties extends Range.ConstructorProperties { [key: string]: any; digits: number; draw_value: boolean; drawValue: boolean; has_origin: boolean; hasOrigin: boolean; value_pos: PositionType; valuePos: PositionType; } } export class Scale extends Range implements Accessible, Buildable, ConstraintTarget, Orientable { static $gtype: GObject.GType<Scale>; constructor( properties?: Partial<Scale.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Scale.ConstructorProperties>, ...args: any[] ): void; // Properties digits: number; draw_value: boolean; drawValue: boolean; has_origin: boolean; hasOrigin: boolean; value_pos: PositionType; valuePos: PositionType; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; orientation: Orientation; // Constructors static ['new']( orientation: Orientation, adjustment?: Adjustment | null ): Scale; static new_with_range( orientation: Orientation, min: number, max: number, step: number ): Scale; // Members add_mark( value: number, position: PositionType, markup?: string | null ): void; clear_marks(): void; get_digits(): number; get_draw_value(): boolean; get_has_origin(): boolean; get_layout(): Pango.Layout | null; get_layout_offsets(): [number | null, number | null]; get_value_pos(): PositionType; set_digits(digits: number): void; set_draw_value(draw_value: boolean): void; set_format_value_func( func?: ScaleFormatValueFunc | null, destroy_notify?: GLib.DestroyNotify | null ): void; set_has_origin(has_origin: boolean): void; set_value_pos(pos: PositionType): void; vfunc_get_layout_offsets(): [number | null, number | null]; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_orientation(): Orientation; set_orientation(orientation: Orientation): void; } export namespace ScaleButton { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; adjustment: Adjustment; icons: string[]; value: number; } } export class ScaleButton extends Widget implements Accessible, Buildable, ConstraintTarget, Orientable { static $gtype: GObject.GType<ScaleButton>; constructor( properties?: Partial<ScaleButton.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ScaleButton.ConstructorProperties>, ...args: any[] ): void; // Properties adjustment: Adjustment; icons: string[]; value: number; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'popdown', callback: (_source: this) => void): number; connect_after(signal: 'popdown', callback: (_source: this) => void): number; emit(signal: 'popdown'): void; connect(signal: 'popup', callback: (_source: this) => void): number; connect_after(signal: 'popup', callback: (_source: this) => void): number; emit(signal: 'popup'): void; connect( signal: 'value-changed', callback: (_source: this, value: number) => void ): number; connect_after( signal: 'value-changed', callback: (_source: this, value: number) => void ): number; emit(signal: 'value-changed', value: number): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; orientation: Orientation; // Constructors static ['new']( min: number, max: number, step: number, icons?: string[] | null ): ScaleButton; // Members get_adjustment(): Adjustment; get_minus_button(): Button; get_plus_button(): Button; get_popup(): Widget; get_value(): number; set_adjustment(adjustment: Adjustment): void; set_icons(icons: string[]): void; set_value(value: number): void; vfunc_value_changed(value: number): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_orientation(): Orientation; set_orientation(orientation: Orientation): void; } export namespace Scrollbar { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; adjustment: Adjustment; } } export class Scrollbar extends Widget implements Accessible, Buildable, ConstraintTarget, Orientable { static $gtype: GObject.GType<Scrollbar>; constructor( properties?: Partial<Scrollbar.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Scrollbar.ConstructorProperties>, ...args: any[] ): void; // Properties adjustment: Adjustment; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; orientation: Orientation; // Constructors static ['new']( orientation: Orientation, adjustment?: Adjustment | null ): Scrollbar; // Members get_adjustment(): Adjustment; set_adjustment(adjustment?: Adjustment | null): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_orientation(): Orientation; set_orientation(orientation: Orientation): void; } export namespace ScrolledWindow { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; child: Widget; hadjustment: Adjustment; has_frame: boolean; hasFrame: boolean; hscrollbar_policy: PolicyType; hscrollbarPolicy: PolicyType; kinetic_scrolling: boolean; kineticScrolling: boolean; max_content_height: number; maxContentHeight: number; max_content_width: number; maxContentWidth: number; min_content_height: number; minContentHeight: number; min_content_width: number; minContentWidth: number; overlay_scrolling: boolean; overlayScrolling: boolean; propagate_natural_height: boolean; propagateNaturalHeight: boolean; propagate_natural_width: boolean; propagateNaturalWidth: boolean; vadjustment: Adjustment; vscrollbar_policy: PolicyType; vscrollbarPolicy: PolicyType; window_placement: CornerType; windowPlacement: CornerType; } } export class ScrolledWindow extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<ScrolledWindow>; constructor( properties?: Partial<ScrolledWindow.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ScrolledWindow.ConstructorProperties>, ...args: any[] ): void; // Properties child: Widget; hadjustment: Adjustment; has_frame: boolean; hasFrame: boolean; hscrollbar_policy: PolicyType; hscrollbarPolicy: PolicyType; kinetic_scrolling: boolean; kineticScrolling: boolean; max_content_height: number; maxContentHeight: number; max_content_width: number; maxContentWidth: number; min_content_height: number; minContentHeight: number; min_content_width: number; minContentWidth: number; overlay_scrolling: boolean; overlayScrolling: boolean; propagate_natural_height: boolean; propagateNaturalHeight: boolean; propagate_natural_width: boolean; propagateNaturalWidth: boolean; vadjustment: Adjustment; vscrollbar_policy: PolicyType; vscrollbarPolicy: PolicyType; window_placement: CornerType; windowPlacement: CornerType; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'edge-overshot', callback: (_source: this, pos: PositionType) => void ): number; connect_after( signal: 'edge-overshot', callback: (_source: this, pos: PositionType) => void ): number; emit(signal: 'edge-overshot', pos: PositionType): void; connect( signal: 'edge-reached', callback: (_source: this, pos: PositionType) => void ): number; connect_after( signal: 'edge-reached', callback: (_source: this, pos: PositionType) => void ): number; emit(signal: 'edge-reached', pos: PositionType): void; connect( signal: 'move-focus-out', callback: (_source: this, direction_type: DirectionType) => void ): number; connect_after( signal: 'move-focus-out', callback: (_source: this, direction_type: DirectionType) => void ): number; emit(signal: 'move-focus-out', direction_type: DirectionType): void; connect( signal: 'scroll-child', callback: ( _source: this, scroll: ScrollType, horizontal: boolean ) => boolean ): number; connect_after( signal: 'scroll-child', callback: ( _source: this, scroll: ScrollType, horizontal: boolean ) => boolean ): number; emit(signal: 'scroll-child', scroll: ScrollType, horizontal: boolean): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](): ScrolledWindow; // Members get_child(): Widget | null; get_hadjustment(): Adjustment; get_has_frame(): boolean; get_hscrollbar(): Widget; get_kinetic_scrolling(): boolean; get_max_content_height(): number; get_max_content_width(): number; get_min_content_height(): number; get_min_content_width(): number; get_overlay_scrolling(): boolean; get_placement(): CornerType; get_policy(): [PolicyType | null, PolicyType | null]; get_propagate_natural_height(): boolean; get_propagate_natural_width(): boolean; get_vadjustment(): Adjustment; get_vscrollbar(): Widget; set_child(child?: Widget | null): void; set_hadjustment(hadjustment?: Adjustment | null): void; set_has_frame(has_frame: boolean): void; set_kinetic_scrolling(kinetic_scrolling: boolean): void; set_max_content_height(height: number): void; set_max_content_width(width: number): void; set_min_content_height(height: number): void; set_min_content_width(width: number): void; set_overlay_scrolling(overlay_scrolling: boolean): void; set_placement(window_placement: CornerType): void; set_policy( hscrollbar_policy: PolicyType, vscrollbar_policy: PolicyType ): void; set_propagate_natural_height(propagate: boolean): void; set_propagate_natural_width(propagate: boolean): void; set_vadjustment(vadjustment?: Adjustment | null): void; unset_placement(): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace SearchBar { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; child: Widget; key_capture_widget: Widget; keyCaptureWidget: Widget; search_mode_enabled: boolean; searchModeEnabled: boolean; show_close_button: boolean; showCloseButton: boolean; } } export class SearchBar extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<SearchBar>; constructor( properties?: Partial<SearchBar.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<SearchBar.ConstructorProperties>, ...args: any[] ): void; // Properties child: Widget; key_capture_widget: Widget; keyCaptureWidget: Widget; search_mode_enabled: boolean; searchModeEnabled: boolean; show_close_button: boolean; showCloseButton: boolean; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](): SearchBar; // Members connect_entry(entry: Editable): void; get_child(): Widget | null; get_key_capture_widget(): Widget; get_search_mode(): boolean; get_show_close_button(): boolean; set_child(child?: Widget | null): void; set_key_capture_widget(widget?: Widget | null): void; set_search_mode(search_mode: boolean): void; set_show_close_button(visible: boolean): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace SearchEntry { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; activates_default: boolean; activatesDefault: boolean; placeholder_text: string; placeholderText: string; } } export class SearchEntry extends Widget implements Accessible, Buildable, ConstraintTarget, Editable { static $gtype: GObject.GType<SearchEntry>; constructor( properties?: Partial<SearchEntry.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<SearchEntry.ConstructorProperties>, ...args: any[] ): void; // Properties activates_default: boolean; activatesDefault: boolean; placeholder_text: string; placeholderText: string; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'activate', callback: (_source: this) => void): number; connect_after( signal: 'activate', callback: (_source: this) => void ): number; emit(signal: 'activate'): void; connect(signal: 'next-match', callback: (_source: this) => void): number; connect_after( signal: 'next-match', callback: (_source: this) => void ): number; emit(signal: 'next-match'): void; connect( signal: 'previous-match', callback: (_source: this) => void ): number; connect_after( signal: 'previous-match', callback: (_source: this) => void ): number; emit(signal: 'previous-match'): void; connect( signal: 'search-changed', callback: (_source: this) => void ): number; connect_after( signal: 'search-changed', callback: (_source: this) => void ): number; emit(signal: 'search-changed'): void; connect( signal: 'search-started', callback: (_source: this) => void ): number; connect_after( signal: 'search-started', callback: (_source: this) => void ): number; emit(signal: 'search-started'): void; connect(signal: 'stop-search', callback: (_source: this) => void): number; connect_after( signal: 'stop-search', callback: (_source: this) => void ): number; emit(signal: 'stop-search'): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; cursor_position: number; cursorPosition: number; editable: boolean; enable_undo: boolean; enableUndo: boolean; max_width_chars: number; maxWidthChars: number; selection_bound: number; selectionBound: number; text: string; width_chars: number; widthChars: number; xalign: number; // Constructors static ['new'](): SearchEntry; // Members get_key_capture_widget(): Widget; set_key_capture_widget(widget?: Widget | null): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; delete_selection(): void; delete_text(start_pos: number, end_pos: number): void; finish_delegate(): void; get_alignment(): number; get_chars(start_pos: number, end_pos: number): string; get_delegate(): Editable | null; get_editable(): boolean; get_enable_undo(): boolean; get_max_width_chars(): number; get_position(): number; get_selection_bounds(): [boolean, number | null, number | null]; get_text(): string; get_width_chars(): number; init_delegate(): void; insert_text(text: string, length: number, position: number): number; select_region(start_pos: number, end_pos: number): void; set_alignment(xalign: number): void; set_editable(is_editable: boolean): void; set_enable_undo(enable_undo: boolean): void; set_max_width_chars(n_chars: number): void; set_position(position: number): void; set_text(text: string): void; set_width_chars(n_chars: number): void; vfunc_changed(): void; vfunc_delete_text(start_pos: number, end_pos: number): void; vfunc_do_delete_text(start_pos: number, end_pos: number): void; vfunc_do_insert_text( text: string, length: number, position: number ): number; vfunc_get_delegate(): Editable | null; vfunc_get_selection_bounds(): [boolean, number | null, number | null]; vfunc_get_text(): string; vfunc_insert_text(text: string, length: number, position: number): number; vfunc_set_selection_bounds(start_pos: number, end_pos: number): void; } export namespace SelectionFilterModel { export interface ConstructorProperties< A extends GObject.Object = GObject.Object > extends GObject.Object.ConstructorProperties { [key: string]: any; model: SelectionModel; } } export class SelectionFilterModel<A extends GObject.Object = GObject.Object> extends GObject.Object implements Gio.ListModel<A> { static $gtype: GObject.GType<SelectionFilterModel>; constructor( properties?: Partial<SelectionFilterModel.ConstructorProperties<A>>, ...args: any[] ); _init( properties?: Partial<SelectionFilterModel.ConstructorProperties<A>>, ...args: any[] ): void; // Properties model: SelectionModel; // Constructors static ['new'](model?: SelectionModel | null): SelectionFilterModel; // Members get_model(): SelectionModel | null; set_model(model?: SelectionModel | null): void; // Implemented Members get_item_type(): GObject.GType; get_n_items(): number; get_item(position: number): A | null; items_changed(position: number, removed: number, added: number): void; vfunc_get_item(position: number): A | null; vfunc_get_item_type(): GObject.GType; vfunc_get_n_items(): number; } export namespace Separator { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; } } export class Separator extends Widget implements Accessible, Buildable, ConstraintTarget, Orientable { static $gtype: GObject.GType<Separator>; constructor( properties?: Partial<Separator.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Separator.ConstructorProperties>, ...args: any[] ): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; orientation: Orientation; // Constructors static ['new'](orientation: Orientation): Separator; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_orientation(): Orientation; set_orientation(orientation: Orientation): void; } export namespace Settings { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; gtk_alternative_button_order: boolean; gtkAlternativeButtonOrder: boolean; gtk_alternative_sort_arrows: boolean; gtkAlternativeSortArrows: boolean; gtk_application_prefer_dark_theme: boolean; gtkApplicationPreferDarkTheme: boolean; gtk_cursor_aspect_ratio: number; gtkCursorAspectRatio: number; gtk_cursor_blink: boolean; gtkCursorBlink: boolean; gtk_cursor_blink_time: number; gtkCursorBlinkTime: number; gtk_cursor_blink_timeout: number; gtkCursorBlinkTimeout: number; gtk_cursor_theme_name: string; gtkCursorThemeName: string; gtk_cursor_theme_size: number; gtkCursorThemeSize: number; gtk_decoration_layout: string; gtkDecorationLayout: string; gtk_dialogs_use_header: boolean; gtkDialogsUseHeader: boolean; gtk_dnd_drag_threshold: number; gtkDndDragThreshold: number; gtk_double_click_distance: number; gtkDoubleClickDistance: number; gtk_double_click_time: number; gtkDoubleClickTime: number; gtk_enable_accels: boolean; gtkEnableAccels: boolean; gtk_enable_animations: boolean; gtkEnableAnimations: boolean; gtk_enable_event_sounds: boolean; gtkEnableEventSounds: boolean; gtk_enable_input_feedback_sounds: boolean; gtkEnableInputFeedbackSounds: boolean; gtk_enable_primary_paste: boolean; gtkEnablePrimaryPaste: boolean; gtk_entry_password_hint_timeout: number; gtkEntryPasswordHintTimeout: number; gtk_entry_select_on_focus: boolean; gtkEntrySelectOnFocus: boolean; gtk_error_bell: boolean; gtkErrorBell: boolean; gtk_font_name: string; gtkFontName: string; gtk_fontconfig_timestamp: number; gtkFontconfigTimestamp: number; gtk_icon_theme_name: string; gtkIconThemeName: string; gtk_im_module: string; gtkImModule: string; gtk_keynav_use_caret: boolean; gtkKeynavUseCaret: boolean; gtk_label_select_on_focus: boolean; gtkLabelSelectOnFocus: boolean; gtk_long_press_time: number; gtkLongPressTime: number; gtk_overlay_scrolling: boolean; gtkOverlayScrolling: boolean; gtk_primary_button_warps_slider: boolean; gtkPrimaryButtonWarpsSlider: boolean; gtk_print_backends: string; gtkPrintBackends: string; gtk_print_preview_command: string; gtkPrintPreviewCommand: string; gtk_recent_files_enabled: boolean; gtkRecentFilesEnabled: boolean; gtk_recent_files_max_age: number; gtkRecentFilesMaxAge: number; gtk_shell_shows_app_menu: boolean; gtkShellShowsAppMenu: boolean; gtk_shell_shows_desktop: boolean; gtkShellShowsDesktop: boolean; gtk_shell_shows_menubar: boolean; gtkShellShowsMenubar: boolean; gtk_sound_theme_name: string; gtkSoundThemeName: string; gtk_split_cursor: boolean; gtkSplitCursor: boolean; gtk_theme_name: string; gtkThemeName: string; gtk_titlebar_double_click: string; gtkTitlebarDoubleClick: string; gtk_titlebar_middle_click: string; gtkTitlebarMiddleClick: string; gtk_titlebar_right_click: string; gtkTitlebarRightClick: string; gtk_xft_antialias: number; gtkXftAntialias: number; gtk_xft_dpi: number; gtkXftDpi: number; gtk_xft_hinting: number; gtkXftHinting: number; gtk_xft_hintstyle: string; gtkXftHintstyle: string; gtk_xft_rgba: string; gtkXftRgba: string; } } export class Settings extends GObject.Object implements StyleProvider { static $gtype: GObject.GType<Settings>; constructor( properties?: Partial<Settings.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Settings.ConstructorProperties>, ...args: any[] ): void; // Properties gtk_alternative_button_order: boolean; gtkAlternativeButtonOrder: boolean; gtk_alternative_sort_arrows: boolean; gtkAlternativeSortArrows: boolean; gtk_application_prefer_dark_theme: boolean; gtkApplicationPreferDarkTheme: boolean; gtk_cursor_aspect_ratio: number; gtkCursorAspectRatio: number; gtk_cursor_blink: boolean; gtkCursorBlink: boolean; gtk_cursor_blink_time: number; gtkCursorBlinkTime: number; gtk_cursor_blink_timeout: number; gtkCursorBlinkTimeout: number; gtk_cursor_theme_name: string; gtkCursorThemeName: string; gtk_cursor_theme_size: number; gtkCursorThemeSize: number; gtk_decoration_layout: string; gtkDecorationLayout: string; gtk_dialogs_use_header: boolean; gtkDialogsUseHeader: boolean; gtk_dnd_drag_threshold: number; gtkDndDragThreshold: number; gtk_double_click_distance: number; gtkDoubleClickDistance: number; gtk_double_click_time: number; gtkDoubleClickTime: number; gtk_enable_accels: boolean; gtkEnableAccels: boolean; gtk_enable_animations: boolean; gtkEnableAnimations: boolean; gtk_enable_event_sounds: boolean; gtkEnableEventSounds: boolean; gtk_enable_input_feedback_sounds: boolean; gtkEnableInputFeedbackSounds: boolean; gtk_enable_primary_paste: boolean; gtkEnablePrimaryPaste: boolean; gtk_entry_password_hint_timeout: number; gtkEntryPasswordHintTimeout: number; gtk_entry_select_on_focus: boolean; gtkEntrySelectOnFocus: boolean; gtk_error_bell: boolean; gtkErrorBell: boolean; gtk_font_name: string; gtkFontName: string; gtk_fontconfig_timestamp: number; gtkFontconfigTimestamp: number; gtk_icon_theme_name: string; gtkIconThemeName: string; gtk_im_module: string; gtkImModule: string; gtk_keynav_use_caret: boolean; gtkKeynavUseCaret: boolean; gtk_label_select_on_focus: boolean; gtkLabelSelectOnFocus: boolean; gtk_long_press_time: number; gtkLongPressTime: number; gtk_overlay_scrolling: boolean; gtkOverlayScrolling: boolean; gtk_primary_button_warps_slider: boolean; gtkPrimaryButtonWarpsSlider: boolean; gtk_print_backends: string; gtkPrintBackends: string; gtk_print_preview_command: string; gtkPrintPreviewCommand: string; gtk_recent_files_enabled: boolean; gtkRecentFilesEnabled: boolean; gtk_recent_files_max_age: number; gtkRecentFilesMaxAge: number; gtk_shell_shows_app_menu: boolean; gtkShellShowsAppMenu: boolean; gtk_shell_shows_desktop: boolean; gtkShellShowsDesktop: boolean; gtk_shell_shows_menubar: boolean; gtkShellShowsMenubar: boolean; gtk_sound_theme_name: string; gtkSoundThemeName: string; gtk_split_cursor: boolean; gtkSplitCursor: boolean; gtk_theme_name: string; gtkThemeName: string; gtk_titlebar_double_click: string; gtkTitlebarDoubleClick: string; gtk_titlebar_middle_click: string; gtkTitlebarMiddleClick: string; gtk_titlebar_right_click: string; gtkTitlebarRightClick: string; gtk_xft_antialias: number; gtkXftAntialias: number; gtk_xft_dpi: number; gtkXftDpi: number; gtk_xft_hinting: number; gtkXftHinting: number; gtk_xft_hintstyle: string; gtkXftHintstyle: string; gtk_xft_rgba: string; gtkXftRgba: string; // Members reset_property(name: string): void; static get_default(): Settings | null; static get_for_display(display: Gdk.Display): Settings; } export namespace Shortcut { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; action: ShortcutAction; arguments: GLib.Variant; trigger: ShortcutTrigger; } } export class Shortcut extends GObject.Object { static $gtype: GObject.GType<Shortcut>; constructor( properties?: Partial<Shortcut.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Shortcut.ConstructorProperties>, ...args: any[] ): void; // Properties action: ShortcutAction; 'arguments': GLib.Variant; trigger: ShortcutTrigger; // Constructors static ['new']( trigger?: ShortcutTrigger | null, action?: ShortcutAction | null ): Shortcut; // Members get_action(): ShortcutAction | null; get_arguments(): GLib.Variant | null; get_trigger(): ShortcutTrigger | null; set_action(action?: ShortcutAction | null): void; set_arguments(args?: GLib.Variant | null): void; set_trigger(trigger?: ShortcutTrigger | null): void; } export namespace ShortcutAction { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export abstract class ShortcutAction extends GObject.Object { static $gtype: GObject.GType<ShortcutAction>; constructor( properties?: Partial<ShortcutAction.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ShortcutAction.ConstructorProperties>, ...args: any[] ): void; // Constructors static parse_string(string: string): ShortcutAction; // Members activate( flags: ShortcutActionFlags, widget: Widget, args?: GLib.Variant | null ): boolean; print(string: GLib.String): void; to_string(): string; } export namespace ShortcutController { export interface ConstructorProperties< A extends GObject.Object = GObject.Object > extends EventController.ConstructorProperties { [key: string]: any; mnemonic_modifiers: Gdk.ModifierType; mnemonicModifiers: Gdk.ModifierType; model: Gio.ListModel; scope: ShortcutScope; } } export class ShortcutController<A extends GObject.Object = GObject.Object> extends EventController implements Gio.ListModel<A>, Buildable { static $gtype: GObject.GType<ShortcutController>; constructor( properties?: Partial<ShortcutController.ConstructorProperties<A>>, ...args: any[] ); _init( properties?: Partial<ShortcutController.ConstructorProperties<A>>, ...args: any[] ): void; // Properties mnemonic_modifiers: Gdk.ModifierType; mnemonicModifiers: Gdk.ModifierType; model: Gio.ListModel; scope: ShortcutScope; // Constructors static ['new'](): ShortcutController; static new_for_model(model: Gio.ListModel): ShortcutController; // Members add_shortcut(shortcut: Shortcut): void; get_mnemonics_modifiers(): Gdk.ModifierType; get_scope(): ShortcutScope; remove_shortcut(shortcut: Shortcut): void; set_mnemonics_modifiers(modifiers: Gdk.ModifierType): void; set_scope(scope: ShortcutScope): void; // Implemented Members get_item_type(): GObject.GType; get_n_items(): number; get_item(position: number): A | null; items_changed(position: number, removed: number, added: number): void; vfunc_get_item(position: number): A | null; vfunc_get_item_type(): GObject.GType; vfunc_get_n_items(): number; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace ShortcutLabel { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; accelerator: string; disabled_text: string; disabledText: string; } } export class ShortcutLabel extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<ShortcutLabel>; constructor( properties?: Partial<ShortcutLabel.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ShortcutLabel.ConstructorProperties>, ...args: any[] ): void; // Properties accelerator: string; disabled_text: string; disabledText: string; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](accelerator: string): ShortcutLabel; // Members get_accelerator(): string | null; get_disabled_text(): string | null; set_accelerator(accelerator: string): void; set_disabled_text(disabled_text: string): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace ShortcutTrigger { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export abstract class ShortcutTrigger extends GObject.Object { static $gtype: GObject.GType<ShortcutTrigger>; constructor( properties?: Partial<ShortcutTrigger.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ShortcutTrigger.ConstructorProperties>, ...args: any[] ): void; // Constructors static parse_string(string: string): ShortcutTrigger; // Members compare(trigger2: ShortcutTrigger): number; equal(trigger2: ShortcutTrigger): boolean; hash(): number; print(string: GLib.String): void; print_label(display: Gdk.Display, string: GLib.String): boolean; to_label(display: Gdk.Display): string; to_string(): string; trigger(event: Gdk.Event, enable_mnemonics: boolean): Gdk.KeyMatch; } export namespace ShortcutsGroup { export interface ConstructorProperties extends Box.ConstructorProperties { [key: string]: any; accel_size_group: SizeGroup; accelSizeGroup: SizeGroup; height: number; title: string; title_size_group: SizeGroup; titleSizeGroup: SizeGroup; view: string; } } export class ShortcutsGroup extends Box implements Accessible, Buildable, ConstraintTarget, Orientable { static $gtype: GObject.GType<ShortcutsGroup>; constructor( properties?: Partial<ShortcutsGroup.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ShortcutsGroup.ConstructorProperties>, ...args: any[] ): void; // Properties accel_size_group: SizeGroup; accelSizeGroup: SizeGroup; height: number; title: string; title_size_group: SizeGroup; titleSizeGroup: SizeGroup; view: string; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; orientation: Orientation; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_orientation(): Orientation; set_orientation(orientation: Orientation): void; } export namespace ShortcutsSection { export interface ConstructorProperties extends Box.ConstructorProperties { [key: string]: any; max_height: number; maxHeight: number; section_name: string; sectionName: string; title: string; view_name: string; viewName: string; } } export class ShortcutsSection extends Box implements Accessible, Buildable, ConstraintTarget, Orientable { static $gtype: GObject.GType<ShortcutsSection>; constructor( properties?: Partial<ShortcutsSection.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ShortcutsSection.ConstructorProperties>, ...args: any[] ): void; // Properties max_height: number; maxHeight: number; section_name: string; sectionName: string; title: string; view_name: string; viewName: string; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'change-current-page', callback: (_source: this, object: number) => boolean ): number; connect_after( signal: 'change-current-page', callback: (_source: this, object: number) => boolean ): number; emit(signal: 'change-current-page', object: number): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; orientation: Orientation; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_orientation(): Orientation; set_orientation(orientation: Orientation): void; } export namespace ShortcutsShortcut { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; accel_size_group: SizeGroup; accelSizeGroup: SizeGroup; accelerator: string; action_name: string; actionName: string; direction: TextDirection; icon: Gio.Icon; icon_set: boolean; iconSet: boolean; shortcut_type: ShortcutType; shortcutType: ShortcutType; subtitle: string; subtitle_set: boolean; subtitleSet: boolean; title: string; title_size_group: SizeGroup; titleSizeGroup: SizeGroup; } } export class ShortcutsShortcut extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<ShortcutsShortcut>; constructor( properties?: Partial<ShortcutsShortcut.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ShortcutsShortcut.ConstructorProperties>, ...args: any[] ): void; // Properties accel_size_group: SizeGroup; accelSizeGroup: SizeGroup; accelerator: string; action_name: string; actionName: string; direction: TextDirection; icon: Gio.Icon; icon_set: boolean; iconSet: boolean; shortcut_type: ShortcutType; shortcutType: ShortcutType; subtitle: string; subtitle_set: boolean; subtitleSet: boolean; title: string; title_size_group: SizeGroup; titleSizeGroup: SizeGroup; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace ShortcutsWindow { export interface ConstructorProperties extends Window.ConstructorProperties { [key: string]: any; section_name: string; sectionName: string; view_name: string; viewName: string; } } export class ShortcutsWindow extends Window implements Accessible, Buildable, ConstraintTarget, Native, Root, ShortcutManager { static $gtype: GObject.GType<ShortcutsWindow>; constructor( properties?: Partial<ShortcutsWindow.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ShortcutsWindow.ConstructorProperties>, ...args: any[] ): void; // Properties section_name: string; sectionName: string; view_name: string; viewName: string; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'close', callback: (_source: this) => void): number; connect_after(signal: 'close', callback: (_source: this) => void): number; emit(signal: 'close'): void; connect(signal: 'search', callback: (_source: this) => void): number; connect_after(signal: 'search', callback: (_source: this) => void): number; emit(signal: 'search'): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_renderer(): Gsk.Renderer; get_surface(): Gdk.Surface; get_surface_transform(): [number, number]; realize(): void; unrealize(): void; get_display(): Gdk.Display; get_focus(): Widget | null; set_focus(focus?: Widget | null): void; vfunc_add_controller(controller: ShortcutController): void; vfunc_remove_controller(controller: ShortcutController): void; } export namespace SignalAction { export interface ConstructorProperties extends ShortcutAction.ConstructorProperties { [key: string]: any; signal_name: string; signalName: string; } } export class SignalAction extends ShortcutAction { static $gtype: GObject.GType<SignalAction>; constructor( properties?: Partial<SignalAction.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<SignalAction.ConstructorProperties>, ...args: any[] ): void; // Properties signal_name: string; signalName: string; // Constructors static ['new'](signal_name: string): SignalAction; // Members get_signal_name(): string; } export namespace SignalListItemFactory { export interface ConstructorProperties extends ListItemFactory.ConstructorProperties { [key: string]: any; } } export class SignalListItemFactory extends ListItemFactory { static $gtype: GObject.GType<SignalListItemFactory>; constructor( properties?: Partial<SignalListItemFactory.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<SignalListItemFactory.ConstructorProperties>, ...args: any[] ): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'bind', callback: (_source: this, listitem: ListItem) => void ): number; connect_after( signal: 'bind', callback: (_source: this, listitem: ListItem) => void ): number; emit(signal: 'bind', listitem: ListItem): void; connect( signal: 'setup', callback: (_source: this, listitem: ListItem) => void ): number; connect_after( signal: 'setup', callback: (_source: this, listitem: ListItem) => void ): number; emit(signal: 'setup', listitem: ListItem): void; connect( signal: 'teardown', callback: (_source: this, listitem: ListItem) => void ): number; connect_after( signal: 'teardown', callback: (_source: this, listitem: ListItem) => void ): number; emit(signal: 'teardown', listitem: ListItem): void; connect( signal: 'unbind', callback: (_source: this, listitem: ListItem) => void ): number; connect_after( signal: 'unbind', callback: (_source: this, listitem: ListItem) => void ): number; emit(signal: 'unbind', listitem: ListItem): void; // Constructors static ['new'](): SignalListItemFactory; } export namespace SingleSelection { export interface ConstructorProperties< A extends GObject.Object = GObject.Object > extends GObject.Object.ConstructorProperties { [key: string]: any; autoselect: boolean; can_unselect: boolean; canUnselect: boolean; model: Gio.ListModel; selected: number; selected_item: GObject.Object; selectedItem: GObject.Object; } } export class SingleSelection<A extends GObject.Object = GObject.Object> extends GObject.Object implements Gio.ListModel<A>, SelectionModel<A> { static $gtype: GObject.GType<SingleSelection>; constructor( properties?: Partial<SingleSelection.ConstructorProperties<A>>, ...args: any[] ); _init( properties?: Partial<SingleSelection.ConstructorProperties<A>>, ...args: any[] ): void; // Properties autoselect: boolean; can_unselect: boolean; canUnselect: boolean; model: Gio.ListModel; selected: number; selected_item: GObject.Object; selectedItem: GObject.Object; // Constructors static ['new'](model?: Gio.ListModel | null): SingleSelection; // Members get_autoselect(): boolean; get_can_unselect(): boolean; get_model(): Gio.ListModel; get_selected(): number; get_selected_item(): any | null; set_autoselect(autoselect: boolean): void; set_can_unselect(can_unselect: boolean): void; set_model(model?: Gio.ListModel | null): void; set_selected(position: number): void; // Implemented Members get_item_type(): GObject.GType; get_n_items(): number; get_item(position: number): A | null; items_changed(position: number, removed: number, added: number): void; vfunc_get_item(position: number): A | null; vfunc_get_item_type(): GObject.GType; vfunc_get_n_items(): number; get_selection(): Bitset; get_selection_in_range(position: number, n_items: number): Bitset; is_selected(position: number): boolean; select_all(): boolean; select_item(position: number, unselect_rest: boolean): boolean; select_range( position: number, n_items: number, unselect_rest: boolean ): boolean; selection_changed(position: number, n_items: number): void; set_selection(selected: Bitset, mask: Bitset): boolean; unselect_all(): boolean; unselect_item(position: number): boolean; unselect_range(position: number, n_items: number): boolean; vfunc_get_selection_in_range(position: number, n_items: number): Bitset; vfunc_is_selected(position: number): boolean; vfunc_select_all(): boolean; vfunc_select_item(position: number, unselect_rest: boolean): boolean; vfunc_select_range( position: number, n_items: number, unselect_rest: boolean ): boolean; vfunc_set_selection(selected: Bitset, mask: Bitset): boolean; vfunc_unselect_all(): boolean; vfunc_unselect_item(position: number): boolean; vfunc_unselect_range(position: number, n_items: number): boolean; } export namespace SizeGroup { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; mode: SizeGroupMode; } } export class SizeGroup extends GObject.Object implements Buildable { static $gtype: GObject.GType<SizeGroup>; constructor( properties?: Partial<SizeGroup.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<SizeGroup.ConstructorProperties>, ...args: any[] ): void; // Properties mode: SizeGroupMode; // Constructors static ['new'](mode: SizeGroupMode): SizeGroup; // Members add_widget(widget: Widget): void; get_mode(): SizeGroupMode; get_widgets(): Widget[]; remove_widget(widget: Widget): void; set_mode(mode: SizeGroupMode): void; // Implemented Members get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace SliceListModel { export interface ConstructorProperties< A extends GObject.Object = GObject.Object > extends GObject.Object.ConstructorProperties { [key: string]: any; model: Gio.ListModel; offset: number; size: number; } } export class SliceListModel<A extends GObject.Object = GObject.Object> extends GObject.Object implements Gio.ListModel<A> { static $gtype: GObject.GType<SliceListModel>; constructor( properties?: Partial<SliceListModel.ConstructorProperties<A>>, ...args: any[] ); _init( properties?: Partial<SliceListModel.ConstructorProperties<A>>, ...args: any[] ): void; // Properties model: Gio.ListModel; offset: number; size: number; // Constructors static ['new']( model: Gio.ListModel | null, offset: number, size: number ): SliceListModel; // Members get_model(): Gio.ListModel | null; get_offset(): number; get_size(): number; set_model(model?: Gio.ListModel | null): void; set_offset(offset: number): void; set_size(size: number): void; // Implemented Members get_item_type(): GObject.GType; get_n_items(): number; get_item(position: number): A | null; items_changed(position: number, removed: number, added: number): void; vfunc_get_item(position: number): A | null; vfunc_get_item_type(): GObject.GType; vfunc_get_n_items(): number; } export namespace Snapshot { export interface ConstructorProperties extends Gdk.Snapshot.ConstructorProperties { [key: string]: any; } } export class Snapshot extends Gdk.Snapshot { static $gtype: GObject.GType<Snapshot>; constructor( properties?: Partial<Snapshot.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Snapshot.ConstructorProperties>, ...args: any[] ): void; // Constructors static ['new'](): Snapshot; // Members append_border( outline: Gsk.RoundedRect, border_width: number[], border_color: Gdk.RGBA[] ): void; append_cairo(bounds: Graphene.Rect): cairo.Context; append_color(color: Gdk.RGBA, bounds: Graphene.Rect): void; append_conic_gradient( bounds: Graphene.Rect, center: Graphene.Point, rotation: number, stops: Gsk.ColorStop[] ): void; append_inset_shadow( outline: Gsk.RoundedRect, color: Gdk.RGBA, dx: number, dy: number, spread: number, blur_radius: number ): void; append_layout(layout: Pango.Layout, color: Gdk.RGBA): void; append_linear_gradient( bounds: Graphene.Rect, start_point: Graphene.Point, end_point: Graphene.Point, stops: Gsk.ColorStop[] ): void; append_node(node: Gsk.RenderNode): void; append_outset_shadow( outline: Gsk.RoundedRect, color: Gdk.RGBA, dx: number, dy: number, spread: number, blur_radius: number ): void; append_radial_gradient( bounds: Graphene.Rect, center: Graphene.Point, hradius: number, vradius: number, start: number, end: number, stops: Gsk.ColorStop[] ): void; append_repeating_linear_gradient( bounds: Graphene.Rect, start_point: Graphene.Point, end_point: Graphene.Point, stops: Gsk.ColorStop[] ): void; append_repeating_radial_gradient( bounds: Graphene.Rect, center: Graphene.Point, hradius: number, vradius: number, start: number, end: number, stops: Gsk.ColorStop[] ): void; append_texture(texture: Gdk.Texture, bounds: Graphene.Rect): void; gl_shader_pop_texture(): void; perspective(depth: number): void; pop(): void; push_blend(blend_mode: Gsk.BlendMode): void; push_blur(radius: number): void; push_clip(bounds: Graphene.Rect): void; push_color_matrix( color_matrix: Graphene.Matrix, color_offset: Graphene.Vec4 ): void; push_cross_fade(progress: number): void; push_gl_shader( shader: Gsk.GLShader, bounds: Graphene.Rect, take_args: GLib.Bytes | Uint8Array ): void; push_opacity(opacity: number): void; push_repeat( bounds: Graphene.Rect, child_bounds?: Graphene.Rect | null ): void; push_rounded_clip(bounds: Gsk.RoundedRect): void; push_shadow(shadow: Gsk.Shadow, n_shadows: number): void; render_background( context: StyleContext, x: number, y: number, width: number, height: number ): void; render_focus( context: StyleContext, x: number, y: number, width: number, height: number ): void; render_frame( context: StyleContext, x: number, y: number, width: number, height: number ): void; render_insertion_cursor( context: StyleContext, x: number, y: number, layout: Pango.Layout, index: number, direction: Pango.Direction ): void; render_layout( context: StyleContext, x: number, y: number, layout: Pango.Layout ): void; restore(): void; rotate(angle: number): void; rotate_3d(angle: number, axis: Graphene.Vec3): void; save(): void; scale(factor_x: number, factor_y: number): void; scale_3d(factor_x: number, factor_y: number, factor_z: number): void; to_node(): Gsk.RenderNode; to_paintable(size?: Graphene.Size | null): Gdk.Paintable; transform(transform?: Gsk.Transform | null): void; transform_matrix(matrix: Graphene.Matrix): void; translate(point: Graphene.Point): void; translate_3d(point: Graphene.Point3D): void; } export namespace SortListModel { export interface ConstructorProperties< A extends GObject.Object = GObject.Object > extends GObject.Object.ConstructorProperties { [key: string]: any; incremental: boolean; model: Gio.ListModel; pending: number; sorter: Sorter; } } export class SortListModel<A extends GObject.Object = GObject.Object> extends GObject.Object implements Gio.ListModel<A> { static $gtype: GObject.GType<SortListModel>; constructor( properties?: Partial<SortListModel.ConstructorProperties<A>>, ...args: any[] ); _init( properties?: Partial<SortListModel.ConstructorProperties<A>>, ...args: any[] ): void; // Properties incremental: boolean; model: Gio.ListModel; pending: number; sorter: Sorter; // Constructors static ['new']( model?: Gio.ListModel | null, sorter?: Sorter | null ): SortListModel; // Members get_incremental(): boolean; get_model(): Gio.ListModel | null; get_pending(): number; get_sorter(): Sorter | null; set_incremental(incremental: boolean): void; set_model(model?: Gio.ListModel | null): void; set_sorter(sorter?: Sorter | null): void; // Implemented Members get_item_type(): GObject.GType; get_n_items(): number; get_item(position: number): A | null; items_changed(position: number, removed: number, added: number): void; vfunc_get_item(position: number): A | null; vfunc_get_item_type(): GObject.GType; vfunc_get_n_items(): number; } export namespace Sorter { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class Sorter extends GObject.Object { static $gtype: GObject.GType<Sorter>; constructor( properties?: Partial<Sorter.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Sorter.ConstructorProperties>, ...args: any[] ): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'changed', callback: (_source: this, change: SorterChange) => void ): number; connect_after( signal: 'changed', callback: (_source: this, change: SorterChange) => void ): number; emit(signal: 'changed', change: SorterChange): void; // Members changed(change: SorterChange): void; compare(item1: GObject.Object, item2: GObject.Object): Ordering; get_order(): SorterOrder; vfunc_compare( item1?: GObject.Object | null, item2?: GObject.Object | null ): Ordering; vfunc_get_order(): SorterOrder; } export namespace SpinButton { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; adjustment: Adjustment; climb_rate: number; climbRate: number; digits: number; numeric: boolean; snap_to_ticks: boolean; snapToTicks: boolean; update_policy: SpinButtonUpdatePolicy; updatePolicy: SpinButtonUpdatePolicy; value: number; wrap: boolean; } } export class SpinButton extends Widget implements Accessible, Buildable, CellEditable, ConstraintTarget, Editable, Orientable { static $gtype: GObject.GType<SpinButton>; constructor( properties?: Partial<SpinButton.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<SpinButton.ConstructorProperties>, ...args: any[] ): void; // Properties adjustment: Adjustment; climb_rate: number; climbRate: number; digits: number; numeric: boolean; snap_to_ticks: boolean; snapToTicks: boolean; update_policy: SpinButtonUpdatePolicy; updatePolicy: SpinButtonUpdatePolicy; value: number; wrap: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'change-value', callback: (_source: this, scroll: ScrollType) => void ): number; connect_after( signal: 'change-value', callback: (_source: this, scroll: ScrollType) => void ): number; emit(signal: 'change-value', scroll: ScrollType): void; connect( signal: 'input', callback: (_source: this, new_value: number) => number ): number; connect_after( signal: 'input', callback: (_source: this, new_value: number) => number ): number; emit(signal: 'input', new_value: number): void; connect(signal: 'output', callback: (_source: this) => boolean): number; connect_after( signal: 'output', callback: (_source: this) => boolean ): number; emit(signal: 'output'): void; connect(signal: 'value-changed', callback: (_source: this) => void): number; connect_after( signal: 'value-changed', callback: (_source: this) => void ): number; emit(signal: 'value-changed'): void; connect(signal: 'wrapped', callback: (_source: this) => void): number; connect_after(signal: 'wrapped', callback: (_source: this) => void): number; emit(signal: 'wrapped'): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; editing_canceled: boolean; editingCanceled: boolean; cursor_position: number; cursorPosition: number; editable: boolean; enable_undo: boolean; enableUndo: boolean; max_width_chars: number; maxWidthChars: number; selection_bound: number; selectionBound: number; text: string; width_chars: number; widthChars: number; xalign: number; orientation: Orientation; // Constructors static ['new']( adjustment: Adjustment | null, climb_rate: number, digits: number ): SpinButton; static new_with_range(min: number, max: number, step: number): SpinButton; // Members configure( adjustment: Adjustment | null, climb_rate: number, digits: number ): void; get_adjustment(): Adjustment; get_climb_rate(): number; get_digits(): number; get_increments(): [number | null, number | null]; get_numeric(): boolean; get_range(): [number | null, number | null]; get_snap_to_ticks(): boolean; get_update_policy(): SpinButtonUpdatePolicy; get_value(): number; get_value_as_int(): number; get_wrap(): boolean; set_adjustment(adjustment: Adjustment): void; set_climb_rate(climb_rate: number): void; set_digits(digits: number): void; set_increments(step: number, page: number): void; set_numeric(numeric: boolean): void; set_range(min: number, max: number): void; set_snap_to_ticks(snap_to_ticks: boolean): void; set_update_policy(policy: SpinButtonUpdatePolicy): void; set_value(value: number): void; set_wrap(wrap: boolean): void; spin(direction: SpinType, increment: number): void; update(): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; editing_done(): void; remove_widget(): void; start_editing(event?: Gdk.Event | null): void; vfunc_editing_done(): void; vfunc_remove_widget(): void; vfunc_start_editing(event?: Gdk.Event | null): void; delete_selection(): void; delete_text(start_pos: number, end_pos: number): void; finish_delegate(): void; get_alignment(): number; get_chars(start_pos: number, end_pos: number): string; get_delegate(): Editable | null; get_editable(): boolean; get_enable_undo(): boolean; get_max_width_chars(): number; get_position(): number; get_selection_bounds(): [boolean, number | null, number | null]; get_text(): string; get_width_chars(): number; init_delegate(): void; insert_text(text: string, length: number, position: number): number; select_region(start_pos: number, end_pos: number): void; set_alignment(xalign: number): void; set_editable(is_editable: boolean): void; set_enable_undo(enable_undo: boolean): void; set_max_width_chars(n_chars: number): void; set_position(position: number): void; set_text(text: string): void; set_width_chars(n_chars: number): void; vfunc_changed(): void; vfunc_delete_text(start_pos: number, end_pos: number): void; vfunc_do_delete_text(start_pos: number, end_pos: number): void; vfunc_do_insert_text( text: string, length: number, position: number ): number; vfunc_get_delegate(): Editable | null; vfunc_get_selection_bounds(): [boolean, number | null, number | null]; vfunc_get_text(): string; vfunc_insert_text(text: string, length: number, position: number): number; vfunc_set_selection_bounds(start_pos: number, end_pos: number): void; get_orientation(): Orientation; set_orientation(orientation: Orientation): void; } export namespace Spinner { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; spinning: boolean; } } export class Spinner extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<Spinner>; constructor( properties?: Partial<Spinner.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Spinner.ConstructorProperties>, ...args: any[] ): void; // Properties spinning: boolean; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](): Spinner; // Members get_spinning(): boolean; set_spinning(spinning: boolean): void; start(): void; stop(): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace Stack { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; hhomogeneous: boolean; interpolate_size: boolean; interpolateSize: boolean; pages: SelectionModel; transition_duration: number; transitionDuration: number; transition_running: boolean; transitionRunning: boolean; transition_type: StackTransitionType; transitionType: StackTransitionType; vhomogeneous: boolean; visible_child: Widget; visibleChild: Widget; visible_child_name: string; visibleChildName: string; } } export class Stack extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<Stack>; constructor( properties?: Partial<Stack.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Stack.ConstructorProperties>, ...args: any[] ): void; // Properties hhomogeneous: boolean; interpolate_size: boolean; interpolateSize: boolean; pages: SelectionModel; transition_duration: number; transitionDuration: number; transition_running: boolean; transitionRunning: boolean; transition_type: StackTransitionType; transitionType: StackTransitionType; vhomogeneous: boolean; visible_child: Widget; visibleChild: Widget; visible_child_name: string; visibleChildName: string; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](): Stack; // Members add_child(child: Widget): StackPage; add_named(child: Widget, name?: string | null): StackPage; add_titled(child: Widget, name: string | null, title: string): StackPage; get_child_by_name(name: string): Widget | null; get_hhomogeneous(): boolean; get_interpolate_size(): boolean; get_page(child: Widget): StackPage; get_pages(): SelectionModel; get_transition_duration(): number; get_transition_running(): boolean; get_transition_type(): StackTransitionType; get_vhomogeneous(): boolean; get_visible_child(): Widget | null; get_visible_child_name(): string | null; remove(child: Widget): void; set_hhomogeneous(hhomogeneous: boolean): void; set_interpolate_size(interpolate_size: boolean): void; set_transition_duration(duration: number): void; set_transition_type(transition: StackTransitionType): void; set_vhomogeneous(vhomogeneous: boolean): void; set_visible_child(child: Widget): void; set_visible_child_full(name: string, transition: StackTransitionType): void; set_visible_child_name(name: string): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace StackPage { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; child: Widget; icon_name: string; iconName: string; name: string; needs_attention: boolean; needsAttention: boolean; title: string; use_underline: boolean; useUnderline: boolean; visible: boolean; } } export class StackPage extends GObject.Object implements Accessible { static $gtype: GObject.GType<StackPage>; constructor( properties?: Partial<StackPage.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<StackPage.ConstructorProperties>, ...args: any[] ): void; // Properties child: Widget; icon_name: string; iconName: string; name: string; needs_attention: boolean; needsAttention: boolean; title: string; use_underline: boolean; useUnderline: boolean; visible: boolean; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Members get_child(): Widget; get_icon_name(): string | null; get_name(): string | null; get_needs_attention(): boolean; get_title(): string | null; get_use_underline(): boolean; get_visible(): boolean; set_icon_name(setting: string): void; set_name(setting: string): void; set_needs_attention(setting: boolean): void; set_title(setting: string): void; set_use_underline(setting: boolean): void; set_visible(visible: boolean): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; } export namespace StackSidebar { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; stack: Stack; } } export class StackSidebar extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<StackSidebar>; constructor( properties?: Partial<StackSidebar.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<StackSidebar.ConstructorProperties>, ...args: any[] ): void; // Properties stack: Stack; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](): StackSidebar; // Members get_stack(): Stack | null; set_stack(stack: Stack): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace StackSwitcher { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; stack: Stack; } } export class StackSwitcher extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<StackSwitcher>; constructor( properties?: Partial<StackSwitcher.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<StackSwitcher.ConstructorProperties>, ...args: any[] ): void; // Properties stack: Stack; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](): StackSwitcher; // Members get_stack(): Stack | null; set_stack(stack?: Stack | null): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace Statusbar { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; } } export class Statusbar extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<Statusbar>; constructor( properties?: Partial<Statusbar.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Statusbar.ConstructorProperties>, ...args: any[] ): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'text-popped', callback: (_source: this, context_id: number, text: string) => void ): number; connect_after( signal: 'text-popped', callback: (_source: this, context_id: number, text: string) => void ): number; emit(signal: 'text-popped', context_id: number, text: string): void; connect( signal: 'text-pushed', callback: (_source: this, context_id: number, text: string) => void ): number; connect_after( signal: 'text-pushed', callback: (_source: this, context_id: number, text: string) => void ): number; emit(signal: 'text-pushed', context_id: number, text: string): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](): Statusbar; // Members get_context_id(context_description: string): number; pop(context_id: number): void; push(context_id: number, text: string): number; remove(context_id: number, message_id: number): void; remove_all(context_id: number): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace StringFilter { export interface ConstructorProperties extends Filter.ConstructorProperties { [key: string]: any; expression: Expression; ignore_case: boolean; ignoreCase: boolean; match_mode: StringFilterMatchMode; matchMode: StringFilterMatchMode; search: string; } } export class StringFilter extends Filter { static $gtype: GObject.GType<StringFilter>; constructor( properties?: Partial<StringFilter.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<StringFilter.ConstructorProperties>, ...args: any[] ): void; // Properties expression: Expression; ignore_case: boolean; ignoreCase: boolean; match_mode: StringFilterMatchMode; matchMode: StringFilterMatchMode; search: string; // Constructors static ['new'](expression?: Expression | null): StringFilter; // Members get_expression(): Expression; get_ignore_case(): boolean; get_match_mode(): StringFilterMatchMode; get_search(): string | null; set_expression(expression: Expression): void; set_ignore_case(ignore_case: boolean): void; set_match_mode(mode: StringFilterMatchMode): void; set_search(search?: string | null): void; } export namespace StringList { export interface ConstructorProperties< A extends GObject.Object = GObject.Object > extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class StringList<A extends GObject.Object = GObject.Object> extends GObject.Object implements Gio.ListModel<A>, Buildable { static $gtype: GObject.GType<StringList>; constructor( properties?: Partial<StringList.ConstructorProperties<A>>, ...args: any[] ); _init( properties?: Partial<StringList.ConstructorProperties<A>>, ...args: any[] ): void; // Constructors static ['new'](strings?: string[] | null): StringList; // Members append(string: string): void; get_string(position: number): string | null; remove(position: number): void; splice( position: number, n_removals: number, additions?: string[] | null ): void; take(string: string): void; // Implemented Members get_item_type(): GObject.GType; get_n_items(): number; get_item(position: number): A | null; items_changed(position: number, removed: number, added: number): void; vfunc_get_item(position: number): A | null; vfunc_get_item_type(): GObject.GType; vfunc_get_n_items(): number; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace StringObject { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; string: string; } } export class StringObject extends GObject.Object { static $gtype: GObject.GType<StringObject>; constructor( properties?: Partial<StringObject.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<StringObject.ConstructorProperties>, ...args: any[] ): void; // Properties string: string; // Constructors static ['new'](string: string): StringObject; // Members get_string(): string; } export namespace StringSorter { export interface ConstructorProperties extends Sorter.ConstructorProperties { [key: string]: any; expression: Expression; ignore_case: boolean; ignoreCase: boolean; } } export class StringSorter extends Sorter { static $gtype: GObject.GType<StringSorter>; constructor( properties?: Partial<StringSorter.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<StringSorter.ConstructorProperties>, ...args: any[] ): void; // Properties expression: Expression; ignore_case: boolean; ignoreCase: boolean; // Constructors static ['new'](expression?: Expression | null): StringSorter; // Members get_expression(): Expression | null; get_ignore_case(): boolean; set_expression(expression?: Expression | null): void; set_ignore_case(ignore_case: boolean): void; } export namespace StyleContext { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; display: Gdk.Display; } } export class StyleContext extends GObject.Object { static $gtype: GObject.GType<StyleContext>; constructor( properties?: Partial<StyleContext.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<StyleContext.ConstructorProperties>, ...args: any[] ): void; // Properties display: Gdk.Display; // Fields parent_object: GObject.Object; // Members add_class(class_name: string): void; add_provider(provider: StyleProvider, priority: number): void; get_border(): Border; get_color(): Gdk.RGBA; get_display(): Gdk.Display; get_margin(): Border; get_padding(): Border; get_scale(): number; get_state(): StateFlags; has_class(class_name: string): boolean; lookup_color(color_name: string): [boolean, Gdk.RGBA]; remove_class(class_name: string): void; remove_provider(provider: StyleProvider): void; restore(): void; save(): void; set_display(display: Gdk.Display): void; set_scale(scale: number): void; set_state(flags: StateFlags): void; to_string(flags: StyleContextPrintFlags): string; vfunc_changed(): void; static add_provider_for_display( display: Gdk.Display, provider: StyleProvider, priority: number ): void; static remove_provider_for_display( display: Gdk.Display, provider: StyleProvider ): void; } export namespace Switch { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; active: boolean; state: boolean; } } export class Switch extends Widget implements Accessible, Actionable, Buildable, ConstraintTarget { static $gtype: GObject.GType<Switch>; constructor( properties?: Partial<Switch.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Switch.ConstructorProperties>, ...args: any[] ): void; // Properties active: boolean; state: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'activate', callback: (_source: this) => void): number; connect_after( signal: 'activate', callback: (_source: this) => void ): number; emit(signal: 'activate'): void; connect( signal: 'state-set', callback: (_source: this, state: boolean) => boolean ): number; connect_after( signal: 'state-set', callback: (_source: this, state: boolean) => boolean ): number; emit(signal: 'state-set', state: boolean): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; action_name: string; actionName: string; action_target: GLib.Variant; actionTarget: GLib.Variant; // Constructors static ['new'](): Switch; // Members get_active(): boolean; get_state(): boolean; set_active(is_active: boolean): void; set_state(state: boolean): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_action_name(): string | null; get_action_target_value(): GLib.Variant | null; set_action_name(action_name?: string | null): void; set_action_target_value(target_value?: GLib.Variant | null): void; set_detailed_action_name(detailed_action_name: string): void; vfunc_get_action_name(): string | null; vfunc_get_action_target_value(): GLib.Variant | null; vfunc_set_action_name(action_name?: string | null): void; vfunc_set_action_target_value(target_value?: GLib.Variant | null): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace Text { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; activates_default: boolean; activatesDefault: boolean; attributes: Pango.AttrList; buffer: EntryBuffer; enable_emoji_completion: boolean; enableEmojiCompletion: boolean; extra_menu: Gio.MenuModel; extraMenu: Gio.MenuModel; im_module: string; imModule: string; input_hints: InputHints; inputHints: InputHints; input_purpose: InputPurpose; inputPurpose: InputPurpose; invisible_char: number; invisibleChar: number; invisible_char_set: boolean; invisibleCharSet: boolean; max_length: number; maxLength: number; overwrite_mode: boolean; overwriteMode: boolean; placeholder_text: string; placeholderText: string; propagate_text_width: boolean; propagateTextWidth: boolean; scroll_offset: number; scrollOffset: number; tabs: Pango.TabArray; truncate_multiline: boolean; truncateMultiline: boolean; visibility: boolean; } } export class Text extends Widget implements Accessible, Buildable, ConstraintTarget, Editable { static $gtype: GObject.GType<Text>; constructor( properties?: Partial<Text.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Text.ConstructorProperties>, ...args: any[] ): void; // Properties activates_default: boolean; activatesDefault: boolean; attributes: Pango.AttrList; buffer: EntryBuffer; enable_emoji_completion: boolean; enableEmojiCompletion: boolean; extra_menu: Gio.MenuModel; extraMenu: Gio.MenuModel; im_module: string; imModule: string; input_hints: InputHints; inputHints: InputHints; input_purpose: InputPurpose; inputPurpose: InputPurpose; invisible_char: number; invisibleChar: number; invisible_char_set: boolean; invisibleCharSet: boolean; max_length: number; maxLength: number; overwrite_mode: boolean; overwriteMode: boolean; placeholder_text: string; placeholderText: string; propagate_text_width: boolean; propagateTextWidth: boolean; scroll_offset: number; scrollOffset: number; tabs: Pango.TabArray; truncate_multiline: boolean; truncateMultiline: boolean; visibility: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'activate', callback: (_source: this) => void): number; connect_after( signal: 'activate', callback: (_source: this) => void ): number; emit(signal: 'activate'): void; connect(signal: 'backspace', callback: (_source: this) => void): number; connect_after( signal: 'backspace', callback: (_source: this) => void ): number; emit(signal: 'backspace'): void; connect( signal: 'copy-clipboard', callback: (_source: this) => void ): number; connect_after( signal: 'copy-clipboard', callback: (_source: this) => void ): number; emit(signal: 'copy-clipboard'): void; connect(signal: 'cut-clipboard', callback: (_source: this) => void): number; connect_after( signal: 'cut-clipboard', callback: (_source: this) => void ): number; emit(signal: 'cut-clipboard'): void; connect( signal: 'delete-from-cursor', callback: (_source: this, type: DeleteType, count: number) => void ): number; connect_after( signal: 'delete-from-cursor', callback: (_source: this, type: DeleteType, count: number) => void ): number; emit(signal: 'delete-from-cursor', type: DeleteType, count: number): void; connect( signal: 'insert-at-cursor', callback: (_source: this, string: string) => void ): number; connect_after( signal: 'insert-at-cursor', callback: (_source: this, string: string) => void ): number; emit(signal: 'insert-at-cursor', string: string): void; connect(signal: 'insert-emoji', callback: (_source: this) => void): number; connect_after( signal: 'insert-emoji', callback: (_source: this) => void ): number; emit(signal: 'insert-emoji'): void; connect( signal: 'move-cursor', callback: ( _source: this, step: MovementStep, count: number, extend: boolean ) => void ): number; connect_after( signal: 'move-cursor', callback: ( _source: this, step: MovementStep, count: number, extend: boolean ) => void ): number; emit( signal: 'move-cursor', step: MovementStep, count: number, extend: boolean ): void; connect( signal: 'paste-clipboard', callback: (_source: this) => void ): number; connect_after( signal: 'paste-clipboard', callback: (_source: this) => void ): number; emit(signal: 'paste-clipboard'): void; connect( signal: 'preedit-changed', callback: (_source: this, preedit: string) => void ): number; connect_after( signal: 'preedit-changed', callback: (_source: this, preedit: string) => void ): number; emit(signal: 'preedit-changed', preedit: string): void; connect( signal: 'toggle-overwrite', callback: (_source: this) => void ): number; connect_after( signal: 'toggle-overwrite', callback: (_source: this) => void ): number; emit(signal: 'toggle-overwrite'): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; cursor_position: number; cursorPosition: number; editable: boolean; enable_undo: boolean; enableUndo: boolean; max_width_chars: number; maxWidthChars: number; selection_bound: number; selectionBound: number; text: string; width_chars: number; widthChars: number; xalign: number; // Constructors static ['new'](): Text; static new_with_buffer(buffer: EntryBuffer): Text; // Members get_activates_default(): boolean; get_attributes(): Pango.AttrList | null; get_buffer(): EntryBuffer; get_enable_emoji_completion(): boolean; get_extra_menu(): Gio.MenuModel | null; get_input_hints(): InputHints; get_input_purpose(): InputPurpose; get_invisible_char(): number; get_max_length(): number; get_overwrite_mode(): boolean; get_placeholder_text(): string | null; get_propagate_text_width(): boolean; get_tabs(): Pango.TabArray | null; get_text_length(): number; get_truncate_multiline(): boolean; get_visibility(): boolean; grab_focus_without_selecting(): boolean; set_activates_default(activates: boolean): void; set_attributes(attrs?: Pango.AttrList | null): void; set_buffer(buffer: EntryBuffer): void; set_enable_emoji_completion(enable_emoji_completion: boolean): void; set_extra_menu(model?: Gio.MenuModel | null): void; set_input_hints(hints: InputHints): void; set_input_purpose(purpose: InputPurpose): void; set_invisible_char(ch: number): void; set_max_length(length: number): void; set_overwrite_mode(overwrite: boolean): void; set_placeholder_text(text?: string | null): void; set_propagate_text_width(propagate_text_width: boolean): void; set_tabs(tabs?: Pango.TabArray | null): void; set_truncate_multiline(truncate_multiline: boolean): void; set_visibility(visible: boolean): void; unset_invisible_char(): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; delete_selection(): void; delete_text(start_pos: number, end_pos: number): void; finish_delegate(): void; get_alignment(): number; get_chars(start_pos: number, end_pos: number): string; get_delegate(): Editable | null; get_editable(): boolean; get_enable_undo(): boolean; get_max_width_chars(): number; get_position(): number; get_selection_bounds(): [boolean, number | null, number | null]; get_text(): string; get_width_chars(): number; init_delegate(): void; insert_text(text: string, length: number, position: number): number; select_region(start_pos: number, end_pos: number): void; set_alignment(xalign: number): void; set_editable(is_editable: boolean): void; set_enable_undo(enable_undo: boolean): void; set_max_width_chars(n_chars: number): void; set_position(position: number): void; set_text(text: string): void; set_width_chars(n_chars: number): void; vfunc_changed(): void; vfunc_delete_text(start_pos: number, end_pos: number): void; vfunc_do_delete_text(start_pos: number, end_pos: number): void; vfunc_do_insert_text( text: string, length: number, position: number ): number; vfunc_get_delegate(): Editable | null; vfunc_get_selection_bounds(): [boolean, number | null, number | null]; vfunc_get_text(): string; vfunc_insert_text(text: string, length: number, position: number): number; vfunc_set_selection_bounds(start_pos: number, end_pos: number): void; } export namespace TextBuffer { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; can_redo: boolean; canRedo: boolean; can_undo: boolean; canUndo: boolean; cursor_position: number; cursorPosition: number; enable_undo: boolean; enableUndo: boolean; has_selection: boolean; hasSelection: boolean; tag_table: TextTagTable; tagTable: TextTagTable; text: string; } } export class TextBuffer extends GObject.Object { static $gtype: GObject.GType<TextBuffer>; constructor( properties?: Partial<TextBuffer.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<TextBuffer.ConstructorProperties>, ...args: any[] ): void; // Properties can_redo: boolean; canRedo: boolean; can_undo: boolean; canUndo: boolean; cursor_position: number; cursorPosition: number; enable_undo: boolean; enableUndo: boolean; has_selection: boolean; hasSelection: boolean; tag_table: TextTagTable; tagTable: TextTagTable; text: string; // Fields priv: TextBufferPrivate; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'apply-tag', callback: ( _source: this, tag: TextTag, start: TextIter, end: TextIter ) => void ): number; connect_after( signal: 'apply-tag', callback: ( _source: this, tag: TextTag, start: TextIter, end: TextIter ) => void ): number; emit( signal: 'apply-tag', tag: TextTag, start: TextIter, end: TextIter ): void; connect( signal: 'begin-user-action', callback: (_source: this) => void ): number; connect_after( signal: 'begin-user-action', callback: (_source: this) => void ): number; emit(signal: 'begin-user-action'): void; connect(signal: 'changed', callback: (_source: this) => void): number; connect_after(signal: 'changed', callback: (_source: this) => void): number; emit(signal: 'changed'): void; connect( signal: 'delete-range', callback: (_source: this, start: TextIter, end: TextIter) => void ): number; connect_after( signal: 'delete-range', callback: (_source: this, start: TextIter, end: TextIter) => void ): number; emit(signal: 'delete-range', start: TextIter, end: TextIter): void; connect( signal: 'end-user-action', callback: (_source: this) => void ): number; connect_after( signal: 'end-user-action', callback: (_source: this) => void ): number; emit(signal: 'end-user-action'): void; connect( signal: 'insert-child-anchor', callback: ( _source: this, location: TextIter, anchor: TextChildAnchor ) => void ): number; connect_after( signal: 'insert-child-anchor', callback: ( _source: this, location: TextIter, anchor: TextChildAnchor ) => void ): number; emit( signal: 'insert-child-anchor', location: TextIter, anchor: TextChildAnchor ): void; connect( signal: 'insert-paintable', callback: ( _source: this, location: TextIter, paintable: Gdk.Paintable ) => void ): number; connect_after( signal: 'insert-paintable', callback: ( _source: this, location: TextIter, paintable: Gdk.Paintable ) => void ): number; emit( signal: 'insert-paintable', location: TextIter, paintable: Gdk.Paintable ): void; connect( signal: 'insert-text', callback: ( _source: this, location: TextIter, text: string, len: number ) => void ): number; connect_after( signal: 'insert-text', callback: ( _source: this, location: TextIter, text: string, len: number ) => void ): number; emit( signal: 'insert-text', location: TextIter, text: string, len: number ): void; connect( signal: 'mark-deleted', callback: (_source: this, mark: TextMark) => void ): number; connect_after( signal: 'mark-deleted', callback: (_source: this, mark: TextMark) => void ): number; emit(signal: 'mark-deleted', mark: TextMark): void; connect( signal: 'mark-set', callback: (_source: this, location: TextIter, mark: TextMark) => void ): number; connect_after( signal: 'mark-set', callback: (_source: this, location: TextIter, mark: TextMark) => void ): number; emit(signal: 'mark-set', location: TextIter, mark: TextMark): void; connect( signal: 'modified-changed', callback: (_source: this) => void ): number; connect_after( signal: 'modified-changed', callback: (_source: this) => void ): number; emit(signal: 'modified-changed'): void; connect( signal: 'paste-done', callback: (_source: this, clipboard: Gdk.Clipboard) => void ): number; connect_after( signal: 'paste-done', callback: (_source: this, clipboard: Gdk.Clipboard) => void ): number; emit(signal: 'paste-done', clipboard: Gdk.Clipboard): void; connect(signal: 'redo', callback: (_source: this) => void): number; connect_after(signal: 'redo', callback: (_source: this) => void): number; emit(signal: 'redo'): void; connect( signal: 'remove-tag', callback: ( _source: this, tag: TextTag, start: TextIter, end: TextIter ) => void ): number; connect_after( signal: 'remove-tag', callback: ( _source: this, tag: TextTag, start: TextIter, end: TextIter ) => void ): number; emit( signal: 'remove-tag', tag: TextTag, start: TextIter, end: TextIter ): void; connect(signal: 'undo', callback: (_source: this) => void): number; connect_after(signal: 'undo', callback: (_source: this) => void): number; emit(signal: 'undo'): void; // Constructors static ['new'](table?: TextTagTable | null): TextBuffer; // Members add_mark(mark: TextMark, where: TextIter): void; add_selection_clipboard(clipboard: Gdk.Clipboard): void; apply_tag(tag: TextTag, start: TextIter, end: TextIter): void; apply_tag_by_name(name: string, start: TextIter, end: TextIter): void; backspace( iter: TextIter, interactive: boolean, default_editable: boolean ): boolean; begin_irreversible_action(): void; begin_user_action(): void; copy_clipboard(clipboard: Gdk.Clipboard): void; create_child_anchor(iter: TextIter): TextChildAnchor; create_mark( mark_name: string | null, where: TextIter, left_gravity: boolean ): TextMark; cut_clipboard(clipboard: Gdk.Clipboard, default_editable: boolean): void; ['delete'](start: TextIter, end: TextIter): void; delete_interactive( start_iter: TextIter, end_iter: TextIter, default_editable: boolean ): boolean; delete_mark(mark: TextMark): void; delete_mark_by_name(name: string): void; delete_selection(interactive: boolean, default_editable: boolean): boolean; end_irreversible_action(): void; end_user_action(): void; get_bounds(): [TextIter, TextIter]; get_can_redo(): boolean; get_can_undo(): boolean; get_char_count(): number; get_enable_undo(): boolean; get_end_iter(): TextIter; get_has_selection(): boolean; get_insert(): TextMark; get_iter_at_child_anchor(anchor: TextChildAnchor): TextIter; get_iter_at_line(line_number: number): [boolean, TextIter]; get_iter_at_line_index( line_number: number, byte_index: number ): [boolean, TextIter]; get_iter_at_line_offset( line_number: number, char_offset: number ): [boolean, TextIter]; get_iter_at_mark(mark: TextMark): TextIter; get_iter_at_offset(char_offset: number): TextIter; get_line_count(): number; get_mark(name: string): TextMark | null; get_max_undo_levels(): number; get_modified(): boolean; get_selection_bound(): TextMark; get_selection_bounds(): [boolean, TextIter, TextIter]; get_selection_content(): Gdk.ContentProvider; get_slice( start: TextIter, end: TextIter, include_hidden_chars: boolean ): string; get_start_iter(): TextIter; get_tag_table(): TextTagTable; get_text( start: TextIter, end: TextIter, include_hidden_chars: boolean ): string; insert(iter: TextIter, text: string, len: number): void; insert_at_cursor(text: string, len: number): void; insert_child_anchor(iter: TextIter, anchor: TextChildAnchor): void; insert_interactive( iter: TextIter, text: string, len: number, default_editable: boolean ): boolean; insert_interactive_at_cursor( text: string, len: number, default_editable: boolean ): boolean; insert_markup(iter: TextIter, markup: string, len: number): void; insert_paintable(iter: TextIter, paintable: Gdk.Paintable): void; insert_range(iter: TextIter, start: TextIter, end: TextIter): void; insert_range_interactive( iter: TextIter, start: TextIter, end: TextIter, default_editable: boolean ): boolean; move_mark(mark: TextMark, where: TextIter): void; move_mark_by_name(name: string, where: TextIter): void; paste_clipboard( clipboard: Gdk.Clipboard, override_location: TextIter | null, default_editable: boolean ): void; place_cursor(where: TextIter): void; redo(): void; remove_all_tags(start: TextIter, end: TextIter): void; remove_selection_clipboard(clipboard: Gdk.Clipboard): void; remove_tag(tag: TextTag, start: TextIter, end: TextIter): void; remove_tag_by_name(name: string, start: TextIter, end: TextIter): void; select_range(ins: TextIter, bound: TextIter): void; set_enable_undo(enable_undo: boolean): void; set_max_undo_levels(max_undo_levels: number): void; set_modified(setting: boolean): void; set_text(text: string, len: number): void; undo(): void; vfunc_apply_tag(tag: TextTag, start: TextIter, end: TextIter): void; vfunc_begin_user_action(): void; vfunc_changed(): void; vfunc_delete_range(start: TextIter, end: TextIter): void; vfunc_end_user_action(): void; vfunc_insert_child_anchor(iter: TextIter, anchor: TextChildAnchor): void; vfunc_insert_paintable(iter: TextIter, paintable: Gdk.Paintable): void; vfunc_insert_text( pos: TextIter, new_text: string, new_text_length: number ): void; vfunc_mark_deleted(mark: TextMark): void; vfunc_mark_set(location: TextIter, mark: TextMark): void; vfunc_modified_changed(): void; vfunc_paste_done(clipboard: Gdk.Clipboard): void; vfunc_redo(): void; vfunc_remove_tag(tag: TextTag, start: TextIter, end: TextIter): void; vfunc_undo(): void; } export namespace TextChildAnchor { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class TextChildAnchor extends GObject.Object { static $gtype: GObject.GType<TextChildAnchor>; constructor( properties?: Partial<TextChildAnchor.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<TextChildAnchor.ConstructorProperties>, ...args: any[] ): void; // Constructors static ['new'](): TextChildAnchor; // Members get_deleted(): boolean; get_widgets(): Widget[]; } export namespace TextMark { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; left_gravity: boolean; leftGravity: boolean; name: string; } } export class TextMark extends GObject.Object { static $gtype: GObject.GType<TextMark>; constructor( properties?: Partial<TextMark.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<TextMark.ConstructorProperties>, ...args: any[] ): void; // Properties left_gravity: boolean; leftGravity: boolean; name: string; // Constructors static ['new'](name: string | null, left_gravity: boolean): TextMark; // Members get_buffer(): TextBuffer; get_deleted(): boolean; get_left_gravity(): boolean; get_name(): string | null; get_visible(): boolean; set_visible(setting: boolean): void; } export namespace TextTag { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; accumulative_margin: boolean; accumulativeMargin: boolean; allow_breaks: boolean; allowBreaks: boolean; allow_breaks_set: boolean; allowBreaksSet: boolean; background: string; background_full_height: boolean; backgroundFullHeight: boolean; background_full_height_set: boolean; backgroundFullHeightSet: boolean; background_rgba: Gdk.RGBA; backgroundRgba: Gdk.RGBA; background_set: boolean; backgroundSet: boolean; direction: TextDirection; editable: boolean; editable_set: boolean; editableSet: boolean; fallback: boolean; fallback_set: boolean; fallbackSet: boolean; family: string; family_set: boolean; familySet: boolean; font: string; font_desc: Pango.FontDescription; fontDesc: Pango.FontDescription; font_features: string; fontFeatures: string; font_features_set: boolean; fontFeaturesSet: boolean; foreground: string; foreground_rgba: Gdk.RGBA; foregroundRgba: Gdk.RGBA; foreground_set: boolean; foregroundSet: boolean; indent: number; indent_set: boolean; indentSet: boolean; insert_hyphens: boolean; insertHyphens: boolean; insert_hyphens_set: boolean; insertHyphensSet: boolean; invisible: boolean; invisible_set: boolean; invisibleSet: boolean; justification: Justification; justification_set: boolean; justificationSet: boolean; language: string; language_set: boolean; languageSet: boolean; left_margin: number; leftMargin: number; left_margin_set: boolean; leftMarginSet: boolean; letter_spacing: number; letterSpacing: number; letter_spacing_set: boolean; letterSpacingSet: boolean; name: string; overline: Pango.Overline; overline_rgba: Gdk.RGBA; overlineRgba: Gdk.RGBA; overline_rgba_set: boolean; overlineRgbaSet: boolean; overline_set: boolean; overlineSet: boolean; paragraph_background: string; paragraphBackground: string; paragraph_background_rgba: Gdk.RGBA; paragraphBackgroundRgba: Gdk.RGBA; paragraph_background_set: boolean; paragraphBackgroundSet: boolean; pixels_above_lines: number; pixelsAboveLines: number; pixels_above_lines_set: boolean; pixelsAboveLinesSet: boolean; pixels_below_lines: number; pixelsBelowLines: number; pixels_below_lines_set: boolean; pixelsBelowLinesSet: boolean; pixels_inside_wrap: number; pixelsInsideWrap: number; pixels_inside_wrap_set: boolean; pixelsInsideWrapSet: boolean; right_margin: number; rightMargin: number; right_margin_set: boolean; rightMarginSet: boolean; rise: number; rise_set: boolean; riseSet: boolean; scale: number; scale_set: boolean; scaleSet: boolean; show_spaces: Pango.ShowFlags; showSpaces: Pango.ShowFlags; show_spaces_set: boolean; showSpacesSet: boolean; size: number; size_points: number; sizePoints: number; size_set: boolean; sizeSet: boolean; stretch: Pango.Stretch; stretch_set: boolean; stretchSet: boolean; strikethrough: boolean; strikethrough_rgba: Gdk.RGBA; strikethroughRgba: Gdk.RGBA; strikethrough_rgba_set: boolean; strikethroughRgbaSet: boolean; strikethrough_set: boolean; strikethroughSet: boolean; style: Pango.Style; style_set: boolean; styleSet: boolean; tabs: Pango.TabArray; tabs_set: boolean; tabsSet: boolean; underline: Pango.Underline; underline_rgba: Gdk.RGBA; underlineRgba: Gdk.RGBA; underline_rgba_set: boolean; underlineRgbaSet: boolean; underline_set: boolean; underlineSet: boolean; variant: Pango.Variant; variant_set: boolean; variantSet: boolean; weight: number; weight_set: boolean; weightSet: boolean; wrap_mode: WrapMode; wrapMode: WrapMode; wrap_mode_set: boolean; wrapModeSet: boolean; } } export class TextTag extends GObject.Object { static $gtype: GObject.GType<TextTag>; constructor( properties?: Partial<TextTag.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<TextTag.ConstructorProperties>, ...args: any[] ): void; // Properties accumulative_margin: boolean; accumulativeMargin: boolean; allow_breaks: boolean; allowBreaks: boolean; allow_breaks_set: boolean; allowBreaksSet: boolean; background: string; background_full_height: boolean; backgroundFullHeight: boolean; background_full_height_set: boolean; backgroundFullHeightSet: boolean; background_rgba: Gdk.RGBA; backgroundRgba: Gdk.RGBA; background_set: boolean; backgroundSet: boolean; direction: TextDirection; editable: boolean; editable_set: boolean; editableSet: boolean; fallback: boolean; fallback_set: boolean; fallbackSet: boolean; family: string; family_set: boolean; familySet: boolean; font: string; font_desc: Pango.FontDescription; fontDesc: Pango.FontDescription; font_features: string; fontFeatures: string; font_features_set: boolean; fontFeaturesSet: boolean; foreground: string; foreground_rgba: Gdk.RGBA; foregroundRgba: Gdk.RGBA; foreground_set: boolean; foregroundSet: boolean; indent: number; indent_set: boolean; indentSet: boolean; insert_hyphens: boolean; insertHyphens: boolean; insert_hyphens_set: boolean; insertHyphensSet: boolean; invisible: boolean; invisible_set: boolean; invisibleSet: boolean; justification: Justification; justification_set: boolean; justificationSet: boolean; language: string; language_set: boolean; languageSet: boolean; left_margin: number; leftMargin: number; left_margin_set: boolean; leftMarginSet: boolean; letter_spacing: number; letterSpacing: number; letter_spacing_set: boolean; letterSpacingSet: boolean; name: string; overline: Pango.Overline; overline_rgba: Gdk.RGBA; overlineRgba: Gdk.RGBA; overline_rgba_set: boolean; overlineRgbaSet: boolean; overline_set: boolean; overlineSet: boolean; paragraph_background: string; paragraphBackground: string; paragraph_background_rgba: Gdk.RGBA; paragraphBackgroundRgba: Gdk.RGBA; paragraph_background_set: boolean; paragraphBackgroundSet: boolean; pixels_above_lines: number; pixelsAboveLines: number; pixels_above_lines_set: boolean; pixelsAboveLinesSet: boolean; pixels_below_lines: number; pixelsBelowLines: number; pixels_below_lines_set: boolean; pixelsBelowLinesSet: boolean; pixels_inside_wrap: number; pixelsInsideWrap: number; pixels_inside_wrap_set: boolean; pixelsInsideWrapSet: boolean; right_margin: number; rightMargin: number; right_margin_set: boolean; rightMarginSet: boolean; rise: number; rise_set: boolean; riseSet: boolean; scale: number; scale_set: boolean; scaleSet: boolean; show_spaces: Pango.ShowFlags; showSpaces: Pango.ShowFlags; show_spaces_set: boolean; showSpacesSet: boolean; size: number; size_points: number; sizePoints: number; size_set: boolean; sizeSet: boolean; stretch: Pango.Stretch; stretch_set: boolean; stretchSet: boolean; strikethrough: boolean; strikethrough_rgba: Gdk.RGBA; strikethroughRgba: Gdk.RGBA; strikethrough_rgba_set: boolean; strikethroughRgbaSet: boolean; strikethrough_set: boolean; strikethroughSet: boolean; style: Pango.Style; style_set: boolean; styleSet: boolean; tabs: Pango.TabArray; tabs_set: boolean; tabsSet: boolean; underline: Pango.Underline; underline_rgba: Gdk.RGBA; underlineRgba: Gdk.RGBA; underline_rgba_set: boolean; underlineRgbaSet: boolean; underline_set: boolean; underlineSet: boolean; variant: Pango.Variant; variant_set: boolean; variantSet: boolean; weight: number; weight_set: boolean; weightSet: boolean; wrap_mode: WrapMode; wrapMode: WrapMode; wrap_mode_set: boolean; wrapModeSet: boolean; // Fields priv: TextTagPrivate; // Constructors static ['new'](name?: string | null): TextTag; // Members changed(size_changed: boolean): void; get_priority(): number; set_priority(priority: number): void; } export namespace TextTagTable { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class TextTagTable extends GObject.Object implements Buildable { static $gtype: GObject.GType<TextTagTable>; constructor( properties?: Partial<TextTagTable.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<TextTagTable.ConstructorProperties>, ...args: any[] ): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'tag-added', callback: (_source: this, tag: TextTag) => void ): number; connect_after( signal: 'tag-added', callback: (_source: this, tag: TextTag) => void ): number; emit(signal: 'tag-added', tag: TextTag): void; connect( signal: 'tag-changed', callback: (_source: this, tag: TextTag, size_changed: boolean) => void ): number; connect_after( signal: 'tag-changed', callback: (_source: this, tag: TextTag, size_changed: boolean) => void ): number; emit(signal: 'tag-changed', tag: TextTag, size_changed: boolean): void; connect( signal: 'tag-removed', callback: (_source: this, tag: TextTag) => void ): number; connect_after( signal: 'tag-removed', callback: (_source: this, tag: TextTag) => void ): number; emit(signal: 'tag-removed', tag: TextTag): void; // Constructors static ['new'](): TextTagTable; // Members add(tag: TextTag): boolean; foreach(func: TextTagTableForeach): void; get_size(): number; lookup(name: string): TextTag | null; remove(tag: TextTag): void; // Implemented Members get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace TextView { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; accepts_tab: boolean; acceptsTab: boolean; bottom_margin: number; bottomMargin: number; buffer: TextBuffer; cursor_visible: boolean; cursorVisible: boolean; editable: boolean; extra_menu: Gio.MenuModel; extraMenu: Gio.MenuModel; im_module: string; imModule: string; indent: number; input_hints: InputHints; inputHints: InputHints; input_purpose: InputPurpose; inputPurpose: InputPurpose; justification: Justification; left_margin: number; leftMargin: number; monospace: boolean; overwrite: boolean; pixels_above_lines: number; pixelsAboveLines: number; pixels_below_lines: number; pixelsBelowLines: number; pixels_inside_wrap: number; pixelsInsideWrap: number; right_margin: number; rightMargin: number; tabs: Pango.TabArray; top_margin: number; topMargin: number; wrap_mode: WrapMode; wrapMode: WrapMode; } } export class TextView extends Widget implements Accessible, Buildable, ConstraintTarget, Scrollable { static $gtype: GObject.GType<TextView>; constructor( properties?: Partial<TextView.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<TextView.ConstructorProperties>, ...args: any[] ): void; // Properties accepts_tab: boolean; acceptsTab: boolean; bottom_margin: number; bottomMargin: number; buffer: TextBuffer; cursor_visible: boolean; cursorVisible: boolean; editable: boolean; extra_menu: Gio.MenuModel; extraMenu: Gio.MenuModel; im_module: string; imModule: string; indent: number; input_hints: InputHints; inputHints: InputHints; input_purpose: InputPurpose; inputPurpose: InputPurpose; justification: Justification; left_margin: number; leftMargin: number; monospace: boolean; overwrite: boolean; pixels_above_lines: number; pixelsAboveLines: number; pixels_below_lines: number; pixelsBelowLines: number; pixels_inside_wrap: number; pixelsInsideWrap: number; right_margin: number; rightMargin: number; tabs: Pango.TabArray; top_margin: number; topMargin: number; wrap_mode: WrapMode; wrapMode: WrapMode; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'backspace', callback: (_source: this) => void): number; connect_after( signal: 'backspace', callback: (_source: this) => void ): number; emit(signal: 'backspace'): void; connect( signal: 'copy-clipboard', callback: (_source: this) => void ): number; connect_after( signal: 'copy-clipboard', callback: (_source: this) => void ): number; emit(signal: 'copy-clipboard'): void; connect(signal: 'cut-clipboard', callback: (_source: this) => void): number; connect_after( signal: 'cut-clipboard', callback: (_source: this) => void ): number; emit(signal: 'cut-clipboard'): void; connect( signal: 'delete-from-cursor', callback: (_source: this, type: DeleteType, count: number) => void ): number; connect_after( signal: 'delete-from-cursor', callback: (_source: this, type: DeleteType, count: number) => void ): number; emit(signal: 'delete-from-cursor', type: DeleteType, count: number): void; connect( signal: 'extend-selection', callback: ( _source: this, granularity: TextExtendSelection, location: TextIter, start: TextIter, end: TextIter ) => boolean ): number; connect_after( signal: 'extend-selection', callback: ( _source: this, granularity: TextExtendSelection, location: TextIter, start: TextIter, end: TextIter ) => boolean ): number; emit( signal: 'extend-selection', granularity: TextExtendSelection, location: TextIter, start: TextIter, end: TextIter ): void; connect( signal: 'insert-at-cursor', callback: (_source: this, string: string) => void ): number; connect_after( signal: 'insert-at-cursor', callback: (_source: this, string: string) => void ): number; emit(signal: 'insert-at-cursor', string: string): void; connect(signal: 'insert-emoji', callback: (_source: this) => void): number; connect_after( signal: 'insert-emoji', callback: (_source: this) => void ): number; emit(signal: 'insert-emoji'): void; connect( signal: 'move-cursor', callback: ( _source: this, step: MovementStep, count: number, extend_selection: boolean ) => void ): number; connect_after( signal: 'move-cursor', callback: ( _source: this, step: MovementStep, count: number, extend_selection: boolean ) => void ): number; emit( signal: 'move-cursor', step: MovementStep, count: number, extend_selection: boolean ): void; connect( signal: 'move-viewport', callback: (_source: this, step: ScrollStep, count: number) => void ): number; connect_after( signal: 'move-viewport', callback: (_source: this, step: ScrollStep, count: number) => void ): number; emit(signal: 'move-viewport', step: ScrollStep, count: number): void; connect( signal: 'paste-clipboard', callback: (_source: this) => void ): number; connect_after( signal: 'paste-clipboard', callback: (_source: this) => void ): number; emit(signal: 'paste-clipboard'): void; connect( signal: 'preedit-changed', callback: (_source: this, preedit: string) => void ): number; connect_after( signal: 'preedit-changed', callback: (_source: this, preedit: string) => void ): number; emit(signal: 'preedit-changed', preedit: string): void; connect( signal: 'select-all', callback: (_source: this, select: boolean) => void ): number; connect_after( signal: 'select-all', callback: (_source: this, select: boolean) => void ): number; emit(signal: 'select-all', select: boolean): void; connect(signal: 'set-anchor', callback: (_source: this) => void): number; connect_after( signal: 'set-anchor', callback: (_source: this) => void ): number; emit(signal: 'set-anchor'): void; connect( signal: 'toggle-cursor-visible', callback: (_source: this) => void ): number; connect_after( signal: 'toggle-cursor-visible', callback: (_source: this) => void ): number; emit(signal: 'toggle-cursor-visible'): void; connect( signal: 'toggle-overwrite', callback: (_source: this) => void ): number; connect_after( signal: 'toggle-overwrite', callback: (_source: this) => void ): number; emit(signal: 'toggle-overwrite'): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; hadjustment: Adjustment; hscroll_policy: ScrollablePolicy; hscrollPolicy: ScrollablePolicy; vadjustment: Adjustment; vscroll_policy: ScrollablePolicy; vscrollPolicy: ScrollablePolicy; // Constructors static ['new'](): TextView; static new_with_buffer(buffer: TextBuffer): TextView; // Members add_child_at_anchor(child: Widget, anchor: TextChildAnchor): void; add_overlay(child: Widget, xpos: number, ypos: number): void; backward_display_line(iter: TextIter): boolean; backward_display_line_start(iter: TextIter): boolean; buffer_to_window_coords( win: TextWindowType, buffer_x: number, buffer_y: number ): [number | null, number | null]; forward_display_line(iter: TextIter): boolean; forward_display_line_end(iter: TextIter): boolean; get_accepts_tab(): boolean; get_bottom_margin(): number; get_buffer(): TextBuffer; get_cursor_locations( iter?: TextIter | null ): [Gdk.Rectangle | null, Gdk.Rectangle | null]; get_cursor_visible(): boolean; get_editable(): boolean; get_extra_menu(): Gio.MenuModel; get_gutter(win: TextWindowType): Widget | null; get_indent(): number; get_input_hints(): InputHints; get_input_purpose(): InputPurpose; get_iter_at_location(x: number, y: number): [boolean, TextIter]; get_iter_at_position( x: number, y: number ): [boolean, TextIter, number | null]; get_iter_location(iter: TextIter): Gdk.Rectangle; get_justification(): Justification; get_left_margin(): number; get_line_at_y(y: number): [TextIter, number]; get_line_yrange(iter: TextIter): [number, number]; get_monospace(): boolean; get_overwrite(): boolean; get_pixels_above_lines(): number; get_pixels_below_lines(): number; get_pixels_inside_wrap(): number; get_right_margin(): number; get_tabs(): Pango.TabArray | null; get_top_margin(): number; get_visible_rect(): Gdk.Rectangle; get_wrap_mode(): WrapMode; im_context_filter_keypress(event: Gdk.Event): boolean; move_mark_onscreen(mark: TextMark): boolean; move_overlay(child: Widget, xpos: number, ypos: number): void; move_visually(iter: TextIter, count: number): boolean; place_cursor_onscreen(): boolean; remove(child: Widget): void; reset_cursor_blink(): void; reset_im_context(): void; scroll_mark_onscreen(mark: TextMark): void; scroll_to_iter( iter: TextIter, within_margin: number, use_align: boolean, xalign: number, yalign: number ): boolean; scroll_to_mark( mark: TextMark, within_margin: number, use_align: boolean, xalign: number, yalign: number ): void; set_accepts_tab(accepts_tab: boolean): void; set_bottom_margin(bottom_margin: number): void; set_buffer(buffer?: TextBuffer | null): void; set_cursor_visible(setting: boolean): void; set_editable(setting: boolean): void; set_extra_menu(model?: Gio.MenuModel | null): void; set_gutter(win: TextWindowType, widget?: Widget | null): void; set_indent(indent: number): void; set_input_hints(hints: InputHints): void; set_input_purpose(purpose: InputPurpose): void; set_justification(justification: Justification): void; set_left_margin(left_margin: number): void; set_monospace(monospace: boolean): void; set_overwrite(overwrite: boolean): void; set_pixels_above_lines(pixels_above_lines: number): void; set_pixels_below_lines(pixels_below_lines: number): void; set_pixels_inside_wrap(pixels_inside_wrap: number): void; set_right_margin(right_margin: number): void; set_tabs(tabs: Pango.TabArray): void; set_top_margin(top_margin: number): void; set_wrap_mode(wrap_mode: WrapMode): void; starts_display_line(iter: TextIter): boolean; window_to_buffer_coords( win: TextWindowType, window_x: number, window_y: number ): [number | null, number | null]; vfunc_backspace(): void; vfunc_copy_clipboard(): void; vfunc_cut_clipboard(): void; vfunc_delete_from_cursor(type: DeleteType, count: number): void; vfunc_extend_selection( granularity: TextExtendSelection, location: TextIter, start: TextIter, end: TextIter ): boolean; vfunc_insert_at_cursor(str: string): void; vfunc_insert_emoji(): void; vfunc_move_cursor( step: MovementStep, count: number, extend_selection: boolean ): void; vfunc_paste_clipboard(): void; vfunc_set_anchor(): void; vfunc_snapshot_layer(layer: TextViewLayer, snapshot: Snapshot): void; vfunc_toggle_overwrite(): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_border(): [boolean, Border]; get_hadjustment(): Adjustment; get_hscroll_policy(): ScrollablePolicy; get_vadjustment(): Adjustment; get_vscroll_policy(): ScrollablePolicy; set_hadjustment(hadjustment?: Adjustment | null): void; set_hscroll_policy(policy: ScrollablePolicy): void; set_vadjustment(vadjustment?: Adjustment | null): void; set_vscroll_policy(policy: ScrollablePolicy): void; vfunc_get_border(): [boolean, Border]; } export namespace ToggleButton { export interface ConstructorProperties extends Button.ConstructorProperties { [key: string]: any; active: boolean; group: ToggleButton; } } export class ToggleButton extends Button implements Accessible, Actionable, Buildable, ConstraintTarget { static $gtype: GObject.GType<ToggleButton>; constructor( properties?: Partial<ToggleButton.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ToggleButton.ConstructorProperties>, ...args: any[] ): void; // Properties active: boolean; group: ToggleButton; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'toggled', callback: (_source: this) => void): number; connect_after(signal: 'toggled', callback: (_source: this) => void): number; emit(signal: 'toggled'): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; action_name: string; actionName: string; action_target: GLib.Variant; actionTarget: GLib.Variant; // Constructors static ['new'](): ToggleButton; static new_with_label(label: string): ToggleButton; static new_with_mnemonic(label: string): ToggleButton; // Members get_active(): boolean; set_active(is_active: boolean): void; set_group(group?: ToggleButton | null): void; toggled(): void; vfunc_toggled(): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_action_name(): string | null; get_action_target_value(): GLib.Variant | null; set_action_name(action_name?: string | null): void; set_action_target_value(target_value?: GLib.Variant | null): void; set_detailed_action_name(detailed_action_name: string): void; vfunc_get_action_name(): string | null; vfunc_get_action_target_value(): GLib.Variant | null; vfunc_set_action_name(action_name?: string | null): void; vfunc_set_action_target_value(target_value?: GLib.Variant | null): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace Tooltip { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class Tooltip extends GObject.Object { static $gtype: GObject.GType<Tooltip>; constructor( properties?: Partial<Tooltip.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Tooltip.ConstructorProperties>, ...args: any[] ): void; // Members set_custom(custom_widget?: Widget | null): void; set_icon(paintable?: Gdk.Paintable | null): void; set_icon_from_gicon(gicon?: Gio.Icon | null): void; set_icon_from_icon_name(icon_name?: string | null): void; set_markup(markup?: string | null): void; set_text(text?: string | null): void; set_tip_area(rect: Gdk.Rectangle): void; } export namespace TreeExpander { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; child: Widget; item: GObject.Object; list_row: TreeListRow; listRow: TreeListRow; } } export class TreeExpander extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<TreeExpander>; constructor( properties?: Partial<TreeExpander.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<TreeExpander.ConstructorProperties>, ...args: any[] ): void; // Properties child: Widget; item: GObject.Object; list_row: TreeListRow; listRow: TreeListRow; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](): TreeExpander; // Members get_child(): Widget | null; get_item<T = GObject.Object>(): T; get_list_row(): TreeListRow | null; set_child(child?: Widget | null): void; set_list_row(list_row?: TreeListRow | null): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace TreeListModel { export interface ConstructorProperties< A extends GObject.Object = GObject.Object > extends GObject.Object.ConstructorProperties { [key: string]: any; autoexpand: boolean; model: Gio.ListModel; passthrough: boolean; } } export class TreeListModel<A extends GObject.Object = GObject.Object> extends GObject.Object implements Gio.ListModel<A> { static $gtype: GObject.GType<TreeListModel>; constructor( properties?: Partial<TreeListModel.ConstructorProperties<A>>, ...args: any[] ); _init( properties?: Partial<TreeListModel.ConstructorProperties<A>>, ...args: any[] ): void; // Properties autoexpand: boolean; model: Gio.ListModel; passthrough: boolean; // Constructors static ['new']( root: Gio.ListModel, passthrough: boolean, autoexpand: boolean, create_func: TreeListModelCreateModelFunc ): TreeListModel; // Members get_autoexpand(): boolean; get_child_row(position: number): TreeListRow | null; get_model(): Gio.ListModel; get_passthrough(): boolean; get_row(position: number): TreeListRow | null; set_autoexpand(autoexpand: boolean): void; // Implemented Members get_item_type(): GObject.GType; get_n_items(): number; get_item(position: number): A | null; items_changed(position: number, removed: number, added: number): void; vfunc_get_item(position: number): A | null; vfunc_get_item_type(): GObject.GType; vfunc_get_n_items(): number; } export namespace TreeListRow { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; children: Gio.ListModel; depth: number; expandable: boolean; expanded: boolean; item: GObject.Object; } } export class TreeListRow extends GObject.Object { static $gtype: GObject.GType<TreeListRow>; constructor( properties?: Partial<TreeListRow.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<TreeListRow.ConstructorProperties>, ...args: any[] ): void; // Properties children: Gio.ListModel; depth: number; expandable: boolean; expanded: boolean; item: GObject.Object; // Members get_child_row(position: number): TreeListRow | null; get_children(): Gio.ListModel | null; get_depth(): number; get_expanded(): boolean; get_item<T = GObject.Object>(): T; get_parent(): TreeListRow | null; get_position(): number; is_expandable(): boolean; set_expanded(expanded: boolean): void; } export namespace TreeListRowSorter { export interface ConstructorProperties extends Sorter.ConstructorProperties { [key: string]: any; sorter: Sorter; } } export class TreeListRowSorter extends Sorter { static $gtype: GObject.GType<TreeListRowSorter>; constructor( properties?: Partial<TreeListRowSorter.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<TreeListRowSorter.ConstructorProperties>, ...args: any[] ): void; // Properties sorter: Sorter; // Constructors static ['new'](sorter?: Sorter | null): TreeListRowSorter; // Members get_sorter(): Sorter | null; set_sorter(sorter?: Sorter | null): void; } export namespace TreeModelFilter { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; child_model: TreeModel; childModel: TreeModel; virtual_root: TreePath; virtualRoot: TreePath; } } export class TreeModelFilter extends GObject.Object implements TreeDragSource, TreeModel { static $gtype: GObject.GType<TreeModelFilter>; constructor( properties?: Partial<TreeModelFilter.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<TreeModelFilter.ConstructorProperties>, ...args: any[] ): void; // Properties child_model: TreeModel; childModel: TreeModel; virtual_root: TreePath; virtualRoot: TreePath; // Members clear_cache(): void; convert_child_iter_to_iter(child_iter: TreeIter): [boolean, TreeIter]; convert_child_path_to_path(child_path: TreePath): TreePath | null; convert_iter_to_child_iter(filter_iter: TreeIter): TreeIter; convert_path_to_child_path(filter_path: TreePath): TreePath | null; get_model(): TreeModel; refilter(): void; set_modify_func( types: GObject.GType[], func: TreeModelFilterModifyFunc, destroy?: GLib.DestroyNotify | null ): void; set_visible_column(column: number): void; set_visible_func( func: TreeModelFilterVisibleFunc, destroy?: GLib.DestroyNotify | null ): void; vfunc_modify( child_model: TreeModel, iter: TreeIter, value: any, column: number ): void; vfunc_visible(child_model: TreeModel, iter: TreeIter): boolean; // Implemented Members drag_data_delete(path: TreePath): boolean; drag_data_get(path: TreePath): Gdk.ContentProvider | null; row_draggable(path: TreePath): boolean; vfunc_drag_data_delete(path: TreePath): boolean; vfunc_drag_data_get(path: TreePath): Gdk.ContentProvider | null; vfunc_row_draggable(path: TreePath): boolean; filter_new(root?: TreePath | null): TreeModel; foreach(func: TreeModelForeachFunc): void; get_column_type(index_: number): GObject.GType; get_flags(): TreeModelFlags; get_iter(path: TreePath): [boolean, TreeIter]; get_iter_first(): [boolean, TreeIter]; get_iter_from_string(path_string: string): [boolean, TreeIter]; get_n_columns(): number; get_path(iter: TreeIter): TreePath; get_string_from_iter(iter: TreeIter): string | null; get_value(iter: TreeIter, column: number): unknown; iter_children(parent?: TreeIter | null): [boolean, TreeIter]; iter_has_child(iter: TreeIter): boolean; iter_n_children(iter?: TreeIter | null): number; iter_next(iter: TreeIter): boolean; iter_nth_child(parent: TreeIter | null, n: number): [boolean, TreeIter]; iter_parent(child: TreeIter): [boolean, TreeIter]; iter_previous(iter: TreeIter): boolean; ref_node(iter: TreeIter): void; row_changed(path: TreePath, iter: TreeIter): void; row_deleted(path: TreePath): void; row_has_child_toggled(path: TreePath, iter: TreeIter): void; row_inserted(path: TreePath, iter: TreeIter): void; rows_reordered( path: TreePath, iter: TreeIter | null, new_order: number[] ): void; unref_node(iter: TreeIter): void; vfunc_get_column_type(index_: number): GObject.GType; vfunc_get_flags(): TreeModelFlags; vfunc_get_iter(path: TreePath): [boolean, TreeIter]; vfunc_get_n_columns(): number; vfunc_get_path(iter: TreeIter): TreePath; vfunc_get_value(iter: TreeIter, column: number): unknown; vfunc_iter_children(parent?: TreeIter | null): [boolean, TreeIter]; vfunc_iter_has_child(iter: TreeIter): boolean; vfunc_iter_n_children(iter?: TreeIter | null): number; vfunc_iter_next(iter: TreeIter): boolean; vfunc_iter_nth_child( parent: TreeIter | null, n: number ): [boolean, TreeIter]; vfunc_iter_parent(child: TreeIter): [boolean, TreeIter]; vfunc_iter_previous(iter: TreeIter): boolean; vfunc_ref_node(iter: TreeIter): void; vfunc_row_changed(path: TreePath, iter: TreeIter): void; vfunc_row_deleted(path: TreePath): void; vfunc_row_has_child_toggled(path: TreePath, iter: TreeIter): void; vfunc_row_inserted(path: TreePath, iter: TreeIter): void; vfunc_unref_node(iter: TreeIter): void; } export namespace TreeModelSort { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; model: TreeModel; } } export class TreeModelSort extends GObject.Object implements TreeDragSource, TreeModel, TreeSortable { static $gtype: GObject.GType<TreeModelSort>; constructor( properties?: Partial<TreeModelSort.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<TreeModelSort.ConstructorProperties>, ...args: any[] ): void; // Properties model: TreeModel; // Constructors static new_with_model(child_model: TreeModel): TreeModelSort; // Members clear_cache(): void; convert_child_iter_to_iter(child_iter: TreeIter): [boolean, TreeIter]; convert_child_path_to_path(child_path: TreePath): TreePath | null; convert_iter_to_child_iter(sorted_iter: TreeIter): TreeIter; convert_path_to_child_path(sorted_path: TreePath): TreePath | null; get_model(): TreeModel; iter_is_valid(iter: TreeIter): boolean; reset_default_sort_func(): void; // Implemented Members drag_data_delete(path: TreePath): boolean; drag_data_get(path: TreePath): Gdk.ContentProvider | null; row_draggable(path: TreePath): boolean; vfunc_drag_data_delete(path: TreePath): boolean; vfunc_drag_data_get(path: TreePath): Gdk.ContentProvider | null; vfunc_row_draggable(path: TreePath): boolean; filter_new(root?: TreePath | null): TreeModel; foreach(func: TreeModelForeachFunc): void; get_column_type(index_: number): GObject.GType; get_flags(): TreeModelFlags; get_iter(path: TreePath): [boolean, TreeIter]; get_iter_first(): [boolean, TreeIter]; get_iter_from_string(path_string: string): [boolean, TreeIter]; get_n_columns(): number; get_path(iter: TreeIter): TreePath; get_string_from_iter(iter: TreeIter): string | null; get_value(iter: TreeIter, column: number): unknown; iter_children(parent?: TreeIter | null): [boolean, TreeIter]; iter_has_child(iter: TreeIter): boolean; iter_n_children(iter?: TreeIter | null): number; iter_next(iter: TreeIter): boolean; iter_nth_child(parent: TreeIter | null, n: number): [boolean, TreeIter]; iter_parent(child: TreeIter): [boolean, TreeIter]; iter_previous(iter: TreeIter): boolean; ref_node(iter: TreeIter): void; row_changed(path: TreePath, iter: TreeIter): void; row_deleted(path: TreePath): void; row_has_child_toggled(path: TreePath, iter: TreeIter): void; row_inserted(path: TreePath, iter: TreeIter): void; rows_reordered( path: TreePath, iter: TreeIter | null, new_order: number[] ): void; unref_node(iter: TreeIter): void; vfunc_get_column_type(index_: number): GObject.GType; vfunc_get_flags(): TreeModelFlags; vfunc_get_iter(path: TreePath): [boolean, TreeIter]; vfunc_get_n_columns(): number; vfunc_get_path(iter: TreeIter): TreePath; vfunc_get_value(iter: TreeIter, column: number): unknown; vfunc_iter_children(parent?: TreeIter | null): [boolean, TreeIter]; vfunc_iter_has_child(iter: TreeIter): boolean; vfunc_iter_n_children(iter?: TreeIter | null): number; vfunc_iter_next(iter: TreeIter): boolean; vfunc_iter_nth_child( parent: TreeIter | null, n: number ): [boolean, TreeIter]; vfunc_iter_parent(child: TreeIter): [boolean, TreeIter]; vfunc_iter_previous(iter: TreeIter): boolean; vfunc_ref_node(iter: TreeIter): void; vfunc_row_changed(path: TreePath, iter: TreeIter): void; vfunc_row_deleted(path: TreePath): void; vfunc_row_has_child_toggled(path: TreePath, iter: TreeIter): void; vfunc_row_inserted(path: TreePath, iter: TreeIter): void; vfunc_unref_node(iter: TreeIter): void; get_sort_column_id(): [boolean, number, SortType]; has_default_sort_func(): boolean; set_default_sort_func( sort_func: TreeIterCompareFunc, destroy?: GLib.DestroyNotify | null ): void; set_sort_column_id(sort_column_id: number, order: SortType): void; set_sort_func( sort_column_id: number, sort_func: TreeIterCompareFunc, destroy?: GLib.DestroyNotify | null ): void; sort_column_changed(): void; vfunc_get_sort_column_id(): [boolean, number, SortType]; vfunc_has_default_sort_func(): boolean; vfunc_set_default_sort_func( sort_func: TreeIterCompareFunc, destroy?: GLib.DestroyNotify | null ): void; vfunc_set_sort_column_id(sort_column_id: number, order: SortType): void; vfunc_set_sort_func( sort_column_id: number, sort_func: TreeIterCompareFunc, destroy?: GLib.DestroyNotify | null ): void; vfunc_sort_column_changed(): void; } export namespace TreeSelection { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; mode: SelectionMode; } } export class TreeSelection extends GObject.Object { static $gtype: GObject.GType<TreeSelection>; constructor( properties?: Partial<TreeSelection.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<TreeSelection.ConstructorProperties>, ...args: any[] ): void; // Properties mode: SelectionMode; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'changed', callback: (_source: this) => void): number; connect_after(signal: 'changed', callback: (_source: this) => void): number; emit(signal: 'changed'): void; // Members count_selected_rows(): number; get_mode(): SelectionMode; get_selected(): [boolean, TreeModel | null, TreeIter | null]; get_selected_rows(): [TreePath[], TreeModel | null]; get_tree_view(): TreeView; iter_is_selected(iter: TreeIter): boolean; path_is_selected(path: TreePath): boolean; select_all(): void; select_iter(iter: TreeIter): void; select_path(path: TreePath): void; select_range(start_path: TreePath, end_path: TreePath): void; selected_foreach(func: TreeSelectionForeachFunc): void; set_mode(type: SelectionMode): void; set_select_function(func?: TreeSelectionFunc | null): void; unselect_all(): void; unselect_iter(iter: TreeIter): void; unselect_path(path: TreePath): void; unselect_range(start_path: TreePath, end_path: TreePath): void; } export namespace TreeStore { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class TreeStore extends GObject.Object implements Buildable, TreeDragDest, TreeDragSource, TreeModel, TreeSortable { static $gtype: GObject.GType<TreeStore>; constructor( properties?: Partial<TreeStore.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<TreeStore.ConstructorProperties>, ...args: any[] ): void; // Fields priv: TreeStorePrivate; // Constructors static ['new'](types: GObject.GType[]): TreeStore; // Members append(parent?: TreeIter | null): TreeIter; clear(): void; insert(parent: TreeIter | null, position: number): TreeIter; insert_after(parent?: TreeIter | null, sibling?: TreeIter | null): TreeIter; insert_before( parent?: TreeIter | null, sibling?: TreeIter | null ): TreeIter; insert_with_values( parent: TreeIter | null, position: number, columns: number[], values: GObject.Value[] ): TreeIter | null; is_ancestor(iter: TreeIter, descendant: TreeIter): boolean; iter_depth(iter: TreeIter): number; iter_is_valid(iter: TreeIter): boolean; move_after(iter: TreeIter, position?: TreeIter | null): void; move_before(iter: TreeIter, position?: TreeIter | null): void; prepend(parent?: TreeIter | null): TreeIter; remove(iter: TreeIter): boolean; set_column_types(types: GObject.GType[]): void; set_value(iter: TreeIter, column: number, value: any): void; set(iter: TreeIter, columns: number[], values: GObject.Value[]): void; set(...args: never[]): never; swap(a: TreeIter, b: TreeIter): void; // Implemented Members get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; drag_data_received(dest: TreePath, value: any): boolean; row_drop_possible(dest_path: TreePath, value: any): boolean; vfunc_drag_data_received(dest: TreePath, value: any): boolean; vfunc_row_drop_possible(dest_path: TreePath, value: any): boolean; drag_data_delete(path: TreePath): boolean; drag_data_get(path: TreePath): Gdk.ContentProvider | null; row_draggable(path: TreePath): boolean; vfunc_drag_data_delete(path: TreePath): boolean; vfunc_drag_data_get(path: TreePath): Gdk.ContentProvider | null; vfunc_row_draggable(path: TreePath): boolean; filter_new(root?: TreePath | null): TreeModel; foreach(func: TreeModelForeachFunc): void; get_column_type(index_: number): GObject.GType; get_flags(): TreeModelFlags; get_iter(path: TreePath): [boolean, TreeIter]; get_iter_first(): [boolean, TreeIter]; get_iter_from_string(path_string: string): [boolean, TreeIter]; get_n_columns(): number; get_path(iter: TreeIter): TreePath; get_string_from_iter(iter: TreeIter): string | null; get_value(iter: TreeIter, column: number): unknown; iter_children(parent?: TreeIter | null): [boolean, TreeIter]; iter_has_child(iter: TreeIter): boolean; iter_n_children(iter?: TreeIter | null): number; iter_next(iter: TreeIter): boolean; iter_nth_child(parent: TreeIter | null, n: number): [boolean, TreeIter]; iter_parent(child: TreeIter): [boolean, TreeIter]; iter_previous(iter: TreeIter): boolean; ref_node(iter: TreeIter): void; row_changed(path: TreePath, iter: TreeIter): void; row_deleted(path: TreePath): void; row_has_child_toggled(path: TreePath, iter: TreeIter): void; row_inserted(path: TreePath, iter: TreeIter): void; rows_reordered( path: TreePath, iter: TreeIter | null, new_order: number[] ): void; unref_node(iter: TreeIter): void; vfunc_get_column_type(index_: number): GObject.GType; vfunc_get_flags(): TreeModelFlags; vfunc_get_iter(path: TreePath): [boolean, TreeIter]; vfunc_get_n_columns(): number; vfunc_get_path(iter: TreeIter): TreePath; vfunc_get_value(iter: TreeIter, column: number): unknown; vfunc_iter_children(parent?: TreeIter | null): [boolean, TreeIter]; vfunc_iter_has_child(iter: TreeIter): boolean; vfunc_iter_n_children(iter?: TreeIter | null): number; vfunc_iter_next(iter: TreeIter): boolean; vfunc_iter_nth_child( parent: TreeIter | null, n: number ): [boolean, TreeIter]; vfunc_iter_parent(child: TreeIter): [boolean, TreeIter]; vfunc_iter_previous(iter: TreeIter): boolean; vfunc_ref_node(iter: TreeIter): void; vfunc_row_changed(path: TreePath, iter: TreeIter): void; vfunc_row_deleted(path: TreePath): void; vfunc_row_has_child_toggled(path: TreePath, iter: TreeIter): void; vfunc_row_inserted(path: TreePath, iter: TreeIter): void; vfunc_unref_node(iter: TreeIter): void; get_sort_column_id(): [boolean, number, SortType]; has_default_sort_func(): boolean; set_default_sort_func( sort_func: TreeIterCompareFunc, destroy?: GLib.DestroyNotify | null ): void; set_sort_column_id(sort_column_id: number, order: SortType): void; set_sort_func( sort_column_id: number, sort_func: TreeIterCompareFunc, destroy?: GLib.DestroyNotify | null ): void; sort_column_changed(): void; vfunc_get_sort_column_id(): [boolean, number, SortType]; vfunc_has_default_sort_func(): boolean; vfunc_set_default_sort_func( sort_func: TreeIterCompareFunc, destroy?: GLib.DestroyNotify | null ): void; vfunc_set_sort_column_id(sort_column_id: number, order: SortType): void; vfunc_set_sort_func( sort_column_id: number, sort_func: TreeIterCompareFunc, destroy?: GLib.DestroyNotify | null ): void; vfunc_sort_column_changed(): void; } export namespace TreeView { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; activate_on_single_click: boolean; activateOnSingleClick: boolean; enable_grid_lines: TreeViewGridLines; enableGridLines: TreeViewGridLines; enable_search: boolean; enableSearch: boolean; enable_tree_lines: boolean; enableTreeLines: boolean; expander_column: TreeViewColumn; expanderColumn: TreeViewColumn; fixed_height_mode: boolean; fixedHeightMode: boolean; headers_clickable: boolean; headersClickable: boolean; headers_visible: boolean; headersVisible: boolean; hover_expand: boolean; hoverExpand: boolean; hover_selection: boolean; hoverSelection: boolean; level_indentation: number; levelIndentation: number; model: TreeModel; reorderable: boolean; rubber_banding: boolean; rubberBanding: boolean; search_column: number; searchColumn: number; show_expanders: boolean; showExpanders: boolean; tooltip_column: number; tooltipColumn: number; } } export class TreeView extends Widget implements Accessible, Buildable, ConstraintTarget, Scrollable { static $gtype: GObject.GType<TreeView>; constructor( properties?: Partial<TreeView.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<TreeView.ConstructorProperties>, ...args: any[] ): void; // Properties activate_on_single_click: boolean; activateOnSingleClick: boolean; enable_grid_lines: TreeViewGridLines; enableGridLines: TreeViewGridLines; enable_search: boolean; enableSearch: boolean; enable_tree_lines: boolean; enableTreeLines: boolean; expander_column: TreeViewColumn; expanderColumn: TreeViewColumn; fixed_height_mode: boolean; fixedHeightMode: boolean; headers_clickable: boolean; headersClickable: boolean; headers_visible: boolean; headersVisible: boolean; hover_expand: boolean; hoverExpand: boolean; hover_selection: boolean; hoverSelection: boolean; level_indentation: number; levelIndentation: number; model: TreeModel; reorderable: boolean; rubber_banding: boolean; rubberBanding: boolean; search_column: number; searchColumn: number; show_expanders: boolean; showExpanders: boolean; tooltip_column: number; tooltipColumn: number; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'columns-changed', callback: (_source: this) => void ): number; connect_after( signal: 'columns-changed', callback: (_source: this) => void ): number; emit(signal: 'columns-changed'): void; connect( signal: 'cursor-changed', callback: (_source: this) => void ): number; connect_after( signal: 'cursor-changed', callback: (_source: this) => void ): number; emit(signal: 'cursor-changed'): void; connect( signal: 'expand-collapse-cursor-row', callback: ( _source: this, object: boolean, p0: boolean, p1: boolean ) => boolean ): number; connect_after( signal: 'expand-collapse-cursor-row', callback: ( _source: this, object: boolean, p0: boolean, p1: boolean ) => boolean ): number; emit( signal: 'expand-collapse-cursor-row', object: boolean, p0: boolean, p1: boolean ): void; connect( signal: 'move-cursor', callback: ( _source: this, step: MovementStep, direction: number, extend: boolean, modify: boolean ) => boolean ): number; connect_after( signal: 'move-cursor', callback: ( _source: this, step: MovementStep, direction: number, extend: boolean, modify: boolean ) => boolean ): number; emit( signal: 'move-cursor', step: MovementStep, direction: number, extend: boolean, modify: boolean ): void; connect( signal: 'row-activated', callback: ( _source: this, path: TreePath, column: TreeViewColumn ) => void ): number; connect_after( signal: 'row-activated', callback: ( _source: this, path: TreePath, column: TreeViewColumn ) => void ): number; emit(signal: 'row-activated', path: TreePath, column: TreeViewColumn): void; connect( signal: 'row-collapsed', callback: (_source: this, iter: TreeIter, path: TreePath) => void ): number; connect_after( signal: 'row-collapsed', callback: (_source: this, iter: TreeIter, path: TreePath) => void ): number; emit(signal: 'row-collapsed', iter: TreeIter, path: TreePath): void; connect( signal: 'row-expanded', callback: (_source: this, iter: TreeIter, path: TreePath) => void ): number; connect_after( signal: 'row-expanded', callback: (_source: this, iter: TreeIter, path: TreePath) => void ): number; emit(signal: 'row-expanded', iter: TreeIter, path: TreePath): void; connect(signal: 'select-all', callback: (_source: this) => boolean): number; connect_after( signal: 'select-all', callback: (_source: this) => boolean ): number; emit(signal: 'select-all'): void; connect( signal: 'select-cursor-parent', callback: (_source: this) => boolean ): number; connect_after( signal: 'select-cursor-parent', callback: (_source: this) => boolean ): number; emit(signal: 'select-cursor-parent'): void; connect( signal: 'select-cursor-row', callback: (_source: this, object: boolean) => boolean ): number; connect_after( signal: 'select-cursor-row', callback: (_source: this, object: boolean) => boolean ): number; emit(signal: 'select-cursor-row', object: boolean): void; connect( signal: 'start-interactive-search', callback: (_source: this) => boolean ): number; connect_after( signal: 'start-interactive-search', callback: (_source: this) => boolean ): number; emit(signal: 'start-interactive-search'): void; connect( signal: 'test-collapse-row', callback: (_source: this, iter: TreeIter, path: TreePath) => boolean ): number; connect_after( signal: 'test-collapse-row', callback: (_source: this, iter: TreeIter, path: TreePath) => boolean ): number; emit(signal: 'test-collapse-row', iter: TreeIter, path: TreePath): void; connect( signal: 'test-expand-row', callback: (_source: this, iter: TreeIter, path: TreePath) => boolean ): number; connect_after( signal: 'test-expand-row', callback: (_source: this, iter: TreeIter, path: TreePath) => boolean ): number; emit(signal: 'test-expand-row', iter: TreeIter, path: TreePath): void; connect( signal: 'toggle-cursor-row', callback: (_source: this) => boolean ): number; connect_after( signal: 'toggle-cursor-row', callback: (_source: this) => boolean ): number; emit(signal: 'toggle-cursor-row'): void; connect( signal: 'unselect-all', callback: (_source: this) => boolean ): number; connect_after( signal: 'unselect-all', callback: (_source: this) => boolean ): number; emit(signal: 'unselect-all'): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; hadjustment: Adjustment; hscroll_policy: ScrollablePolicy; hscrollPolicy: ScrollablePolicy; vadjustment: Adjustment; vscroll_policy: ScrollablePolicy; vscrollPolicy: ScrollablePolicy; // Constructors static ['new'](): TreeView; static new_with_model(model: TreeModel): TreeView; // Members append_column(column: TreeViewColumn): number; collapse_all(): void; collapse_row(path: TreePath): boolean; columns_autosize(): void; convert_bin_window_to_tree_coords(bx: number, by: number): [number, number]; convert_bin_window_to_widget_coords( bx: number, by: number ): [number, number]; convert_tree_to_bin_window_coords(tx: number, ty: number): [number, number]; convert_tree_to_widget_coords(tx: number, ty: number): [number, number]; convert_widget_to_bin_window_coords( wx: number, wy: number ): [number, number]; convert_widget_to_tree_coords(wx: number, wy: number): [number, number]; create_row_drag_icon(path: TreePath): Gdk.Paintable | null; enable_model_drag_dest( formats: Gdk.ContentFormats, actions: Gdk.DragAction ): void; enable_model_drag_source( start_button_mask: Gdk.ModifierType, formats: Gdk.ContentFormats, actions: Gdk.DragAction ): void; expand_all(): void; expand_row(path: TreePath, open_all: boolean): boolean; expand_to_path(path: TreePath): void; get_activate_on_single_click(): boolean; get_background_area( path: TreePath | null, column: TreeViewColumn | null ): Gdk.Rectangle; get_cell_area( path: TreePath | null, column: TreeViewColumn | null ): Gdk.Rectangle; get_column(n: number): TreeViewColumn | null; get_columns(): TreeViewColumn[]; get_cursor(): [TreePath | null, TreeViewColumn | null]; get_cursor(...args: never[]): never; get_dest_row_at_pos( drag_x: number, drag_y: number ): [boolean, TreePath | null, TreeViewDropPosition | null]; get_drag_dest_row(): [TreePath | null, TreeViewDropPosition | null]; get_enable_search(): boolean; get_enable_tree_lines(): boolean; get_expander_column(): TreeViewColumn | null; get_fixed_height_mode(): boolean; get_grid_lines(): TreeViewGridLines; get_headers_clickable(): boolean; get_headers_visible(): boolean; get_hover_expand(): boolean; get_hover_selection(): boolean; get_level_indentation(): number; get_model(): TreeModel | null; get_n_columns(): number; get_path_at_pos( x: number, y: number ): [ boolean, TreePath | null, TreeViewColumn | null, number | null, number | null ]; get_reorderable(): boolean; get_rubber_banding(): boolean; get_search_column(): number; get_search_entry(): Editable | null; get_selection(): TreeSelection; get_show_expanders(): boolean; get_tooltip_column(): number; get_tooltip_context( x: number, y: number, keyboard_tip: boolean ): [boolean, TreeModel | null, TreePath | null, TreeIter | null]; get_visible_range(): [boolean, TreePath | null, TreePath | null]; get_visible_rect(): Gdk.Rectangle; insert_column(column: TreeViewColumn, position: number): number; insert_column_with_data_func( position: number, title: string, cell: CellRenderer, func: TreeCellDataFunc ): number; is_blank_at_pos( x: number, y: number ): [ boolean, TreePath | null, TreeViewColumn | null, number | null, number | null ]; is_rubber_banding_active(): boolean; map_expanded_rows(func: TreeViewMappingFunc): void; move_column_after( column: TreeViewColumn, base_column?: TreeViewColumn | null ): void; remove_column(column: TreeViewColumn): number; row_activated(path: TreePath, column: TreeViewColumn): void; row_expanded(path: TreePath): boolean; scroll_to_cell( path: TreePath | null, column: TreeViewColumn | null, use_align: boolean, row_align: number, col_align: number ): void; scroll_to_point(tree_x: number, tree_y: number): void; set_activate_on_single_click(single: boolean): void; set_column_drag_function( func?: TreeViewColumnDropFunc | null, destroy?: GLib.DestroyNotify | null ): void; set_cursor( path: TreePath, focus_column: TreeViewColumn | null, start_editing: boolean ): void; set_cursor(...args: never[]): never; set_cursor_on_cell( path: TreePath, focus_column: TreeViewColumn | null, focus_cell: CellRenderer | null, start_editing: boolean ): void; set_drag_dest_row(path: TreePath | null, pos: TreeViewDropPosition): void; set_enable_search(enable_search: boolean): void; set_enable_tree_lines(enabled: boolean): void; set_expander_column(column?: TreeViewColumn | null): void; set_fixed_height_mode(enable: boolean): void; set_grid_lines(grid_lines: TreeViewGridLines): void; set_headers_clickable(setting: boolean): void; set_headers_visible(headers_visible: boolean): void; set_hover_expand(expand: boolean): void; set_hover_selection(hover: boolean): void; set_level_indentation(indentation: number): void; set_model(model?: TreeModel | null): void; set_reorderable(reorderable: boolean): void; set_row_separator_func( func?: TreeViewRowSeparatorFunc | null, destroy?: GLib.DestroyNotify | null ): void; set_rubber_banding(enable: boolean): void; set_search_column(column: number): void; set_search_entry(entry?: Editable | null): void; set_search_equal_func( search_equal_func: TreeViewSearchEqualFunc, search_destroy?: GLib.DestroyNotify | null ): void; set_show_expanders(enabled: boolean): void; set_tooltip_cell( tooltip: Tooltip, path?: TreePath | null, column?: TreeViewColumn | null, cell?: CellRenderer | null ): void; set_tooltip_column(column: number): void; set_tooltip_row(tooltip: Tooltip, path: TreePath): void; unset_rows_drag_dest(): void; unset_rows_drag_source(): void; vfunc_columns_changed(): void; vfunc_cursor_changed(): void; vfunc_expand_collapse_cursor_row( logical: boolean, expand: boolean, open_all: boolean ): boolean; vfunc_move_cursor( step: MovementStep, count: number, extend: boolean, modify: boolean ): boolean; vfunc_row_activated(path: TreePath, column: TreeViewColumn): void; vfunc_row_collapsed(iter: TreeIter, path: TreePath): void; vfunc_row_expanded(iter: TreeIter, path: TreePath): void; vfunc_select_all(): boolean; vfunc_select_cursor_parent(): boolean; vfunc_select_cursor_row(start_editing: boolean): boolean; vfunc_start_interactive_search(): boolean; vfunc_test_collapse_row(iter: TreeIter, path: TreePath): boolean; vfunc_test_expand_row(iter: TreeIter, path: TreePath): boolean; vfunc_toggle_cursor_row(): boolean; vfunc_unselect_all(): boolean; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_border(): [boolean, Border]; get_hadjustment(): Adjustment; get_hscroll_policy(): ScrollablePolicy; get_vadjustment(): Adjustment; get_vscroll_policy(): ScrollablePolicy; set_hadjustment(hadjustment?: Adjustment | null): void; set_hscroll_policy(policy: ScrollablePolicy): void; set_vadjustment(vadjustment?: Adjustment | null): void; set_vscroll_policy(policy: ScrollablePolicy): void; vfunc_get_border(): [boolean, Border]; } export namespace TreeViewColumn { export interface ConstructorProperties extends GObject.InitiallyUnowned.ConstructorProperties { [key: string]: any; alignment: number; cell_area: CellArea; cellArea: CellArea; clickable: boolean; expand: boolean; fixed_width: number; fixedWidth: number; max_width: number; maxWidth: number; min_width: number; minWidth: number; reorderable: boolean; resizable: boolean; sizing: TreeViewColumnSizing; sort_column_id: number; sortColumnId: number; sort_indicator: boolean; sortIndicator: boolean; sort_order: SortType; sortOrder: SortType; spacing: number; title: string; visible: boolean; widget: Widget; width: number; x_offset: number; xOffset: number; } } export class TreeViewColumn extends GObject.InitiallyUnowned implements Buildable, CellLayout { static $gtype: GObject.GType<TreeViewColumn>; constructor( properties?: Partial<TreeViewColumn.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<TreeViewColumn.ConstructorProperties>, ...args: any[] ): void; // Properties alignment: number; cell_area: CellArea; cellArea: CellArea; clickable: boolean; expand: boolean; fixed_width: number; fixedWidth: number; max_width: number; maxWidth: number; min_width: number; minWidth: number; reorderable: boolean; resizable: boolean; sizing: TreeViewColumnSizing; sort_column_id: number; sortColumnId: number; sort_indicator: boolean; sortIndicator: boolean; sort_order: SortType; sortOrder: SortType; spacing: number; title: string; visible: boolean; widget: Widget; width: number; x_offset: number; xOffset: number; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'clicked', callback: (_source: this) => void): number; connect_after(signal: 'clicked', callback: (_source: this) => void): number; emit(signal: 'clicked'): void; // Constructors static ['new'](): TreeViewColumn; static new_with_area(area: CellArea): TreeViewColumn; // Members add_attribute( cell_renderer: CellRenderer, attribute: string, column: number ): void; cell_get_position( cell_renderer: CellRenderer ): [boolean, number | null, number | null]; cell_get_size(): [ number | null, number | null, number | null, number | null ]; cell_is_visible(): boolean; cell_set_cell_data( tree_model: TreeModel, iter: TreeIter, is_expander: boolean, is_expanded: boolean ): void; clear(): void; clear_attributes(cell_renderer: CellRenderer): void; clicked(): void; focus_cell(cell: CellRenderer): void; get_alignment(): number; get_button(): Widget; get_clickable(): boolean; get_expand(): boolean; get_fixed_width(): number; get_max_width(): number; get_min_width(): number; get_reorderable(): boolean; get_resizable(): boolean; get_sizing(): TreeViewColumnSizing; get_sort_column_id(): number; get_sort_indicator(): boolean; get_sort_order(): SortType; get_spacing(): number; get_title(): string; get_tree_view(): Widget | null; get_visible(): boolean; get_widget(): Widget | null; get_width(): number; get_x_offset(): number; pack_end(cell: CellRenderer, expand: boolean): void; pack_start(cell: CellRenderer, expand: boolean): void; queue_resize(): void; set_alignment(xalign: number): void; set_cell_data_func( cell_renderer: CellRenderer, func?: TreeCellDataFunc | null ): void; set_cell_data_func(...args: never[]): never; set_clickable(clickable: boolean): void; set_expand(expand: boolean): void; set_fixed_width(fixed_width: number): void; set_max_width(max_width: number): void; set_min_width(min_width: number): void; set_reorderable(reorderable: boolean): void; set_resizable(resizable: boolean): void; set_sizing(type: TreeViewColumnSizing): void; set_sort_column_id(sort_column_id: number): void; set_sort_indicator(setting: boolean): void; set_sort_order(order: SortType): void; set_spacing(spacing: number): void; set_title(title: string): void; set_visible(visible: boolean): void; set_widget(widget?: Widget | null): void; // Implemented Members get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_area(): CellArea | null; get_cells(): CellRenderer[]; reorder(cell: CellRenderer, position: number): void; vfunc_add_attribute( cell: CellRenderer, attribute: string, column: number ): void; vfunc_clear(): void; vfunc_clear_attributes(cell: CellRenderer): void; vfunc_get_area(): CellArea | null; vfunc_get_cells(): CellRenderer[]; vfunc_pack_end(cell: CellRenderer, expand: boolean): void; vfunc_pack_start(cell: CellRenderer, expand: boolean): void; vfunc_reorder(cell: CellRenderer, position: number): void; vfunc_set_cell_data_func( cell: CellRenderer, func?: CellLayoutDataFunc | null ): void; } export namespace Video { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; autoplay: boolean; file: Gio.File; loop: boolean; media_stream: MediaStream; mediaStream: MediaStream; } } export class Video extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<Video>; constructor( properties?: Partial<Video.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Video.ConstructorProperties>, ...args: any[] ): void; // Properties autoplay: boolean; file: Gio.File; loop: boolean; media_stream: MediaStream; mediaStream: MediaStream; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](): Video; static new_for_file(file?: Gio.File | null): Video; static new_for_filename(filename?: string | null): Video; static new_for_media_stream(stream?: MediaStream | null): Video; static new_for_resource(resource_path?: string | null): Video; // Members get_autoplay(): boolean; get_file(): Gio.File | null; get_loop(): boolean; get_media_stream(): MediaStream | null; set_autoplay(autoplay: boolean): void; set_file(file?: Gio.File | null): void; set_filename(filename?: string | null): void; set_loop(loop: boolean): void; set_media_stream(stream?: MediaStream | null): void; set_resource(resource_path?: string | null): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace Viewport { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; child: Widget; scroll_to_focus: boolean; scrollToFocus: boolean; } } export class Viewport extends Widget implements Accessible, Buildable, ConstraintTarget, Scrollable { static $gtype: GObject.GType<Viewport>; constructor( properties?: Partial<Viewport.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Viewport.ConstructorProperties>, ...args: any[] ): void; // Properties child: Widget; scroll_to_focus: boolean; scrollToFocus: boolean; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; hadjustment: Adjustment; hscroll_policy: ScrollablePolicy; hscrollPolicy: ScrollablePolicy; vadjustment: Adjustment; vscroll_policy: ScrollablePolicy; vscrollPolicy: ScrollablePolicy; // Constructors static ['new']( hadjustment?: Adjustment | null, vadjustment?: Adjustment | null ): Viewport; // Members get_child(): Widget | null; get_scroll_to_focus(): boolean; set_child(child?: Widget | null): void; set_scroll_to_focus(scroll_to_focus: boolean): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_border(): [boolean, Border]; get_hadjustment(): Adjustment; get_hscroll_policy(): ScrollablePolicy; get_vadjustment(): Adjustment; get_vscroll_policy(): ScrollablePolicy; set_hadjustment(hadjustment?: Adjustment | null): void; set_hscroll_policy(policy: ScrollablePolicy): void; set_vadjustment(vadjustment?: Adjustment | null): void; set_vscroll_policy(policy: ScrollablePolicy): void; vfunc_get_border(): [boolean, Border]; } export namespace VolumeButton { export interface ConstructorProperties extends ScaleButton.ConstructorProperties { [key: string]: any; use_symbolic: boolean; useSymbolic: boolean; } } export class VolumeButton extends ScaleButton implements Accessible, Buildable, ConstraintTarget, Orientable { static $gtype: GObject.GType<VolumeButton>; constructor( properties?: Partial<VolumeButton.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<VolumeButton.ConstructorProperties>, ...args: any[] ): void; // Properties use_symbolic: boolean; useSymbolic: boolean; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; orientation: Orientation; // Constructors static ['new'](): VolumeButton; static ['new'](...args: never[]): never; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_orientation(): Orientation; set_orientation(orientation: Orientation): void; } export namespace Widget { export interface ConstructorProperties extends GObject.InitiallyUnowned.ConstructorProperties { [key: string]: any; can_focus: boolean; canFocus: boolean; can_target: boolean; canTarget: boolean; css_classes: string[]; cssClasses: string[]; css_name: string; cssName: string; cursor: Gdk.Cursor; focus_on_click: boolean; focusOnClick: boolean; focusable: boolean; halign: Align; has_default: boolean; hasDefault: boolean; has_focus: boolean; hasFocus: boolean; has_tooltip: boolean; hasTooltip: boolean; height_request: number; heightRequest: number; hexpand: boolean; hexpand_set: boolean; hexpandSet: boolean; layout_manager: LayoutManager; layoutManager: LayoutManager; margin_bottom: number; marginBottom: number; margin_end: number; marginEnd: number; margin_start: number; marginStart: number; margin_top: number; marginTop: number; name: string; opacity: number; overflow: Overflow; receives_default: boolean; receivesDefault: boolean; root: Root; scale_factor: number; scaleFactor: number; sensitive: boolean; tooltip_markup: string; tooltipMarkup: string; tooltip_text: string; tooltipText: string; valign: Align; vexpand: boolean; vexpand_set: boolean; vexpandSet: boolean; visible: boolean; width_request: number; widthRequest: number; } } export abstract class Widget extends GObject.InitiallyUnowned implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<Widget>; constructor( properties?: Partial<Widget.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Widget.ConstructorProperties>, ...args: any[] ): void; // Properties can_focus: boolean; canFocus: boolean; can_target: boolean; canTarget: boolean; css_classes: string[]; cssClasses: string[]; css_name: string; cssName: string; cursor: Gdk.Cursor; focus_on_click: boolean; focusOnClick: boolean; focusable: boolean; halign: Align; has_default: boolean; hasDefault: boolean; has_focus: boolean; hasFocus: boolean; has_tooltip: boolean; hasTooltip: boolean; height_request: number; heightRequest: number; hexpand: boolean; hexpand_set: boolean; hexpandSet: boolean; layout_manager: LayoutManager; layoutManager: LayoutManager; margin_bottom: number; marginBottom: number; margin_end: number; marginEnd: number; margin_start: number; marginStart: number; margin_top: number; marginTop: number; name: string; opacity: number; overflow: Overflow; receives_default: boolean; receivesDefault: boolean; root: Root; scale_factor: number; scaleFactor: number; sensitive: boolean; tooltip_markup: string; tooltipMarkup: string; tooltip_text: string; tooltipText: string; valign: Align; vexpand: boolean; vexpand_set: boolean; vexpandSet: boolean; visible: boolean; width_request: number; widthRequest: number; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'destroy', callback: (_source: this) => void): number; connect_after(signal: 'destroy', callback: (_source: this) => void): number; emit(signal: 'destroy'): void; connect( signal: 'direction-changed', callback: (_source: this, previous_direction: TextDirection) => void ): number; connect_after( signal: 'direction-changed', callback: (_source: this, previous_direction: TextDirection) => void ): number; emit(signal: 'direction-changed', previous_direction: TextDirection): void; connect(signal: 'hide', callback: (_source: this) => void): number; connect_after(signal: 'hide', callback: (_source: this) => void): number; emit(signal: 'hide'): void; connect( signal: 'keynav-failed', callback: (_source: this, direction: DirectionType) => boolean ): number; connect_after( signal: 'keynav-failed', callback: (_source: this, direction: DirectionType) => boolean ): number; emit(signal: 'keynav-failed', direction: DirectionType): void; connect(signal: 'map', callback: (_source: this) => void): number; connect_after(signal: 'map', callback: (_source: this) => void): number; emit(signal: 'map'): void; connect( signal: 'mnemonic-activate', callback: (_source: this, group_cycling: boolean) => boolean ): number; connect_after( signal: 'mnemonic-activate', callback: (_source: this, group_cycling: boolean) => boolean ): number; emit(signal: 'mnemonic-activate', group_cycling: boolean): void; connect( signal: 'move-focus', callback: (_source: this, direction: DirectionType) => void ): number; connect_after( signal: 'move-focus', callback: (_source: this, direction: DirectionType) => void ): number; emit(signal: 'move-focus', direction: DirectionType): void; connect( signal: 'query-tooltip', callback: ( _source: this, x: number, y: number, keyboard_mode: boolean, tooltip: Tooltip ) => boolean ): number; connect_after( signal: 'query-tooltip', callback: ( _source: this, x: number, y: number, keyboard_mode: boolean, tooltip: Tooltip ) => boolean ): number; emit( signal: 'query-tooltip', x: number, y: number, keyboard_mode: boolean, tooltip: Tooltip ): void; connect(signal: 'realize', callback: (_source: this) => void): number; connect_after(signal: 'realize', callback: (_source: this) => void): number; emit(signal: 'realize'): void; connect(signal: 'show', callback: (_source: this) => void): number; connect_after(signal: 'show', callback: (_source: this) => void): number; emit(signal: 'show'): void; connect( signal: 'state-flags-changed', callback: (_source: this, flags: StateFlags) => void ): number; connect_after( signal: 'state-flags-changed', callback: (_source: this, flags: StateFlags) => void ): number; emit(signal: 'state-flags-changed', flags: StateFlags): void; connect(signal: 'unmap', callback: (_source: this) => void): number; connect_after(signal: 'unmap', callback: (_source: this) => void): number; emit(signal: 'unmap'): void; connect(signal: 'unrealize', callback: (_source: this) => void): number; connect_after( signal: 'unrealize', callback: (_source: this) => void ): number; emit(signal: 'unrealize'): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Members action_set_enabled(action_name: string, enabled: boolean): void; activate(): boolean; activate_action(name: string, args?: GLib.Variant | null): boolean; activate_default(): void; add_controller(controller: EventController): void; add_css_class(css_class: string): void; add_mnemonic_label(label: Widget): void; add_tick_callback(callback: TickCallback): number; allocate( width: number, height: number, baseline: number, transform?: Gsk.Transform | null ): void; child_focus(direction: DirectionType): boolean; compute_bounds(target: Widget): [boolean, Graphene.Rect]; compute_expand(orientation: Orientation): boolean; compute_point( target: Widget, point: Graphene.Point ): [boolean, Graphene.Point]; compute_transform(target: Widget): [boolean, Graphene.Matrix]; contains(x: number, y: number): boolean; create_pango_context(): Pango.Context; create_pango_layout(text?: string | null): Pango.Layout; drag_check_threshold( start_x: number, start_y: number, current_x: number, current_y: number ): boolean; error_bell(): void; get_allocated_baseline(): number; get_allocated_height(): number; get_allocated_width(): number; get_allocation(): Allocation; get_ancestor(widget_type: GObject.GType): Widget | null; get_can_focus(): boolean; get_can_target(): boolean; get_child_visible(): boolean; get_clipboard(): Gdk.Clipboard; get_css_classes(): string[]; get_css_name(): string; get_cursor(): Gdk.Cursor | null; get_direction(): TextDirection; get_display(): Gdk.Display; get_first_child(): Widget | null; get_focus_child(): Widget | null; get_focus_on_click(): boolean; get_focusable(): boolean; get_font_map(): Pango.FontMap | null; get_font_options(): cairo.FontOptions | null; get_frame_clock(): Gdk.FrameClock | null; get_halign(): Align; get_has_tooltip(): boolean; get_height(): number; get_hexpand(): boolean; get_hexpand_set(): boolean; get_last_child(): Widget | null; get_layout_manager(): LayoutManager | null; get_mapped(): boolean; get_margin_bottom(): number; get_margin_end(): number; get_margin_start(): number; get_margin_top(): number; get_name(): string | null; get_native(): Native | null; get_next_sibling(): Widget | null; get_opacity(): number; get_overflow(): Overflow; get_pango_context(): Pango.Context; get_parent(): Widget | null; get_preferred_size(): [Requisition | null, Requisition | null]; get_prev_sibling(): Widget | null; get_primary_clipboard(): Gdk.Clipboard; get_realized(): boolean; get_receives_default(): boolean; get_request_mode(): SizeRequestMode; get_root(): Root | null; get_scale_factor(): number; get_sensitive(): boolean; get_settings(): Settings; get_size(orientation: Orientation): number; get_size_request(): [number | null, number | null]; get_state_flags(): StateFlags; get_style_context(): StyleContext; get_template_child<T = GObject.Object>( widget_type: GObject.GType, name: string ): T; get_tooltip_markup(): string | null; get_tooltip_text(): string | null; get_valign(): Align; get_vexpand(): boolean; get_vexpand_set(): boolean; get_visible(): boolean; get_width(): number; grab_focus(): boolean; has_css_class(css_class: string): boolean; has_visible_focus(): boolean; hide(): void; in_destruction(): boolean; init_template(): void; insert_action_group(name: string, group?: Gio.ActionGroup | null): void; insert_after(parent: Widget, previous_sibling?: Widget | null): void; insert_before(parent: Widget, next_sibling?: Widget | null): void; is_ancestor(ancestor: Widget): boolean; is_drawable(): boolean; is_focus(): boolean; is_sensitive(): boolean; is_visible(): boolean; keynav_failed(direction: DirectionType): boolean; list_mnemonic_labels(): Widget[]; map(): void; measure( orientation: Orientation, for_size: number ): [number | null, number | null, number | null, number | null]; mnemonic_activate(group_cycling: boolean): boolean; observe_children(): Gio.ListModel; observe_controllers(): Gio.ListModel; pick(x: number, y: number, flags: PickFlags): Widget | null; queue_allocate(): void; queue_draw(): void; queue_resize(): void; realize(): void; remove_controller(controller: EventController): void; remove_css_class(css_class: string): void; remove_mnemonic_label(label: Widget): void; remove_tick_callback(id: number): void; set_can_focus(can_focus: boolean): void; set_can_target(can_target: boolean): void; set_child_visible(child_visible: boolean): void; set_css_classes(classes: string[]): void; set_cursor(cursor?: Gdk.Cursor | null): void; set_cursor_from_name(name?: string | null): void; set_direction(dir: TextDirection): void; set_focus_child(child?: Widget | null): void; set_focus_on_click(focus_on_click: boolean): void; set_focusable(focusable: boolean): void; set_font_map(font_map?: Pango.FontMap | null): void; set_font_options(options?: cairo.FontOptions | null): void; set_halign(align: Align): void; set_has_tooltip(has_tooltip: boolean): void; set_hexpand(expand: boolean): void; set_hexpand_set(set: boolean): void; set_layout_manager(layout_manager?: LayoutManager | null): void; set_margin_bottom(margin: number): void; set_margin_end(margin: number): void; set_margin_start(margin: number): void; set_margin_top(margin: number): void; set_name(name: string): void; set_opacity(opacity: number): void; set_overflow(overflow: Overflow): void; set_parent(parent: Widget): void; set_receives_default(receives_default: boolean): void; set_sensitive(sensitive: boolean): void; set_size_request(width: number, height: number): void; set_state_flags(flags: StateFlags, clear: boolean): void; set_tooltip_markup(markup?: string | null): void; set_tooltip_text(text?: string | null): void; set_valign(align: Align): void; set_vexpand(expand: boolean): void; set_vexpand_set(set: boolean): void; set_visible(visible: boolean): void; should_layout(): boolean; show(): void; size_allocate(allocation: Allocation, baseline: number): void; snapshot_child(child: Widget, snapshot: Snapshot): void; translate_coordinates( dest_widget: Widget, src_x: number, src_y: number ): [boolean, number | null, number | null]; trigger_tooltip_query(): void; unmap(): void; unparent(): void; unrealize(): void; unset_state_flags(flags: StateFlags): void; vfunc_compute_expand(hexpand_p: boolean, vexpand_p: boolean): void; vfunc_contains(x: number, y: number): boolean; vfunc_css_changed(change: CssStyleChange): void; vfunc_direction_changed(previous_direction: TextDirection): void; vfunc_focus(direction: DirectionType): boolean; vfunc_get_request_mode(): SizeRequestMode; vfunc_grab_focus(): boolean; vfunc_hide(): void; vfunc_keynav_failed(direction: DirectionType): boolean; vfunc_map(): void; vfunc_measure( orientation: Orientation, for_size: number ): [number | null, number | null, number | null, number | null]; vfunc_mnemonic_activate(group_cycling: boolean): boolean; vfunc_move_focus(direction: DirectionType): void; vfunc_query_tooltip( x: number, y: number, keyboard_tooltip: boolean, tooltip: Tooltip ): boolean; vfunc_realize(): void; vfunc_root(): void; vfunc_set_focus_child(child?: Widget | null): void; vfunc_show(): void; vfunc_size_allocate(width: number, height: number, baseline: number): void; vfunc_snapshot(snapshot: Snapshot): void; vfunc_state_flags_changed(previous_state_flags: StateFlags): void; vfunc_system_setting_changed(settings: SystemSetting): void; vfunc_unmap(): void; vfunc_unrealize(): void; vfunc_unroot(): void; static get_default_direction(): TextDirection; static set_default_direction(dir: TextDirection): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace WidgetPaintable { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; widget: Widget; } } export class WidgetPaintable extends GObject.Object implements Gdk.Paintable { static $gtype: GObject.GType<WidgetPaintable>; constructor( properties?: Partial<WidgetPaintable.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<WidgetPaintable.ConstructorProperties>, ...args: any[] ): void; // Properties widget: Widget; // Constructors static ['new'](widget?: Widget | null): WidgetPaintable; // Members get_widget(): Widget | null; set_widget(widget?: Widget | null): void; // Implemented Members compute_concrete_size( specified_width: number, specified_height: number, default_width: number, default_height: number ): [number, number]; get_current_image(): Gdk.Paintable; get_flags(): Gdk.PaintableFlags; get_intrinsic_aspect_ratio(): number; get_intrinsic_height(): number; get_intrinsic_width(): number; invalidate_contents(): void; invalidate_size(): void; snapshot(snapshot: Gdk.Snapshot, width: number, height: number): void; vfunc_get_current_image(): Gdk.Paintable; vfunc_get_flags(): Gdk.PaintableFlags; vfunc_get_intrinsic_aspect_ratio(): number; vfunc_get_intrinsic_height(): number; vfunc_get_intrinsic_width(): number; vfunc_snapshot(snapshot: Gdk.Snapshot, width: number, height: number): void; } export namespace Window { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; application: Application; child: Widget; decorated: boolean; default_height: number; defaultHeight: number; default_widget: Widget; defaultWidget: Widget; default_width: number; defaultWidth: number; deletable: boolean; destroy_with_parent: boolean; destroyWithParent: boolean; display: Gdk.Display; focus_visible: boolean; focusVisible: boolean; focus_widget: Widget; focusWidget: Widget; fullscreened: boolean; hide_on_close: boolean; hideOnClose: boolean; icon_name: string; iconName: string; is_active: boolean; isActive: boolean; maximized: boolean; mnemonics_visible: boolean; mnemonicsVisible: boolean; modal: boolean; resizable: boolean; startup_id: string; startupId: string; title: string; transient_for: Window; transientFor: Window; } } export class Window extends Widget implements Accessible, Buildable, ConstraintTarget, Native, Root, ShortcutManager { static $gtype: GObject.GType<Window>; constructor( properties?: Partial<Window.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Window.ConstructorProperties>, ...args: any[] ): void; // Properties application: Application; child: Widget; decorated: boolean; default_height: number; defaultHeight: number; default_widget: Widget; defaultWidget: Widget; default_width: number; defaultWidth: number; deletable: boolean; destroy_with_parent: boolean; destroyWithParent: boolean; display: Gdk.Display; focus_visible: boolean; focusVisible: boolean; focus_widget: Widget; focusWidget: Widget; fullscreened: boolean; hide_on_close: boolean; hideOnClose: boolean; icon_name: string; iconName: string; is_active: boolean; isActive: boolean; maximized: boolean; mnemonics_visible: boolean; mnemonicsVisible: boolean; modal: boolean; resizable: boolean; startup_id: string; startupId: string; title: string; transient_for: Window; transientFor: Window; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'activate-default', callback: (_source: this) => void ): number; connect_after( signal: 'activate-default', callback: (_source: this) => void ): number; emit(signal: 'activate-default'): void; connect( signal: 'activate-focus', callback: (_source: this) => void ): number; connect_after( signal: 'activate-focus', callback: (_source: this) => void ): number; emit(signal: 'activate-focus'): void; connect( signal: 'close-request', callback: (_source: this) => boolean ): number; connect_after( signal: 'close-request', callback: (_source: this) => boolean ): number; emit(signal: 'close-request'): void; connect( signal: 'enable-debugging', callback: (_source: this, toggle: boolean) => boolean ): number; connect_after( signal: 'enable-debugging', callback: (_source: this, toggle: boolean) => boolean ): number; emit(signal: 'enable-debugging', toggle: boolean): void; connect(signal: 'keys-changed', callback: (_source: this) => void): number; connect_after( signal: 'keys-changed', callback: (_source: this) => void ): number; emit(signal: 'keys-changed'): void; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](): Window; // Members close(): void; destroy(): void; fullscreen(): void; fullscreen_on_monitor(monitor: Gdk.Monitor): void; get_application(): Application | null; get_child(): Widget | null; get_decorated(): boolean; get_default_size(): [number | null, number | null]; get_default_widget(): Widget | null; get_deletable(): boolean; get_destroy_with_parent(): boolean; get_focus(): Widget | null; get_focus_visible(): boolean; get_group(): WindowGroup; get_hide_on_close(): boolean; get_icon_name(): string | null; get_mnemonics_visible(): boolean; get_modal(): boolean; get_resizable(): boolean; get_title(): string | null; get_titlebar(): Widget | null; get_transient_for(): Window | null; has_group(): boolean; is_fullscreen(): boolean; is_maximized(): boolean; maximize(): void; minimize(): void; present(): void; present_with_time(timestamp: number): void; set_application(application?: Application | null): void; set_child(child?: Widget | null): void; set_decorated(setting: boolean): void; set_default_size(width: number, height: number): void; set_default_widget(default_widget?: Widget | null): void; set_deletable(setting: boolean): void; set_destroy_with_parent(setting: boolean): void; set_display(display: Gdk.Display): void; set_focus(focus?: Widget | null): void; set_focus_visible(setting: boolean): void; set_hide_on_close(setting: boolean): void; set_icon_name(name?: string | null): void; set_mnemonics_visible(setting: boolean): void; set_modal(modal: boolean): void; set_resizable(resizable: boolean): void; set_startup_id(startup_id: string): void; set_title(title?: string | null): void; set_titlebar(titlebar?: Widget | null): void; set_transient_for(parent?: Window | null): void; unfullscreen(): void; unmaximize(): void; unminimize(): void; vfunc_activate_default(): void; vfunc_activate_focus(): void; vfunc_close_request(): boolean; vfunc_enable_debugging(toggle: boolean): boolean; vfunc_keys_changed(): void; static get_default_icon_name(): string | null; static get_toplevels(): Gio.ListModel; static list_toplevels(): Widget[]; static set_auto_startup_notification(setting: boolean): void; static set_default_icon_name(name: string): void; static set_interactive_debugging(enable: boolean): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; get_renderer(): Gsk.Renderer; get_surface(): Gdk.Surface; get_surface_transform(): [number, number]; realize(): void; unrealize(): void; get_display(): Gdk.Display; vfunc_add_controller(controller: ShortcutController): void; vfunc_remove_controller(controller: ShortcutController): void; } export namespace WindowControls { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; decoration_layout: string; decorationLayout: string; empty: boolean; side: PackType; } } export class WindowControls extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<WindowControls>; constructor( properties?: Partial<WindowControls.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<WindowControls.ConstructorProperties>, ...args: any[] ): void; // Properties decoration_layout: string; decorationLayout: string; empty: boolean; side: PackType; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](side: PackType): WindowControls; // Members get_decoration_layout(): string | null; get_empty(): boolean; get_side(): PackType; set_decoration_layout(layout?: string | null): void; set_side(side: PackType): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export namespace WindowGroup { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class WindowGroup extends GObject.Object { static $gtype: GObject.GType<WindowGroup>; constructor( properties?: Partial<WindowGroup.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<WindowGroup.ConstructorProperties>, ...args: any[] ): void; // Fields priv: WindowGroupPrivate; // Constructors static ['new'](): WindowGroup; // Members add_window(window: Window): void; list_windows(): Window[]; remove_window(window: Window): void; } export namespace WindowHandle { export interface ConstructorProperties extends Widget.ConstructorProperties { [key: string]: any; child: Widget; } } export class WindowHandle extends Widget implements Accessible, Buildable, ConstraintTarget { static $gtype: GObject.GType<WindowHandle>; constructor( properties?: Partial<WindowHandle.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<WindowHandle.ConstructorProperties>, ...args: any[] ): void; // Properties child: Widget; // Implemented Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Constructors static ['new'](): WindowHandle; // Members get_child(): Widget | null; set_child(child?: Widget | null): void; // Implemented Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export class Bitset { static $gtype: GObject.GType<Bitset>; constructor(); constructor(copy: Bitset); // Constructors static new_empty(): Bitset; static new_range(start: number, n_items: number): Bitset; // Members add(value: number): boolean; add_range(start: number, n_items: number): void; add_range_closed(first: number, last: number): void; add_rectangle( start: number, width: number, height: number, stride: number ): void; contains(value: number): boolean; copy(): Bitset; difference(other: Bitset): void; equals(other: Bitset): boolean; get_maximum(): number; get_minimum(): number; get_nth(nth: number): number; get_size(): number; get_size_in_range(first: number, last: number): number; intersect(other: Bitset): void; is_empty(): boolean; ref(): Bitset; remove(value: number): boolean; remove_all(): void; remove_range(start: number, n_items: number): void; remove_range_closed(first: number, last: number): void; remove_rectangle( start: number, width: number, height: number, stride: number ): void; shift_left(amount: number): void; shift_right(amount: number): void; splice(position: number, removed: number, added: number): void; subtract(other: Bitset): void; union(other: Bitset): void; unref(): void; } export class BitsetIter { static $gtype: GObject.GType<BitsetIter>; constructor(copy: BitsetIter); // Fields private_data: any[]; // Members get_value(): number; is_valid(): boolean; next(): [boolean, number | null]; previous(): [boolean, number | null]; static init_at( set: Bitset, target: number ): [boolean, BitsetIter, number | null]; static init_first(set: Bitset): [boolean, BitsetIter, number | null]; static init_last(set: Bitset): [boolean, BitsetIter, number | null]; } export class Border { static $gtype: GObject.GType<Border>; constructor(); constructor( properties?: Partial<{ left?: number; right?: number; top?: number; bottom?: number; }> ); constructor(copy: Border); // Fields left: number; right: number; top: number; bottom: number; // Constructors static ['new'](): Border; // Members copy(): Border; free(): void; } export class BuildableParseContext { static $gtype: GObject.GType<BuildableParseContext>; constructor(copy: BuildableParseContext); // Members get_element(): string | null; get_element_stack(): string[]; get_position(): [number | null, number | null]; pop(): any | null; push(parser: BuildableParser, user_data?: any | null): void; } export class BuildableParser { static $gtype: GObject.GType<BuildableParser>; constructor(copy: BuildableParser); // Fields padding?: any[]; } export class ButtonPrivate { static $gtype: GObject.GType<ButtonPrivate>; constructor(copy: ButtonPrivate); } export class CellAreaContextPrivate { static $gtype: GObject.GType<CellAreaContextPrivate>; constructor(copy: CellAreaContextPrivate); } export class CellRendererClassPrivate { static $gtype: GObject.GType<CellRendererClassPrivate>; constructor(copy: CellRendererClassPrivate); } export class CellRendererPrivate { static $gtype: GObject.GType<CellRendererPrivate>; constructor(copy: CellRendererPrivate); } export class CssLocation { static $gtype: GObject.GType<CssLocation>; constructor( properties?: Partial<{ bytes?: number; chars?: number; lines?: number; line_bytes?: number; line_chars?: number; }> ); constructor(copy: CssLocation); // Fields bytes: number; chars: number; lines: number; line_bytes: number; line_chars: number; } export class CssProviderPrivate { static $gtype: GObject.GType<CssProviderPrivate>; constructor(copy: CssProviderPrivate); } export class CssSection { static $gtype: GObject.GType<CssSection>; constructor(file: Gio.File | null, start: CssLocation, end: CssLocation); constructor(copy: CssSection); // Constructors static ['new']( file: Gio.File | null, start: CssLocation, end: CssLocation ): CssSection; // Members get_end_location(): CssLocation; get_file(): Gio.File; get_parent(): CssSection | null; get_start_location(): CssLocation; print(string: GLib.String): void; ref(): CssSection; to_string(): string; unref(): void; } export class CssStyleChange { static $gtype: GObject.GType<CssStyleChange>; constructor(copy: CssStyleChange); } export class ExpressionWatch { static $gtype: GObject.GType<ExpressionWatch>; constructor(copy: ExpressionWatch); // Members evaluate(value: any): boolean; ref(): ExpressionWatch; unref(): void; unwatch(): void; } export class IMContextSimplePrivate { static $gtype: GObject.GType<IMContextSimplePrivate>; constructor(copy: IMContextSimplePrivate); } export class IMMulticontextPrivate { static $gtype: GObject.GType<IMMulticontextPrivate>; constructor(copy: IMMulticontextPrivate); } export class ListStorePrivate { static $gtype: GObject.GType<ListStorePrivate>; constructor(copy: ListStorePrivate); } export class MountOperationPrivate { static $gtype: GObject.GType<MountOperationPrivate>; constructor(copy: MountOperationPrivate); } export class PadActionEntry { static $gtype: GObject.GType<PadActionEntry>; constructor(copy: PadActionEntry); // Fields type: PadActionType; index: number; mode: number; label: string; action_name: string; } export class PageRange { static $gtype: GObject.GType<PageRange>; constructor( properties?: Partial<{ start?: number; end?: number; }> ); constructor(copy: PageRange); // Fields start: number; end: number; } export class PaperSize { static $gtype: GObject.GType<PaperSize>; constructor(name?: string | null); constructor(copy: PaperSize); // Constructors static ['new'](name?: string | null): PaperSize; static new_custom( name: string, display_name: string, width: number, height: number, unit: Unit ): PaperSize; static new_from_gvariant(variant: GLib.Variant): PaperSize; static new_from_ipp( ipp_name: string, width: number, height: number ): PaperSize; static new_from_key_file( key_file: GLib.KeyFile, group_name?: string | null ): PaperSize; static new_from_ppd( ppd_name: string, ppd_display_name: string, width: number, height: number ): PaperSize; // Members copy(): PaperSize; free(): void; get_default_bottom_margin(unit: Unit): number; get_default_left_margin(unit: Unit): number; get_default_right_margin(unit: Unit): number; get_default_top_margin(unit: Unit): number; get_display_name(): string; get_height(unit: Unit): number; get_name(): string; get_ppd_name(): string; get_width(unit: Unit): number; is_custom(): boolean; is_equal(size2: PaperSize): boolean; is_ipp(): boolean; set_size(width: number, height: number, unit: Unit): void; to_gvariant(): GLib.Variant; to_key_file(key_file: GLib.KeyFile, group_name: string): void; static get_default(): string; static get_paper_sizes(include_custom: boolean): PaperSize[]; } export class PrintOperationPrivate { static $gtype: GObject.GType<PrintOperationPrivate>; constructor(copy: PrintOperationPrivate); } export class RecentData { static $gtype: GObject.GType<RecentData>; constructor(copy: RecentData); // Fields display_name: string; description: string; mime_type: string; app_name: string; app_exec: string; groups: string[]; is_private: boolean; } export class RecentInfo { static $gtype: GObject.GType<RecentInfo>; constructor(copy: RecentInfo); // Members create_app_info(app_name?: string | null): Gio.AppInfo | null; exists(): boolean; get_added(): GLib.DateTime; get_age(): number; get_application_info( app_name: string ): [boolean, string, number, GLib.DateTime]; get_applications(): string[]; get_description(): string; get_display_name(): string; get_gicon(): Gio.Icon | null; get_groups(): string[]; get_mime_type(): string; get_modified(): GLib.DateTime; get_private_hint(): boolean; get_short_name(): string; get_uri(): string; get_uri_display(): string | null; get_visited(): GLib.DateTime; has_application(app_name: string): boolean; has_group(group_name: string): boolean; is_local(): boolean; last_application(): string; match(info_b: RecentInfo): boolean; ref(): RecentInfo; unref(): void; } export class RecentManagerPrivate { static $gtype: GObject.GType<RecentManagerPrivate>; constructor(copy: RecentManagerPrivate); } export class RequestedSize { static $gtype: GObject.GType<RequestedSize>; constructor( properties?: Partial<{ data?: any; minimum_size?: number; natural_size?: number; }> ); constructor(copy: RequestedSize); // Fields data: any; minimum_size: number; natural_size: number; } export class Requisition { static $gtype: GObject.GType<Requisition>; constructor(); constructor( properties?: Partial<{ width?: number; height?: number; }> ); constructor(copy: Requisition); // Fields width: number; height: number; // Constructors static ['new'](): Requisition; // Members copy(): Requisition; free(): void; } export class SettingsValue { static $gtype: GObject.GType<SettingsValue>; constructor(copy: SettingsValue); // Fields origin: string; value: GObject.Value; } export class TextBTree { static $gtype: GObject.GType<TextBTree>; constructor(copy: TextBTree); } export class TextBufferPrivate { static $gtype: GObject.GType<TextBufferPrivate>; constructor(copy: TextBufferPrivate); } export class TextIter { static $gtype: GObject.GType<TextIter>; constructor( properties?: Partial<{ dummy1?: any; dummy2?: any; dummy3?: number; dummy4?: number; dummy5?: number; dummy6?: number; dummy7?: number; dummy8?: number; dummy9?: any; dummy10?: any; dummy11?: number; dummy12?: number; dummy13?: number; dummy14?: any; }> ); constructor(copy: TextIter); // Fields dummy1: any; dummy2: any; dummy3: number; dummy4: number; dummy5: number; dummy6: number; dummy7: number; dummy8: number; dummy9: any; dummy10: any; dummy11: number; dummy12: number; dummy13: number; dummy14: any; // Members assign(other: TextIter): void; backward_char(): boolean; backward_chars(count: number): boolean; backward_cursor_position(): boolean; backward_cursor_positions(count: number): boolean; backward_find_char( pred: TextCharPredicate, limit?: TextIter | null ): boolean; backward_line(): boolean; backward_lines(count: number): boolean; backward_search( str: string, flags: TextSearchFlags, limit?: TextIter | null ): [boolean, TextIter | null, TextIter | null]; backward_sentence_start(): boolean; backward_sentence_starts(count: number): boolean; backward_to_tag_toggle(tag?: TextTag | null): boolean; backward_visible_cursor_position(): boolean; backward_visible_cursor_positions(count: number): boolean; backward_visible_line(): boolean; backward_visible_lines(count: number): boolean; backward_visible_word_start(): boolean; backward_visible_word_starts(count: number): boolean; backward_word_start(): boolean; backward_word_starts(count: number): boolean; can_insert(default_editability: boolean): boolean; compare(rhs: TextIter): number; copy(): TextIter; editable(default_setting: boolean): boolean; ends_line(): boolean; ends_sentence(): boolean; ends_tag(tag?: TextTag | null): boolean; ends_word(): boolean; equal(rhs: TextIter): boolean; forward_char(): boolean; forward_chars(count: number): boolean; forward_cursor_position(): boolean; forward_cursor_positions(count: number): boolean; forward_find_char( pred: TextCharPredicate, limit?: TextIter | null ): boolean; forward_line(): boolean; forward_lines(count: number): boolean; forward_search( str: string, flags: TextSearchFlags, limit?: TextIter | null ): [boolean, TextIter | null, TextIter | null]; forward_sentence_end(): boolean; forward_sentence_ends(count: number): boolean; forward_to_end(): void; forward_to_line_end(): boolean; forward_to_tag_toggle(tag?: TextTag | null): boolean; forward_visible_cursor_position(): boolean; forward_visible_cursor_positions(count: number): boolean; forward_visible_line(): boolean; forward_visible_lines(count: number): boolean; forward_visible_word_end(): boolean; forward_visible_word_ends(count: number): boolean; forward_word_end(): boolean; forward_word_ends(count: number): boolean; free(): void; get_buffer(): TextBuffer; get_bytes_in_line(): number; get_char(): number; get_chars_in_line(): number; get_child_anchor(): TextChildAnchor; get_language(): Pango.Language; get_line(): number; get_line_index(): number; get_line_offset(): number; get_marks(): TextMark[]; get_offset(): number; get_paintable(): Gdk.Paintable; get_slice(end: TextIter): string; get_tags(): TextTag[]; get_text(end: TextIter): string; get_toggled_tags(toggled_on: boolean): TextTag[]; get_visible_line_index(): number; get_visible_line_offset(): number; get_visible_slice(end: TextIter): string; get_visible_text(end: TextIter): string; has_tag(tag: TextTag): boolean; in_range(start: TextIter, end: TextIter): boolean; inside_sentence(): boolean; inside_word(): boolean; is_cursor_position(): boolean; is_end(): boolean; is_start(): boolean; order(second: TextIter): void; set_line(line_number: number): void; set_line_index(byte_on_line: number): void; set_line_offset(char_on_line: number): void; set_offset(char_offset: number): void; set_visible_line_index(byte_on_line: number): void; set_visible_line_offset(char_on_line: number): void; starts_line(): boolean; starts_sentence(): boolean; starts_tag(tag?: TextTag | null): boolean; starts_word(): boolean; toggles_tag(tag?: TextTag | null): boolean; } export class TextTagPrivate { static $gtype: GObject.GType<TextTagPrivate>; constructor(copy: TextTagPrivate); } export class TextViewPrivate { static $gtype: GObject.GType<TextViewPrivate>; constructor(copy: TextViewPrivate); } export class TreeIter { static $gtype: GObject.GType<TreeIter>; constructor( properties?: Partial<{ stamp?: number; user_data?: any; user_data2?: any; user_data3?: any; }> ); constructor(copy: TreeIter); // Fields stamp: number; user_data: any; user_data2: any; user_data3: any; // Members copy(): TreeIter; free(): void; } export class TreeModelFilterPrivate { static $gtype: GObject.GType<TreeModelFilterPrivate>; constructor(copy: TreeModelFilterPrivate); } export class TreeModelSortPrivate { static $gtype: GObject.GType<TreeModelSortPrivate>; constructor(copy: TreeModelSortPrivate); } export class TreePath { static $gtype: GObject.GType<TreePath>; constructor(); constructor(copy: TreePath); // Constructors static ['new'](): TreePath; static new_first(): TreePath; static new_from_indices(indices: number[]): TreePath; static new_from_string(path: string): TreePath; // Members append_index(index_: number): void; compare(b: TreePath): number; copy(): TreePath; down(): void; free(): void; get_depth(): number; get_indices(): number[]; is_ancestor(descendant: TreePath): boolean; is_descendant(ancestor: TreePath): boolean; next(): void; prepend_index(index_: number): void; prev(): boolean; to_string(): string | null; up(): boolean; } export class TreeRowReference { static $gtype: GObject.GType<TreeRowReference>; constructor(model: TreeModel, path: TreePath); constructor(copy: TreeRowReference); // Constructors static ['new'](model: TreeModel, path: TreePath): TreeRowReference; static new_proxy( proxy: GObject.Object, model: TreeModel, path: TreePath ): TreeRowReference; // Members copy(): TreeRowReference; free(): void; get_model(): TreeModel; get_path(): TreePath | null; valid(): boolean; static deleted(proxy: GObject.Object, path: TreePath): void; static inserted(proxy: GObject.Object, path: TreePath): void; } export class TreeStorePrivate { static $gtype: GObject.GType<TreeStorePrivate>; constructor(copy: TreeStorePrivate); } export class WidgetClassPrivate { static $gtype: GObject.GType<WidgetClassPrivate>; constructor(copy: WidgetClassPrivate); } export class WidgetPrivate { static $gtype: GObject.GType<WidgetPrivate>; constructor(copy: WidgetPrivate); } export class WindowGroupPrivate { static $gtype: GObject.GType<WindowGroupPrivate>; constructor(copy: WindowGroupPrivate); } export interface AccessibleNamespace { $gtype: GObject.GType<Accessible>; prototype: AccessiblePrototype; } export type Accessible = AccessiblePrototype; export interface AccessiblePrototype extends GObject.Object { // Properties accessible_role: AccessibleRole; accessibleRole: AccessibleRole; // Members get_accessible_role(): AccessibleRole; reset_property(property: AccessibleProperty): void; reset_relation(relation: AccessibleRelation): void; reset_state(state: AccessibleState): void; update_property( properties: AccessibleProperty[], values: GObject.Value[] ): void; update_relation( relations: AccessibleRelation[], values: GObject.Value[] ): void; update_state(states: AccessibleState[], values: GObject.Value[]): void; } export const Accessible: AccessibleNamespace; export interface ActionableNamespace { $gtype: GObject.GType<Actionable>; prototype: ActionablePrototype; } export type Actionable = ActionablePrototype; export interface ActionablePrototype extends Widget { // Properties action_name: string; actionName: string; action_target: GLib.Variant; actionTarget: GLib.Variant; // Members get_action_name(): string | null; get_action_target_value(): GLib.Variant | null; set_action_name(action_name?: string | null): void; set_action_target_value(target_value?: GLib.Variant | null): void; set_detailed_action_name(detailed_action_name: string): void; vfunc_get_action_name(): string | null; vfunc_get_action_target_value(): GLib.Variant | null; vfunc_set_action_name(action_name?: string | null): void; vfunc_set_action_target_value(target_value?: GLib.Variant | null): void; } export const Actionable: ActionableNamespace; export interface AppChooserNamespace { $gtype: GObject.GType<AppChooser>; prototype: AppChooserPrototype; } export type AppChooser = AppChooserPrototype; export interface AppChooserPrototype extends Widget { // Properties content_type: string; contentType: string; // Members get_app_info(): Gio.AppInfo | null; get_content_type(): string; refresh(): void; } export const AppChooser: AppChooserNamespace; export interface BuildableNamespace { $gtype: GObject.GType<Buildable>; prototype: BuildablePrototype; } export type Buildable = BuildablePrototype; export interface BuildablePrototype extends GObject.Object { // Members get_buildable_id(): string; vfunc_add_child( builder: Builder, child: GObject.Object, type?: string | null ): void; vfunc_custom_finished( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_end( builder: Builder, child: GObject.Object | null, tagname: string, data?: any | null ): void; vfunc_custom_tag_start( builder: Builder, child: GObject.Object | null, tagname: string ): [boolean, BuildableParser, any | null]; vfunc_get_id(): string; vfunc_get_internal_child<T = GObject.Object>( builder: Builder, childname: string ): T; vfunc_parser_finished(builder: Builder): void; vfunc_set_buildable_property( builder: Builder, name: string, value: any ): void; vfunc_set_id(id: string): void; } export const Buildable: BuildableNamespace; export interface BuilderScopeNamespace { $gtype: GObject.GType<BuilderScope>; prototype: BuilderScopePrototype; } export type BuilderScope = BuilderScopePrototype; export interface BuilderScopePrototype extends GObject.Object { // Members vfunc_create_closure( builder: Builder, function_name: string, flags: BuilderClosureFlags, object: GObject.Object ): GObject.Closure; vfunc_get_type_from_function( builder: Builder, function_name: string ): GObject.GType; vfunc_get_type_from_name( builder: Builder, type_name: string ): GObject.GType; } export const BuilderScope: BuilderScopeNamespace; export interface CellEditableNamespace { $gtype: GObject.GType<CellEditable>; prototype: CellEditablePrototype; } export type CellEditable = CellEditablePrototype; export interface CellEditablePrototype extends Widget { // Properties editing_canceled: boolean; editingCanceled: boolean; // Members editing_done(): void; remove_widget(): void; start_editing(event?: Gdk.Event | null): void; vfunc_editing_done(): void; vfunc_remove_widget(): void; vfunc_start_editing(event?: Gdk.Event | null): void; } export const CellEditable: CellEditableNamespace; export interface CellLayoutNamespace { $gtype: GObject.GType<CellLayout>; prototype: CellLayoutPrototype; } export type CellLayout = CellLayoutPrototype; export interface CellLayoutPrototype extends GObject.Object { // Members add_attribute(cell: CellRenderer, attribute: string, column: number): void; clear(): void; clear_attributes(cell: CellRenderer): void; get_area(): CellArea | null; get_cells(): CellRenderer[]; pack_end(cell: CellRenderer, expand: boolean): void; pack_start(cell: CellRenderer, expand: boolean): void; reorder(cell: CellRenderer, position: number): void; set_cell_data_func( cell: CellRenderer, func?: CellLayoutDataFunc | null ): void; vfunc_add_attribute( cell: CellRenderer, attribute: string, column: number ): void; vfunc_clear(): void; vfunc_clear_attributes(cell: CellRenderer): void; vfunc_get_area(): CellArea | null; vfunc_get_cells(): CellRenderer[]; vfunc_pack_end(cell: CellRenderer, expand: boolean): void; vfunc_pack_start(cell: CellRenderer, expand: boolean): void; vfunc_reorder(cell: CellRenderer, position: number): void; vfunc_set_cell_data_func( cell: CellRenderer, func?: CellLayoutDataFunc | null ): void; } export const CellLayout: CellLayoutNamespace; export interface ColorChooserNamespace { $gtype: GObject.GType<ColorChooser>; prototype: ColorChooserPrototype; } export type ColorChooser = ColorChooserPrototype; export interface ColorChooserPrototype extends GObject.Object { // Properties rgba: Gdk.RGBA; use_alpha: boolean; useAlpha: boolean; // Members add_palette( orientation: Orientation, colors_per_line: number, colors?: Gdk.RGBA[] | null ): void; get_rgba(): Gdk.RGBA; get_use_alpha(): boolean; set_rgba(color: Gdk.RGBA): void; set_use_alpha(use_alpha: boolean): void; vfunc_add_palette( orientation: Orientation, colors_per_line: number, colors?: Gdk.RGBA[] | null ): void; vfunc_color_activated(color: Gdk.RGBA): void; vfunc_get_rgba(): Gdk.RGBA; vfunc_set_rgba(color: Gdk.RGBA): void; } export const ColorChooser: ColorChooserNamespace; export interface ConstraintTargetNamespace { $gtype: GObject.GType<ConstraintTarget>; prototype: ConstraintTargetPrototype; } export type ConstraintTarget = ConstraintTargetPrototype; export type ConstraintTargetPrototype = GObject.Object; export const ConstraintTarget: ConstraintTargetNamespace; export interface EditableNamespace { $gtype: GObject.GType<Editable>; prototype: EditablePrototype; delegate_get_property( object: GObject.Object, prop_id: number, value: any, pspec: GObject.ParamSpec ): boolean; delegate_set_property( object: GObject.Object, prop_id: number, value: any, pspec: GObject.ParamSpec ): boolean; install_properties( object_class: GObject.Object, first_prop: number ): number; } export type Editable = EditablePrototype; export interface EditablePrototype extends Widget { // Properties cursor_position: number; cursorPosition: number; editable: boolean; enable_undo: boolean; enableUndo: boolean; max_width_chars: number; maxWidthChars: number; selection_bound: number; selectionBound: number; text: string; width_chars: number; widthChars: number; xalign: number; // Members delete_selection(): void; delete_text(start_pos: number, end_pos: number): void; finish_delegate(): void; get_alignment(): number; get_chars(start_pos: number, end_pos: number): string; get_delegate(): Editable | null; get_editable(): boolean; get_enable_undo(): boolean; get_max_width_chars(): number; get_position(): number; get_selection_bounds(): [boolean, number | null, number | null]; get_text(): string; get_width_chars(): number; init_delegate(): void; insert_text(text: string, length: number, position: number): number; select_region(start_pos: number, end_pos: number): void; set_alignment(xalign: number): void; set_editable(is_editable: boolean): void; set_enable_undo(enable_undo: boolean): void; set_max_width_chars(n_chars: number): void; set_position(position: number): void; set_text(text: string): void; set_width_chars(n_chars: number): void; vfunc_changed(): void; vfunc_delete_text(start_pos: number, end_pos: number): void; vfunc_do_delete_text(start_pos: number, end_pos: number): void; vfunc_do_insert_text( text: string, length: number, position: number ): number; vfunc_get_delegate(): Editable | null; vfunc_get_selection_bounds(): [boolean, number | null, number | null]; vfunc_get_text(): string; vfunc_insert_text(text: string, length: number, position: number): number; vfunc_set_selection_bounds(start_pos: number, end_pos: number): void; } export const Editable: EditableNamespace; export interface FileChooserNamespace { $gtype: GObject.GType<FileChooser>; prototype: FileChooserPrototype; } export type FileChooser = FileChooserPrototype; export interface FileChooserPrototype extends GObject.Object { // Properties action: FileChooserAction; create_folders: boolean; createFolders: boolean; filter: FileFilter; filters: Gio.ListModel; select_multiple: boolean; selectMultiple: boolean; shortcut_folders: Gio.ListModel; shortcutFolders: Gio.ListModel; // Members add_choice( id: string, label: string, options?: string[] | null, option_labels?: string[] | null ): void; add_filter(filter: FileFilter): void; add_shortcut_folder(folder: Gio.File): boolean; get_action(): FileChooserAction; get_choice(id: string): string; get_create_folders(): boolean; get_current_folder(): Gio.File; get_current_name(): string; get_file(): Gio.File; get_files(): Gio.ListModel; get_filter(): FileFilter | null; get_filters(): Gio.ListModel; get_select_multiple(): boolean; get_shortcut_folders(): Gio.ListModel; remove_choice(id: string): void; remove_filter(filter: FileFilter): void; remove_shortcut_folder(folder: Gio.File): boolean; set_action(action: FileChooserAction): void; set_choice(id: string, option: string): void; set_create_folders(create_folders: boolean): void; set_current_folder(file: Gio.File): boolean; set_current_name(name: string): void; set_file(file: Gio.File): boolean; set_filter(filter: FileFilter): void; set_select_multiple(select_multiple: boolean): void; } export const FileChooser: FileChooserNamespace; export interface FontChooserNamespace { $gtype: GObject.GType<FontChooser>; prototype: FontChooserPrototype; } export type FontChooser = FontChooserPrototype; export interface FontChooserPrototype extends GObject.Object { // Properties font: string; font_desc: Pango.FontDescription; fontDesc: Pango.FontDescription; font_features: string; fontFeatures: string; language: string; level: FontChooserLevel; preview_text: string; previewText: string; show_preview_entry: boolean; showPreviewEntry: boolean; // Members get_font(): string | null; get_font_desc(): Pango.FontDescription | null; get_font_face(): Pango.FontFace | null; get_font_family(): Pango.FontFamily | null; get_font_features(): string; get_font_map(): Pango.FontMap | null; get_font_size(): number; get_language(): string; get_level(): FontChooserLevel; get_preview_text(): string; get_show_preview_entry(): boolean; set_filter_func(filter?: FontFilterFunc | null): void; set_font(fontname: string): void; set_font_desc(font_desc: Pango.FontDescription): void; set_font_map(fontmap?: Pango.FontMap | null): void; set_language(language: string): void; set_level(level: FontChooserLevel): void; set_preview_text(text: string): void; set_show_preview_entry(show_preview_entry: boolean): void; vfunc_font_activated(fontname: string): void; vfunc_get_font_face(): Pango.FontFace | null; vfunc_get_font_family(): Pango.FontFamily | null; vfunc_get_font_map(): Pango.FontMap | null; vfunc_get_font_size(): number; vfunc_set_filter_func(filter?: FontFilterFunc | null): void; vfunc_set_font_map(fontmap?: Pango.FontMap | null): void; } export const FontChooser: FontChooserNamespace; export interface NativeNamespace { $gtype: GObject.GType<Native>; prototype: NativePrototype; get_for_surface(surface: Gdk.Surface): Native; } export type Native = NativePrototype; export interface NativePrototype extends Widget { // Members get_renderer(): Gsk.Renderer; get_surface(): Gdk.Surface; get_surface_transform(): [number, number]; realize(): void; unrealize(): void; } export const Native: NativeNamespace; export interface OrientableNamespace { $gtype: GObject.GType<Orientable>; prototype: OrientablePrototype; } export type Orientable = OrientablePrototype; export interface OrientablePrototype extends GObject.Object { // Properties orientation: Orientation; // Members get_orientation(): Orientation; set_orientation(orientation: Orientation): void; } export const Orientable: OrientableNamespace; export interface PrintOperationPreviewNamespace { $gtype: GObject.GType<PrintOperationPreview>; prototype: PrintOperationPreviewPrototype; } export type PrintOperationPreview = PrintOperationPreviewPrototype; export interface PrintOperationPreviewPrototype extends GObject.Object { // Members end_preview(): void; is_selected(page_nr: number): boolean; render_page(page_nr: number): void; vfunc_end_preview(): void; vfunc_got_page_size(context: PrintContext, page_setup: PageSetup): void; vfunc_is_selected(page_nr: number): boolean; vfunc_ready(context: PrintContext): void; vfunc_render_page(page_nr: number): void; } export const PrintOperationPreview: PrintOperationPreviewNamespace; export interface RootNamespace { $gtype: GObject.GType<Root>; prototype: RootPrototype; } export type Root = RootPrototype; export interface RootPrototype extends Native { // Members get_display(): Gdk.Display; get_focus(): Widget | null; set_focus(focus?: Widget | null): void; } export const Root: RootNamespace; export interface ScrollableNamespace { $gtype: GObject.GType<Scrollable>; prototype: ScrollablePrototype; } export type Scrollable = ScrollablePrototype; export interface ScrollablePrototype extends GObject.Object { // Properties hadjustment: Adjustment; hscroll_policy: ScrollablePolicy; hscrollPolicy: ScrollablePolicy; vadjustment: Adjustment; vscroll_policy: ScrollablePolicy; vscrollPolicy: ScrollablePolicy; // Members get_border(): [boolean, Border]; get_hadjustment(): Adjustment; get_hscroll_policy(): ScrollablePolicy; get_vadjustment(): Adjustment; get_vscroll_policy(): ScrollablePolicy; set_hadjustment(hadjustment?: Adjustment | null): void; set_hscroll_policy(policy: ScrollablePolicy): void; set_vadjustment(vadjustment?: Adjustment | null): void; set_vscroll_policy(policy: ScrollablePolicy): void; vfunc_get_border(): [boolean, Border]; } export const Scrollable: ScrollableNamespace; export interface SelectionModelNamespace { $gtype: GObject.GType<SelectionModel>; prototype: SelectionModelPrototype; } export type SelectionModel< A extends GObject.Object = GObject.Object > = SelectionModelPrototype<A>; export interface SelectionModelPrototype< A extends GObject.Object = GObject.Object > extends Gio.ListModel<A> { // Members get_selection(): Bitset; get_selection_in_range(position: number, n_items: number): Bitset; is_selected(position: number): boolean; select_all(): boolean; select_item(position: number, unselect_rest: boolean): boolean; select_range( position: number, n_items: number, unselect_rest: boolean ): boolean; selection_changed(position: number, n_items: number): void; set_selection(selected: Bitset, mask: Bitset): boolean; unselect_all(): boolean; unselect_item(position: number): boolean; unselect_range(position: number, n_items: number): boolean; vfunc_get_selection_in_range(position: number, n_items: number): Bitset; vfunc_is_selected(position: number): boolean; vfunc_select_all(): boolean; vfunc_select_item(position: number, unselect_rest: boolean): boolean; vfunc_select_range( position: number, n_items: number, unselect_rest: boolean ): boolean; vfunc_set_selection(selected: Bitset, mask: Bitset): boolean; vfunc_unselect_all(): boolean; vfunc_unselect_item(position: number): boolean; vfunc_unselect_range(position: number, n_items: number): boolean; } export const SelectionModel: SelectionModelNamespace; export interface ShortcutManagerNamespace { $gtype: GObject.GType<ShortcutManager>; prototype: ShortcutManagerPrototype; } export type ShortcutManager = ShortcutManagerPrototype; export interface ShortcutManagerPrototype extends GObject.Object { // Members vfunc_add_controller(controller: ShortcutController): void; vfunc_remove_controller(controller: ShortcutController): void; } export const ShortcutManager: ShortcutManagerNamespace; export interface StyleProviderNamespace { $gtype: GObject.GType<StyleProvider>; prototype: StyleProviderPrototype; } export type StyleProvider = StyleProviderPrototype; export type StyleProviderPrototype = GObject.Object; export const StyleProvider: StyleProviderNamespace; export interface TreeDragDestNamespace { $gtype: GObject.GType<TreeDragDest>; prototype: TreeDragDestPrototype; } export type TreeDragDest = TreeDragDestPrototype; export interface TreeDragDestPrototype extends GObject.Object { // Members drag_data_received(dest: TreePath, value: any): boolean; row_drop_possible(dest_path: TreePath, value: any): boolean; vfunc_drag_data_received(dest: TreePath, value: any): boolean; vfunc_row_drop_possible(dest_path: TreePath, value: any): boolean; } export const TreeDragDest: TreeDragDestNamespace; export interface TreeDragSourceNamespace { $gtype: GObject.GType<TreeDragSource>; prototype: TreeDragSourcePrototype; } export type TreeDragSource = TreeDragSourcePrototype; export interface TreeDragSourcePrototype extends GObject.Object { // Members drag_data_delete(path: TreePath): boolean; drag_data_get(path: TreePath): Gdk.ContentProvider | null; row_draggable(path: TreePath): boolean; vfunc_drag_data_delete(path: TreePath): boolean; vfunc_drag_data_get(path: TreePath): Gdk.ContentProvider | null; vfunc_row_draggable(path: TreePath): boolean; } export const TreeDragSource: TreeDragSourceNamespace; export interface TreeModelNamespace { $gtype: GObject.GType<TreeModel>; prototype: TreeModelPrototype; } export type TreeModel = TreeModelPrototype; export interface TreeModelPrototype extends GObject.Object { // Members filter_new(root?: TreePath | null): TreeModel; foreach(func: TreeModelForeachFunc): void; get_column_type(index_: number): GObject.GType; get_flags(): TreeModelFlags; get_iter(path: TreePath): [boolean, TreeIter]; get_iter_first(): [boolean, TreeIter]; get_iter_from_string(path_string: string): [boolean, TreeIter]; get_n_columns(): number; get_path(iter: TreeIter): TreePath; get_string_from_iter(iter: TreeIter): string | null; get_value(iter: TreeIter, column: number): unknown; iter_children(parent?: TreeIter | null): [boolean, TreeIter]; iter_has_child(iter: TreeIter): boolean; iter_n_children(iter?: TreeIter | null): number; iter_next(iter: TreeIter): boolean; iter_nth_child(parent: TreeIter | null, n: number): [boolean, TreeIter]; iter_parent(child: TreeIter): [boolean, TreeIter]; iter_previous(iter: TreeIter): boolean; ref_node(iter: TreeIter): void; row_changed(path: TreePath, iter: TreeIter): void; row_deleted(path: TreePath): void; row_has_child_toggled(path: TreePath, iter: TreeIter): void; row_inserted(path: TreePath, iter: TreeIter): void; rows_reordered( path: TreePath, iter: TreeIter | null, new_order: number[] ): void; unref_node(iter: TreeIter): void; vfunc_get_column_type(index_: number): GObject.GType; vfunc_get_flags(): TreeModelFlags; vfunc_get_iter(path: TreePath): [boolean, TreeIter]; vfunc_get_n_columns(): number; vfunc_get_path(iter: TreeIter): TreePath; vfunc_get_value(iter: TreeIter, column: number): unknown; vfunc_iter_children(parent?: TreeIter | null): [boolean, TreeIter]; vfunc_iter_has_child(iter: TreeIter): boolean; vfunc_iter_n_children(iter?: TreeIter | null): number; vfunc_iter_next(iter: TreeIter): boolean; vfunc_iter_nth_child( parent: TreeIter | null, n: number ): [boolean, TreeIter]; vfunc_iter_parent(child: TreeIter): [boolean, TreeIter]; vfunc_iter_previous(iter: TreeIter): boolean; vfunc_ref_node(iter: TreeIter): void; vfunc_row_changed(path: TreePath, iter: TreeIter): void; vfunc_row_deleted(path: TreePath): void; vfunc_row_has_child_toggled(path: TreePath, iter: TreeIter): void; vfunc_row_inserted(path: TreePath, iter: TreeIter): void; vfunc_unref_node(iter: TreeIter): void; } export const TreeModel: TreeModelNamespace; export interface TreeSortableNamespace { $gtype: GObject.GType<TreeSortable>; prototype: TreeSortablePrototype; } export type TreeSortable = TreeSortablePrototype; export interface TreeSortablePrototype extends TreeModel { // Members get_sort_column_id(): [boolean, number, SortType]; has_default_sort_func(): boolean; set_default_sort_func( sort_func: TreeIterCompareFunc, destroy?: GLib.DestroyNotify | null ): void; set_sort_column_id(sort_column_id: number, order: SortType): void; set_sort_func( sort_column_id: number, sort_func: TreeIterCompareFunc, destroy?: GLib.DestroyNotify | null ): void; sort_column_changed(): void; vfunc_get_sort_column_id(): [boolean, number, SortType]; vfunc_has_default_sort_func(): boolean; vfunc_set_default_sort_func( sort_func: TreeIterCompareFunc, destroy?: GLib.DestroyNotify | null ): void; vfunc_set_sort_column_id(sort_column_id: number, order: SortType): void; vfunc_set_sort_func( sort_column_id: number, sort_func: TreeIterCompareFunc, destroy?: GLib.DestroyNotify | null ): void; vfunc_sort_column_changed(): void; } export const TreeSortable: TreeSortableNamespace; export type Allocation = Gdk.Rectangle;
the_stack
import React, { useCallback, useMemo, useReducer, useRef, useState, } from 'react' import { Column, useExpanded, useTable } from 'react-table' import { SortEndHandler, SortStartHandler } from 'react-sortable-hoc' import { ChannelTableContentsSet, ChannelTableContentsSetVariables, ChannelTableContentsSet_channel_blokks, } from '__generated__/ChannelTableContentsSet' import { BaseConnectableTypeEnum, ConnectableTypeEnum, SortDirection, Sorts, } from '__generated__/globalTypes' import { ChannelPage_channel } from '__generated__/ChannelPage' import { ChannelTableConnectors_channel_connectors } from '__generated__/ChannelTableConnectors' import Box from 'v2/components/UI/Box' import { usePaginatedBlocks } from 'v2/hooks/usePaginatedBlocks' import { ContentCell } from './components/ContentCell' import { PotentiallyEditableBlockCell } from './components/PotentiallyEditableBlockCell' import { StandardCell } from './components/StandardCell' import { Table } from './components/TableComponents' import ChannelTableHeader from './components/ChannelTableHeader' import { SettingsCell } from './components/SettingsCell' import { ChannelTableBody } from './components/ChannelTableBody' import LoadingRow from './components/LoadingRow' import { SortableTableContainer } from './components/SortableTableContainer' import { ColumnIds, SortAndSortDir, TableData } from './lib/types' import { FIRST_COLUMN_WIDTH } from './lib/constants' import { parsePayload, PusherPayload, usePusher } from 'v2/hooks/usePusher' import { getConnectableType } from 'v2/util/getConnectableType' import { ConnectableTableBlokk, ConnectableTableBlokkVariables, } from '__generated__/ConnectableTableBlokk' import CHANNEL_TABLE_CONTENTS_QUERY from './queries/ChannelTableContents' import CONNECTABLE_TABLE_BLOKK_QUERY from './queries/TableConnectableBlokk' interface ChannelTableQueryProps { id: string channel: ChannelPage_channel } export const STANDARD_HEADERS: Array<Column<TableData>> = [ { Header: 'Content', id: ColumnIds.content, accessor: block => block, Cell: ContentCell, width: FIRST_COLUMN_WIDTH, }, { Header: 'Title', id: ColumnIds.title, Cell: PotentiallyEditableBlockCell, accessor: block => ({ block, attr: 'title' }), width: '30%', }, { Header: 'Added at', id: ColumnIds.addedAt, accessor: block => '__typename' in block && block?.connection?.created_at, Cell: StandardCell, width: '200px', }, { Header: 'Author', id: ColumnIds.author, accessor: block => '__typename' in block && block?.user?.name, Cell: StandardCell, width: '200px', }, { Header: 'Connections', id: ColumnIds.connections, accessor: block => { if ('isNull' in block) { return null } return block.counts?.__typename === 'BlockCounts' ? block.counts.public_channels : block.counts?.connected_to_channels }, Cell: StandardCell, width: '200px', }, { Header: ColumnIds.addSettings, id: ColumnIds.addSettings, accessor: block => ('__typename' in block ? block : null), Cell: SettingsCell, width: '100px', }, ] const sortAndSortDirReducer: React.Reducer<SortAndSortDir, SortAndSortDir> = ( prevState, action ) => { if (prevState.sort === action.sort && prevState.dir === action.dir) { return { sort: Sorts.POSITION, dir: SortDirection.DESC, } } return action } export const ChannelTableQuery: React.FC<ChannelTableQueryProps> = ({ id, channel, }) => { const [sortAndSortDir, setSortAndSortDir] = useReducer( sortAndSortDirReducer, { sort: Sorts.POSITION, dir: SortDirection.DESC } ) const [type, setType] = useState<ConnectableTypeEnum | null>(null) const [ user, setUser, ] = useState<ChannelTableConnectors_channel_connectors | null>(null) const { blocks, getPage, getPageFromIndex, hasQueriedPage, contentCount, addBlock, updateBlock, getBlocksFromCache, moveBlock, removeBlock, loading, } = usePaginatedBlocks< ChannelTableContentsSet, ChannelTableContentsSetVariables, ConnectableTableBlokk, ConnectableTableBlokkVariables >({ channelQuery: CHANNEL_TABLE_CONTENTS_QUERY, direction: sortAndSortDir.dir, sort: sortAndSortDir.sort, channelId: id, type, user_id: user?.id.toString(), per: 25, blockquery: CONNECTABLE_TABLE_BLOKK_QUERY, }) const onItemIntersected = useCallback( (index: number) => { const page = getPageFromIndex(index) if (!hasQueriedPage(page)) { getPage(page) } }, [getPage, getPageFromIndex, hasQueriedPage] ) return ( <ChannelTableContents contentCount={contentCount} blocks={blocks} channel={channel} sortAndSortDir={sortAndSortDir} setSortAndSortDir={setSortAndSortDir} loading={loading} type={type} user={user} setType={setType} setUser={setUser} onItemIntersected={onItemIntersected} addBlock={addBlock} updateBlock={updateBlock} getBlocksFromCache={getBlocksFromCache} moveBlock={moveBlock} removeBlock={removeBlock} /> ) } interface ChannelTableContentsProps { blocks: Array<ChannelTableContentsSet_channel_blokks | null> channel: ChannelPage_channel contentCount: number sortAndSortDir: SortAndSortDir setSortAndSortDir: React.Dispatch<SortAndSortDir> type?: ConnectableTypeEnum user?: ChannelTableConnectors_channel_connectors setType: (value: ConnectableTypeEnum) => void setUser: (value: ChannelTableConnectors_channel_connectors) => void onItemIntersected: (index: number) => void addBlock: () => void loading: boolean updateBlock: (args: { id: string type: BaseConnectableTypeEnum | false }) => Promise<void> getBlocksFromCache: () => Array<ChannelTableContentsSet_channel_blokks | null> | null moveBlock: (args: { oldIndex: number; newIndex: number }) => void removeBlock: (args: { id: number; type: string }) => void } export const ChannelTableContents: React.FC<ChannelTableContentsProps> = ({ blocks, channel, contentCount, sortAndSortDir, setSortAndSortDir, type, user, setType, setUser, onItemIntersected, addBlock, updateBlock, getBlocksFromCache, moveBlock, removeBlock, loading, }) => { /** * Build the table rows */ const tableData = useMemo<Array<TableData>>(() => { const data: Array<TableData> = [] for (let i = 0; i < contentCount; i++) { const block = blocks[i] data.push(block ?? { isNull: true }) } return data }, [blocks, contentCount]) const tableColumns = useMemo<Array<Column<TableData>>>(() => { return STANDARD_HEADERS }, []) const getRowId = useCallback((row: TableData, index: number): string => { const rowId = '__typename' in row ? row.id.toString() : `nullRow${index}` return `${rowId}` }, []) const initialExpandedStateRef = useRef<Record<string, boolean> | undefined>() if (!initialExpandedStateRef.current) { const initialState = {} tableData.forEach(row => { if ('__typename' in row && row.connection) { initialState[row.id.toString()] = row.connection.selected } }) initialExpandedStateRef.current = initialState } const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow, columns, } = useTable<TableData>( { data: tableData, columns: tableColumns, autoResetExpanded: false, getRowId: getRowId, initialState: { expanded: initialExpandedStateRef.current, }, }, useExpanded ) const intersectionObserverCallback = useCallback< (itemIndex: number) => (entries: IntersectionObserverEntry[]) => void >( itemIndex => entries => { const entry = entries[0] if (entry.isIntersecting) { onItemIntersected(itemIndex) } }, [onItemIntersected] ) const updateConnectable = useCallback( ({ id, type }: PusherPayload) => { updateBlock({ id, type }) }, [updateBlock] ) const createdConnectable = useCallback( ({ id, type }: PusherPayload) => { // // This method can be called in a few different cases: // - When a block is added via add block either by you or from another person (via pusher) // - When a block is connected into the channel from another person // - AND when a block in the current channel is connected into another channel // We need to first check if the block already exists in this channel, // if it does, do nothing. Otherwise, proceed. // const cacheBlocks = getBlocksFromCache() if (!cacheBlocks) return const blockIndex = cacheBlocks.findIndex( block => block && block.id === parseInt(id) && getConnectableType(block.__typename) === type ) // If the block already exists, early return if (blockIndex > 0) return // Otherwise proceed. addBlock() }, [getBlocksFromCache, addBlock] ) usePusher({ channelId: channel.id, shouldSubscribe: !!channel?.can?.add_to, onCreated: createdConnectable, onUpdated: updateConnectable, parsePayload: parsePayload, }) const intersectionObserverOptions = useMemo<IntersectionObserverInit>( () => ({ rootMargin: '200px' }), [] ) const onSortEnd = useCallback<SortEndHandler>( ({ oldIndex, newIndex }) => { if (sortAndSortDir.sort === Sorts.POSITION) { moveBlock({ oldIndex, newIndex }) } }, [moveBlock, sortAndSortDir.sort] ) const onSortStart = useCallback<SortStartHandler>(({ node, helper }: any) => { node.childNodes.forEach((td: HTMLTableCellElement, index: number) => { helper.childNodes[index].style.width = `${td.offsetWidth}px !important` }) }, []) const tableRef = useRef<HTMLTableSectionElement>() return ( <Box> <Table {...getTableProps()}> <ChannelTableHeader headerGroups={headerGroups} channel={channel} setSortAndSortDir={setSortAndSortDir} sortAndSortDir={sortAndSortDir} type={type} user={user} setType={setType} setUser={setUser} addBlock={addBlock} /> {loading && ( <tbody {...getTableBodyProps()}> <LoadingRow columnLength={STANDARD_HEADERS.length} /> </tbody> )} {!loading && ( <SortableTableContainer transitionDuration={0} distance={1} useDragHandle helperClass="dragging" axis="y" lockAxis="y" useWindowAsScrollContainer helperContainer={tableRef.current} onSortEnd={onSortEnd} onSortStart={onSortStart} > <tbody {...getTableBodyProps()} ref={tableRef}> <ChannelTableBody key={`${sortAndSortDir.sort}.${sortAndSortDir.dir}`} rows={rows} prepareRow={prepareRow} channel={channel} intersectionObserverCallback={intersectionObserverCallback} columns={columns} intersectionObserverOptions={intersectionObserverOptions} sortAndSortDir={sortAndSortDir} moveBlock={moveBlock} removeBlock={removeBlock} /> </tbody> </SortableTableContainer> )} </Table> </Box> ) }
the_stack
import { defineComponent } from 'vue'; import classNames from '../../../_util/classNames'; import PropTypes from '../../../_util/vue-types'; import addEventListener from '../../../vc-util/Dom/addEventListener'; import warning from '../../../_util/warning'; import { initDefaultProps, getSlot } from '../../../_util/props-util'; import Steps from './Steps'; import Marks from './Marks'; import Handle from '../Handle'; import * as utils from '../utils'; import BaseMixin from '../../../_util/BaseMixin'; import supportsPassive from '../../../_util/supportsPassive'; function noop() {} export default function createSlider(Component) { // const displayName = `ComponentEnhancer(${Component.displayName})` const propTypes = { id: PropTypes.string, min: PropTypes.number, max: PropTypes.number, step: PropTypes.number, marks: PropTypes.object, included: PropTypes.looseBool, prefixCls: PropTypes.string, disabled: PropTypes.looseBool, handle: PropTypes.func, dots: PropTypes.looseBool, vertical: PropTypes.looseBool, reverse: PropTypes.looseBool, minimumTrackStyle: PropTypes.object, // just for compatibility, will be deperecate maximumTrackStyle: PropTypes.object, // just for compatibility, will be deperecate handleStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.arrayOf(PropTypes.object)]), trackStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.arrayOf(PropTypes.object)]), railStyle: PropTypes.object, dotStyle: PropTypes.object, activeDotStyle: PropTypes.object, autofocus: PropTypes.looseBool, draggableTrack: PropTypes.looseBool, }; return defineComponent({ name: 'CreateSlider', mixins: [BaseMixin, Component], inheritAttrs: false, slots: ['mark'], props: initDefaultProps(propTypes, { prefixCls: 'rc-slider', min: 0, max: 100, step: 1, marks: {}, included: true, disabled: false, dots: false, vertical: false, reverse: false, trackStyle: [{}], handleStyle: [{}], railStyle: {}, dotStyle: {}, activeDotStyle: {}, }), data() { const { step, max, min } = this; const isPointDiffEven = isFinite(max - min) ? (max - min) % step === 0 : true; // eslint-disable-line warning( step && Math.floor(step) === step ? isPointDiffEven : true, `Slider[max] - Slider[min] (${max - min}) should be a multiple of Slider[step] (${step})`, ); (this as any).handlesRefs = {}; return {}; }, mounted() { this.$nextTick(() => { // Snapshot testing cannot handle refs, so be sure to null-check this. this.document = this.sliderRef && this.sliderRef.ownerDocument; // this.setHandleRefs() const { autofocus, disabled } = this; if (autofocus && !disabled) { this.focus(); } }); }, beforeUnmount() { this.$nextTick(() => { // if (super.componentWillUnmount) super.componentWillUnmount() this.removeDocumentEvents(); }); }, methods: { defaultHandle({ index, directives, className, style, ...restProps }) { delete restProps.dragging; if (restProps.value === null) { return null; } const handleProps = { ...restProps, class: className, style, key: index, }; return <Handle {...handleProps} />; }, onDown(e, position) { let p = position; const { draggableTrack, vertical: isVertical } = this.$props; const { bounds } = this.$data; const value = draggableTrack && this.positionGetValue ? this.positionGetValue(p) || [] : []; const inPoint = utils.isEventFromHandle(e, this.handlesRefs); this.dragTrack = draggableTrack && bounds.length >= 2 && !inPoint && !value .map((n, i) => { const v = !i ? n >= bounds[i] : true; return i === value.length - 1 ? n <= bounds[i] : v; }) .some(c => !c); if (this.dragTrack) { this.dragOffset = p; this.startBounds = [...bounds]; } else { if (!inPoint) { this.dragOffset = 0; } else { const handlePosition = utils.getHandleCenterPosition(isVertical, e.target); this.dragOffset = p - handlePosition; p = handlePosition; } this.onStart(p); } }, onMouseDown(e) { if (e.button !== 0) { return; } this.removeDocumentEvents(); const isVertical = this.$props.vertical; const position = utils.getMousePosition(isVertical, e); this.onDown(e, position); this.addDocumentMouseEvents(); }, onTouchStart(e) { if (utils.isNotTouchEvent(e)) return; const isVertical = this.vertical; const position = utils.getTouchPosition(isVertical, e); this.onDown(e, position); this.addDocumentTouchEvents(); utils.pauseEvent(e); }, onFocus(e) { const { vertical } = this; if (utils.isEventFromHandle(e, this.handlesRefs) && !this.dragTrack) { const handlePosition = utils.getHandleCenterPosition(vertical, e.target); this.dragOffset = 0; this.onStart(handlePosition); utils.pauseEvent(e); this.__emit('focus', e); } }, onBlur(e) { if (!this.dragTrack) { this.onEnd(); } this.__emit('blur', e); }, onMouseUp() { if (this.handlesRefs[this.prevMovedHandleIndex]) { this.handlesRefs[this.prevMovedHandleIndex].clickFocus(); } }, onMouseMove(e) { if (!this.sliderRef) { this.onEnd(); return; } const position = utils.getMousePosition(this.vertical, e); this.onMove(e, position - this.dragOffset, this.dragTrack, this.startBounds); }, onTouchMove(e) { if (utils.isNotTouchEvent(e) || !this.sliderRef) { this.onEnd(); return; } const position = utils.getTouchPosition(this.vertical, e); this.onMove(e, position - this.dragOffset, this.dragTrack, this.startBounds); }, onKeyDown(e) { if (this.sliderRef && utils.isEventFromHandle(e, this.handlesRefs)) { this.onKeyboard(e); } }, onClickMarkLabel(e, value) { e.stopPropagation(); this.onChange({ sValue: value }); this.setState({ sValue: value }, () => this.onEnd(true)); }, getSliderStart() { const slider = this.sliderRef; const { vertical, reverse } = this; const rect = slider.getBoundingClientRect(); if (vertical) { return reverse ? rect.bottom : rect.top; } return window.pageXOffset + (reverse ? rect.right : rect.left); }, getSliderLength() { const slider = this.sliderRef; if (!slider) { return 0; } const coords = slider.getBoundingClientRect(); return this.vertical ? coords.height : coords.width; }, addDocumentTouchEvents() { // just work for Chrome iOS Safari and Android Browser this.onTouchMoveListener = addEventListener(this.document, 'touchmove', this.onTouchMove); this.onTouchUpListener = addEventListener(this.document, 'touchend', this.onEnd); }, addDocumentMouseEvents() { this.onMouseMoveListener = addEventListener(this.document, 'mousemove', this.onMouseMove); this.onMouseUpListener = addEventListener(this.document, 'mouseup', this.onEnd); }, removeDocumentEvents() { /* eslint-disable no-unused-expressions */ this.onTouchMoveListener && this.onTouchMoveListener.remove(); this.onTouchUpListener && this.onTouchUpListener.remove(); this.onMouseMoveListener && this.onMouseMoveListener.remove(); this.onMouseUpListener && this.onMouseUpListener.remove(); /* eslint-enable no-unused-expressions */ }, focus() { if (this.$props.disabled) { return; } this.handlesRefs[0]?.focus(); }, blur() { if (this.$props.disabled) { return; } Object.keys(this.handlesRefs).forEach(key => { this.handlesRefs[key]?.blur?.(); }); }, calcValue(offset) { const { vertical, min, max } = this; const ratio = Math.abs(Math.max(offset, 0) / this.getSliderLength()); const value = vertical ? (1 - ratio) * (max - min) + min : ratio * (max - min) + min; return value; }, calcValueByPos(position) { const sign = this.reverse ? -1 : +1; const pixelOffset = sign * (position - this.getSliderStart()); const nextValue = this.trimAlignValue(this.calcValue(pixelOffset)); return nextValue; }, calcOffset(value) { const { min, max } = this; const ratio = (value - min) / (max - min); return Math.max(0, ratio * 100); }, saveSlider(slider) { this.sliderRef = slider; }, saveHandle(index, handle) { this.handlesRefs[index] = handle; }, }, render() { const { prefixCls, marks, dots, step, included, disabled, vertical, reverse, min, max, maximumTrackStyle, railStyle, dotStyle, activeDotStyle, id, } = this; const { class: className, style } = this.$attrs; const { tracks, handles } = this.renderSlider(); const sliderClassName = classNames(prefixCls, className, { [`${prefixCls}-with-marks`]: Object.keys(marks).length, [`${prefixCls}-disabled`]: disabled, [`${prefixCls}-vertical`]: vertical, }); const markProps = { vertical, marks, included, lowerBound: this.getLowerBound(), upperBound: this.getUpperBound(), max, min, reverse, class: `${prefixCls}-mark`, onClickLabel: disabled ? noop : this.onClickMarkLabel, }; const touchEvents = { [supportsPassive ? 'onTouchstartPassive' : 'onTouchstart']: disabled ? noop : this.onTouchStart, }; return ( <div id={id} ref={this.saveSlider} tabindex="-1" class={sliderClassName} {...touchEvents} onMousedown={disabled ? noop : this.onMouseDown} onMouseup={disabled ? noop : this.onMouseUp} onKeydown={disabled ? noop : this.onKeyDown} onFocus={disabled ? noop : this.onFocus} onBlur={disabled ? noop : this.onBlur} style={style} > <div class={`${prefixCls}-rail`} style={{ ...maximumTrackStyle, ...railStyle, }} /> {tracks} <Steps prefixCls={prefixCls} vertical={vertical} reverse={reverse} marks={marks} dots={dots} step={step} included={included} lowerBound={this.getLowerBound()} upperBound={this.getUpperBound()} max={max} min={min} dotStyle={dotStyle} activeDotStyle={activeDotStyle} /> {handles} <Marks {...markProps} v-slots={{ mark: this.$slots.mark }} /> {getSlot(this)} </div> ); }, }); }
the_stack
import { waitFor, fireEvent } from '@testing-library/react' import React from 'react' import { queryKey, sleep, mockConsoleError, renderWithClient, setActTimeout, Blink, } from './utils' import { useInfiniteQuery, UseInfiniteQueryResult, QueryClient, QueryCache, } from '../..' interface Result { items: number[] nextId?: number prevId?: number ts: number } const pageSize = 10 const fetchItems = async ( page: number, ts: number, noNext?: boolean, noPrev?: boolean ): Promise<Result> => { await sleep(10) return { items: [...new Array(10)].fill(null).map((_, d) => page * pageSize + d), nextId: noNext ? undefined : page + 1, prevId: noPrev ? undefined : page - 1, ts, } } describe('useInfiniteQuery', () => { const queryCache = new QueryCache() const queryClient = new QueryClient({ queryCache }) it('should return the correct states for a successful query', async () => { const key = queryKey() const states: UseInfiniteQueryResult<number>[] = [] function Page() { const state = useInfiniteQuery( key, ({ pageParam = 0 }) => Number(pageParam), { getNextPageParam: lastPage => lastPage + 1, } ) states.push(state) return null } renderWithClient(queryClient, <Page />) await sleep(100) expect(states.length).toBe(2) expect(states[0]).toEqual({ data: undefined, dataUpdatedAt: 0, error: null, errorUpdatedAt: 0, failureCount: 0, fetchNextPage: expect.any(Function), fetchPreviousPage: expect.any(Function), hasNextPage: undefined, hasPreviousPage: undefined, isError: false, isFetched: false, isFetchedAfterMount: false, isFetching: true, isFetchingNextPage: false, isFetchingPreviousPage: false, isIdle: false, isLoading: true, isLoadingError: false, isPlaceholderData: false, isPreviousData: false, isRefetchError: false, isRefetching: false, isStale: true, isSuccess: false, refetch: expect.any(Function), remove: expect.any(Function), status: 'loading', }) expect(states[1]).toEqual({ data: { pages: [0], pageParams: [undefined] }, dataUpdatedAt: expect.any(Number), error: null, errorUpdatedAt: 0, failureCount: 0, fetchNextPage: expect.any(Function), fetchPreviousPage: expect.any(Function), hasNextPage: true, hasPreviousPage: undefined, isError: false, isFetched: true, isFetchedAfterMount: true, isFetching: false, isFetchingNextPage: false, isFetchingPreviousPage: false, isIdle: false, isLoading: false, isLoadingError: false, isPlaceholderData: false, isPreviousData: false, isRefetchError: false, isRefetching: false, isStale: true, isSuccess: true, refetch: expect.any(Function), remove: expect.any(Function), status: 'success', }) }) it('should not throw when fetchNextPage returns an error', async () => { const consoleMock = mockConsoleError() const key = queryKey() let noThrow: boolean function Page() { const start = 1 const state = useInfiniteQuery( key, async ({ pageParam = start }) => { if (pageParam === 2) { throw new Error('error') } return Number(pageParam) }, { retry: 1, retryDelay: 10, getNextPageParam: lastPage => lastPage + 1, } ) const { fetchNextPage } = state React.useEffect(() => { setActTimeout(() => { fetchNextPage() .then(() => { noThrow = true }) .catch(() => undefined) }, 20) }, [fetchNextPage]) return null } renderWithClient(queryClient, <Page />) await waitFor(() => expect(noThrow).toBe(true)) consoleMock.mockRestore() }) it('should keep the previous data when keepPreviousData is set', async () => { const key = queryKey() const states: UseInfiniteQueryResult<string>[] = [] function Page() { const [order, setOrder] = React.useState('desc') const state = useInfiniteQuery( [key, order], async ({ pageParam = 0 }) => { await sleep(10) return `${pageParam}-${order}` }, { getNextPageParam: () => 1, keepPreviousData: true, } ) states.push(state) const { fetchNextPage } = state React.useEffect(() => { setActTimeout(() => { fetchNextPage() }, 50) setActTimeout(() => { setOrder('asc') }, 100) }, [fetchNextPage]) return null } renderWithClient(queryClient, <Page />) await sleep(300) expect(states.length).toBe(7) expect(states[0]).toMatchObject({ data: undefined, isFetching: true, isFetchingNextPage: false, isSuccess: false, isPreviousData: false, }) expect(states[1]).toMatchObject({ data: { pages: ['0-desc'] }, isFetching: false, isFetchingNextPage: false, isSuccess: true, isPreviousData: false, }) expect(states[2]).toMatchObject({ data: { pages: ['0-desc'] }, isFetching: true, isFetchingNextPage: true, isSuccess: true, isPreviousData: false, }) expect(states[3]).toMatchObject({ data: { pages: ['0-desc', '1-desc'] }, isFetching: false, isFetchingNextPage: false, isSuccess: true, isPreviousData: false, }) // Set state expect(states[4]).toMatchObject({ data: { pages: ['0-desc', '1-desc'] }, isFetching: true, isFetchingNextPage: false, isSuccess: true, isPreviousData: true, }) // Hook state update expect(states[5]).toMatchObject({ data: { pages: ['0-desc', '1-desc'] }, isFetching: true, isFetchingNextPage: false, isSuccess: true, isPreviousData: true, }) expect(states[6]).toMatchObject({ data: { pages: ['0-asc'] }, isFetching: false, isFetchingNextPage: false, isSuccess: true, isPreviousData: false, }) }) it('should be able to select a part of the data', async () => { const key = queryKey() const states: UseInfiniteQueryResult<string>[] = [] function Page() { const state = useInfiniteQuery(key, () => ({ count: 1 }), { select: data => ({ pages: data.pages.map(x => `count: ${x.count}`), pageParams: data.pageParams, }), }) states.push(state) return null } renderWithClient(queryClient, <Page />) await sleep(10) expect(states.length).toBe(2) expect(states[0]).toMatchObject({ data: undefined, isSuccess: false, }) expect(states[1]).toMatchObject({ data: { pages: ['count: 1'] }, isSuccess: true, }) }) it('should be able to reverse the data', async () => { const key = queryKey() const states: UseInfiniteQueryResult<number>[] = [] function Page() { const state = useInfiniteQuery( key, ({ pageParam = 0 }) => Number(pageParam), { select: data => ({ pages: [...data.pages].reverse(), pageParams: [...data.pageParams].reverse(), }), } ) states.push(state) const { fetchNextPage } = state React.useEffect(() => { setActTimeout(() => { fetchNextPage({ pageParam: 1 }) }, 10) }, [fetchNextPage]) return null } renderWithClient(queryClient, <Page />) await sleep(100) expect(states.length).toBe(4) expect(states[0]).toMatchObject({ data: undefined, isSuccess: false, }) expect(states[1]).toMatchObject({ data: { pages: [0] }, isSuccess: true, }) expect(states[2]).toMatchObject({ data: { pages: [0] }, isSuccess: true, }) expect(states[3]).toMatchObject({ data: { pages: [1, 0] }, isSuccess: true, }) }) it('should be able to fetch a previous page', async () => { const key = queryKey() const states: UseInfiniteQueryResult<number>[] = [] function Page() { const start = 10 const state = useInfiniteQuery( key, async ({ pageParam = start }) => { await sleep(10) return Number(pageParam) }, { getPreviousPageParam: firstPage => firstPage - 1, } ) states.push(state) const { fetchPreviousPage } = state React.useEffect(() => { setActTimeout(() => { fetchPreviousPage() }, 20) }, [fetchPreviousPage]) return null } renderWithClient(queryClient, <Page />) await sleep(100) expect(states.length).toBe(4) expect(states[0]).toMatchObject({ data: undefined, hasNextPage: undefined, hasPreviousPage: undefined, isFetching: true, isFetchingNextPage: false, isFetchingPreviousPage: false, isSuccess: false, }) expect(states[1]).toMatchObject({ data: { pages: [10] }, hasNextPage: undefined, hasPreviousPage: true, isFetching: false, isFetchingNextPage: false, isFetchingPreviousPage: false, isSuccess: true, }) expect(states[2]).toMatchObject({ data: { pages: [10] }, hasNextPage: undefined, hasPreviousPage: true, isFetching: true, isFetchingNextPage: false, isFetchingPreviousPage: true, isSuccess: true, }) expect(states[3]).toMatchObject({ data: { pages: [9, 10] }, hasNextPage: undefined, hasPreviousPage: true, isFetching: false, isFetchingNextPage: false, isFetchingPreviousPage: false, isSuccess: true, }) }) it('should be able to refetch when providing page params manually', async () => { const key = queryKey() const states: UseInfiniteQueryResult<number>[] = [] function Page() { const state = useInfiniteQuery(key, ({ pageParam = 10 }) => Number(pageParam) ) states.push(state) const { fetchNextPage, fetchPreviousPage, refetch } = state React.useEffect(() => { setActTimeout(() => { fetchNextPage({ pageParam: 11 }) }, 10) setActTimeout(() => { fetchPreviousPage({ pageParam: 9 }) }, 20) setActTimeout(() => { refetch() }, 30) }, [fetchNextPage, fetchPreviousPage, refetch]) return null } renderWithClient(queryClient, <Page />) await sleep(100) expect(states.length).toBe(8) // Initial fetch expect(states[0]).toMatchObject({ data: undefined, isFetching: true, isFetchingNextPage: false, }) // Initial fetch done expect(states[1]).toMatchObject({ data: { pages: [10] }, isFetching: false, isFetchingNextPage: false, }) // Fetch next page expect(states[2]).toMatchObject({ data: { pages: [10] }, isFetching: true, isFetchingNextPage: true, }) // Fetch next page done expect(states[3]).toMatchObject({ data: { pages: [10, 11] }, isFetching: false, isFetchingNextPage: false, }) // Fetch previous page expect(states[4]).toMatchObject({ data: { pages: [10, 11] }, isFetching: true, isFetchingNextPage: false, isFetchingPreviousPage: true, }) // Fetch previous page done expect(states[5]).toMatchObject({ data: { pages: [9, 10, 11] }, isFetching: false, isFetchingNextPage: false, isFetchingPreviousPage: false, }) // Refetch expect(states[6]).toMatchObject({ data: { pages: [9, 10, 11] }, isFetching: true, isFetchingNextPage: false, isFetchingPreviousPage: false, }) // Refetch done expect(states[7]).toMatchObject({ data: { pages: [9, 10, 11] }, isFetching: false, isFetchingNextPage: false, isFetchingPreviousPage: false, }) }) it('should be able to refetch when providing page params automatically', async () => { const key = queryKey() const states: UseInfiniteQueryResult<number>[] = [] function Page() { const state = useInfiniteQuery( key, ({ pageParam = 10 }) => Number(pageParam), { getPreviousPageParam: firstPage => firstPage - 1, getNextPageParam: lastPage => lastPage + 1, } ) states.push(state) const { fetchNextPage, fetchPreviousPage, refetch } = state React.useEffect(() => { setActTimeout(() => { fetchNextPage() }, 10) setActTimeout(() => { fetchPreviousPage() }, 20) setActTimeout(() => { refetch() }, 30) }, [fetchNextPage, fetchPreviousPage, refetch]) return null } renderWithClient(queryClient, <Page />) await sleep(100) expect(states.length).toBe(8) // Initial fetch expect(states[0]).toMatchObject({ data: undefined, isFetching: true, isFetchingNextPage: false, }) // Initial fetch done expect(states[1]).toMatchObject({ data: { pages: [10] }, isFetching: false, isFetchingNextPage: false, }) // Fetch next page expect(states[2]).toMatchObject({ data: { pages: [10] }, isFetching: true, isFetchingNextPage: true, }) // Fetch next page done expect(states[3]).toMatchObject({ data: { pages: [10, 11] }, isFetching: false, isFetchingNextPage: false, }) // Fetch previous page expect(states[4]).toMatchObject({ data: { pages: [10, 11] }, isFetching: true, isFetchingNextPage: false, isFetchingPreviousPage: true, }) // Fetch previous page done expect(states[5]).toMatchObject({ data: { pages: [9, 10, 11] }, isFetching: false, isFetchingNextPage: false, isFetchingPreviousPage: false, }) // Refetch expect(states[6]).toMatchObject({ data: { pages: [9, 10, 11] }, isFetching: true, isFetchingNextPage: false, isFetchingPreviousPage: false, }) // Refetch done expect(states[7]).toMatchObject({ data: { pages: [9, 10, 11] }, isFetching: false, isFetchingNextPage: false, isFetchingPreviousPage: false, }) }) it('should be able to refetch only specific pages when refetchPages is provided', async () => { const key = queryKey() const states: UseInfiniteQueryResult<number>[] = [] function Page() { const multiplier = React.useRef(1) const state = useInfiniteQuery( key, ({ pageParam = 10 }) => Number(pageParam) * multiplier.current, { getNextPageParam: lastPage => lastPage + 1, } ) states.push(state) const { fetchNextPage, refetch } = state React.useEffect(() => { setActTimeout(() => { fetchNextPage() }, 10) setActTimeout(() => { multiplier.current = 2 refetch({ refetchPage: (_, index) => index === 0, }) }, 20) }, [fetchNextPage, refetch]) return null } renderWithClient(queryClient, <Page />) await sleep(50) expect(states.length).toBe(6) // Initial fetch expect(states[0]).toMatchObject({ data: undefined, isFetching: true, isFetchingNextPage: false, }) // Initial fetch done expect(states[1]).toMatchObject({ data: { pages: [10] }, isFetching: false, isFetchingNextPage: false, }) // Fetch next page expect(states[2]).toMatchObject({ data: { pages: [10] }, isFetching: true, isFetchingNextPage: true, }) // Fetch next page done expect(states[3]).toMatchObject({ data: { pages: [10, 11] }, isFetching: false, isFetchingNextPage: false, }) // Refetch expect(states[4]).toMatchObject({ data: { pages: [10, 11] }, isFetching: true, isFetchingNextPage: false, }) // Refetch done, only page one has been refetched and multiplied expect(states[5]).toMatchObject({ data: { pages: [20, 11] }, isFetching: false, isFetchingNextPage: false, }) }) it('should silently cancel any ongoing fetch when fetching more', async () => { const key = queryKey() const states: UseInfiniteQueryResult<number>[] = [] function Page() { const start = 10 const state = useInfiniteQuery( key, async ({ pageParam = start }) => { await sleep(50) return Number(pageParam) }, { getNextPageParam: lastPage => lastPage + 1, } ) states.push(state) const { refetch, fetchNextPage } = state React.useEffect(() => { setActTimeout(() => { refetch() }, 100) setActTimeout(() => { fetchNextPage() }, 110) }, [fetchNextPage, refetch]) return null } renderWithClient(queryClient, <Page />) await sleep(300) expect(states.length).toBe(5) expect(states[0]).toMatchObject({ hasNextPage: undefined, data: undefined, isFetching: true, isFetchingNextPage: false, isSuccess: false, }) expect(states[1]).toMatchObject({ hasNextPage: true, data: { pages: [10] }, isFetching: false, isFetchingNextPage: false, isSuccess: true, }) expect(states[2]).toMatchObject({ hasNextPage: true, data: { pages: [10] }, isFetching: true, isFetchingNextPage: false, isSuccess: true, }) expect(states[3]).toMatchObject({ hasNextPage: true, data: { pages: [10] }, isFetching: true, isFetchingNextPage: true, isSuccess: true, }) expect(states[4]).toMatchObject({ hasNextPage: true, data: { pages: [10, 11] }, isFetching: false, isFetchingNextPage: false, isSuccess: true, }) }) it('should silently cancel an ongoing fetchNextPage request when another fetchNextPage is invoked', async () => { const key = queryKey() const start = 10 const fetchPage = jest.fn(async ({ pageParam = start }) => { await sleep(50) return Number(pageParam) }) function Page() { const { fetchNextPage } = useInfiniteQuery(key, fetchPage, { getNextPageParam: lastPage => lastPage + 1, }) React.useEffect(() => { setActTimeout(() => { fetchNextPage() }, 100) setActTimeout(() => { fetchNextPage() }, 110) }, [fetchNextPage]) return null } renderWithClient(queryClient, <Page />) await sleep(300) expect(fetchPage).toBeCalledTimes(3) expect(fetchPage).toHaveBeenNthCalledWith(1, { pageParam: undefined, queryKey: [key], }) expect(fetchPage).toHaveBeenNthCalledWith(2, { pageParam: 11, queryKey: [key], }) expect(fetchPage).toHaveBeenNthCalledWith(3, { pageParam: 11, queryKey: [key], }) }) it('should not cancel an ongoing fetchNextPage request when another fetchNextPage is invoked if `cancelRefetch: false` is used ', async () => { const key = queryKey() const start = 10 const fetchPage = jest.fn(async ({ pageParam = start }) => { await sleep(50) return Number(pageParam) }) function Page() { const { fetchNextPage } = useInfiniteQuery(key, fetchPage, { getNextPageParam: lastPage => lastPage + 1, }) React.useEffect(() => { setActTimeout(() => { fetchNextPage() }, 100) setActTimeout(() => { fetchNextPage({ cancelRefetch: false }) }, 110) }, [fetchNextPage]) return null } renderWithClient(queryClient, <Page />) await sleep(300) expect(fetchPage).toBeCalledTimes(2) expect(fetchPage).toHaveBeenNthCalledWith(1, { pageParam: undefined, queryKey: [key], }) expect(fetchPage).toHaveBeenNthCalledWith(2, { pageParam: 11, queryKey: [key], }) }) it('should keep fetching first page when not loaded yet and triggering fetch more', async () => { const key = queryKey() const states: UseInfiniteQueryResult<number>[] = [] function Page() { const start = 10 const state = useInfiniteQuery( key, async ({ pageParam = start }) => { await sleep(50) return Number(pageParam) }, { getNextPageParam: lastPage => lastPage + 1, } ) states.push(state) const { fetchNextPage } = state React.useEffect(() => { setActTimeout(() => { fetchNextPage() }, 10) }, [fetchNextPage]) return null } renderWithClient(queryClient, <Page />) await sleep(100) expect(states.length).toBe(2) expect(states[0]).toMatchObject({ hasNextPage: undefined, data: undefined, isFetching: true, isFetchingNextPage: false, isSuccess: false, }) expect(states[1]).toMatchObject({ hasNextPage: true, data: { pages: [10] }, isFetching: false, isFetchingNextPage: false, isSuccess: true, }) }) it('should stop fetching additional pages when the component is unmounted', async () => { const key = queryKey() const states: UseInfiniteQueryResult<number>[] = [] let fetches = 0 const initialData = { pages: [1, 2, 3, 4], pageParams: [1, 2, 3, 4] } function List() { const state = useInfiniteQuery( key, async ({ pageParam }) => { fetches++ await sleep(50) return Number(pageParam) }, { initialData, getNextPageParam: lastPage => lastPage + 1, } ) states.push(state) return null } function Page() { const [show, setShow] = React.useState(true) React.useEffect(() => { setActTimeout(() => { setShow(false) }, 75) }, []) return show ? <List /> : null } renderWithClient(queryClient, <Page />) await sleep(300) expect(states.length).toBe(1) expect(fetches).toBe(2) expect(queryClient.getQueryState(key)).toMatchObject({ data: initialData, status: 'success', error: null, }) }) it('should be able to override the cursor in the fetchNextPage callback', async () => { const key = queryKey() const states: UseInfiniteQueryResult<number>[] = [] function Page() { const state = useInfiniteQuery( key, async ({ pageParam = 0 }) => { await sleep(10) return Number(pageParam) }, { getNextPageParam: lastPage => lastPage + 1, } ) states.push(state) const { fetchNextPage } = state React.useEffect(() => { setActTimeout(() => { fetchNextPage({ pageParam: 5 }) }, 20) }, [fetchNextPage]) return null } renderWithClient(queryClient, <Page />) await sleep(100) expect(states.length).toBe(4) expect(states[0]).toMatchObject({ hasNextPage: undefined, data: undefined, isFetching: true, isFetchingNextPage: false, isSuccess: false, }) expect(states[1]).toMatchObject({ hasNextPage: true, data: { pages: [0] }, isFetching: false, isFetchingNextPage: false, isSuccess: true, }) expect(states[2]).toMatchObject({ hasNextPage: true, data: { pages: [0] }, isFetching: true, isFetchingNextPage: true, isSuccess: true, }) expect(states[3]).toMatchObject({ hasNextPage: true, data: { pages: [0, 5] }, isFetching: false, isFetchingNextPage: false, isSuccess: true, }) }) it('should be able to set new pages with the query client', async () => { const key = queryKey() const states: UseInfiniteQueryResult<number>[] = [] function Page() { const [firstPage, setFirstPage] = React.useState(0) const state = useInfiniteQuery( key, async ({ pageParam = firstPage }) => { await sleep(10) return Number(pageParam) }, { getNextPageParam: lastPage => lastPage + 1, } ) states.push(state) const { refetch } = state React.useEffect(() => { setActTimeout(() => { queryClient.setQueryData(key, { pages: [7, 8], pageParams: [7, 8] }) setFirstPage(7) }, 20) setActTimeout(() => { refetch() }, 50) }, [refetch]) return null } renderWithClient(queryClient, <Page />) await sleep(100) expect(states.length).toBe(6) expect(states[0]).toMatchObject({ hasNextPage: undefined, data: undefined, isFetching: true, isFetchingNextPage: false, isSuccess: false, }) // After first fetch expect(states[1]).toMatchObject({ hasNextPage: true, data: { pages: [0] }, isFetching: false, isFetchingNextPage: false, isSuccess: true, }) // Set state expect(states[2]).toMatchObject({ hasNextPage: true, data: { pages: [7, 8] }, isFetching: false, isFetchingNextPage: false, isSuccess: true, }) // Hook state update expect(states[3]).toMatchObject({ hasNextPage: true, data: { pages: [7, 8] }, isFetching: false, isFetchingNextPage: false, isSuccess: true, }) // Refetch expect(states[4]).toMatchObject({ hasNextPage: true, data: { pages: [7, 8] }, isFetching: true, isFetchingNextPage: false, isSuccess: true, }) // Refetch done expect(states[5]).toMatchObject({ hasNextPage: true, data: { pages: [7, 8] }, isFetching: false, isFetchingNextPage: false, isSuccess: true, }) }) it('should only refetch the first page when initialData is provided', async () => { const key = queryKey() const states: UseInfiniteQueryResult<number>[] = [] function Page() { const state = useInfiniteQuery( key, async ({ pageParam }) => { await sleep(10) return pageParam }, { initialData: { pages: [1], pageParams: [1] }, getNextPageParam: lastPage => lastPage + 1, } ) states.push(state) const { fetchNextPage } = state React.useEffect(() => { setActTimeout(() => { fetchNextPage() }, 20) }, [fetchNextPage]) return null } renderWithClient(queryClient, <Page />) await sleep(100) expect(states.length).toBe(4) expect(states[0]).toMatchObject({ data: { pages: [1] }, hasNextPage: true, isFetching: true, isFetchingNextPage: false, isSuccess: true, }) expect(states[1]).toMatchObject({ data: { pages: [1] }, hasNextPage: true, isFetching: false, isFetchingNextPage: false, isSuccess: true, }) expect(states[2]).toMatchObject({ data: { pages: [1] }, hasNextPage: true, isFetching: true, isFetchingNextPage: true, isSuccess: true, }) expect(states[3]).toMatchObject({ data: { pages: [1, 2] }, hasNextPage: true, isFetching: false, isFetchingNextPage: false, isSuccess: true, }) }) it('should set hasNextPage to false if getNextPageParam returns undefined', async () => { const key = queryKey() const states: UseInfiniteQueryResult<number>[] = [] function Page() { const state = useInfiniteQuery( key, ({ pageParam = 1 }) => Number(pageParam), { getNextPageParam: () => undefined, } ) states.push(state) return null } renderWithClient(queryClient, <Page />) await sleep(100) expect(states.length).toBe(2) expect(states[0]).toMatchObject({ data: undefined, hasNextPage: undefined, isFetching: true, isFetchingNextPage: false, isSuccess: false, }) expect(states[1]).toMatchObject({ data: { pages: [1] }, hasNextPage: false, isFetching: false, isFetchingNextPage: false, isSuccess: true, }) }) it('should compute hasNextPage correctly using initialData', async () => { const key = queryKey() const states: UseInfiniteQueryResult<number>[] = [] function Page() { const state = useInfiniteQuery(key, ({ pageParam = 10 }) => pageParam, { initialData: { pages: [10], pageParams: [undefined] }, getNextPageParam: lastPage => (lastPage === 10 ? 11 : undefined), }) states.push(state) return null } renderWithClient(queryClient, <Page />) await sleep(100) expect(states.length).toBe(2) expect(states[0]).toMatchObject({ data: { pages: [10] }, hasNextPage: true, isFetching: true, isFetchingNextPage: false, isSuccess: true, }) expect(states[1]).toMatchObject({ data: { pages: [10] }, hasNextPage: true, isFetching: false, isFetchingNextPage: false, isSuccess: true, }) }) it('should compute hasNextPage correctly for falsy getFetchMore return value using initialData', async () => { const key = queryKey() const states: UseInfiniteQueryResult<number>[] = [] function Page() { const state = useInfiniteQuery(key, ({ pageParam = 10 }) => pageParam, { initialData: { pages: [10], pageParams: [undefined] }, getNextPageParam: () => undefined, }) states.push(state) return null } renderWithClient(queryClient, <Page />) await sleep(100) expect(states.length).toBe(2) expect(states[0]).toMatchObject({ data: { pages: [10] }, hasNextPage: false, isFetching: true, isFetchingNextPage: false, isSuccess: true, }) expect(states[1]).toMatchObject({ data: { pages: [10] }, hasNextPage: false, isFetching: false, isFetchingNextPage: false, isSuccess: true, }) }) it('should not use selected data when computing hasNextPage', async () => { const key = queryKey() const states: UseInfiniteQueryResult<string>[] = [] function Page() { const state = useInfiniteQuery( key, ({ pageParam = 1 }) => Number(pageParam), { getNextPageParam: lastPage => (lastPage === 1 ? 2 : false), select: data => ({ pages: data.pages.map(x => x.toString()), pageParams: data.pageParams, }), } ) states.push(state) return null } renderWithClient(queryClient, <Page />) await sleep(100) expect(states.length).toBe(2) expect(states[0]).toMatchObject({ data: undefined, hasNextPage: undefined, isFetching: true, isFetchingNextPage: false, isSuccess: false, }) expect(states[1]).toMatchObject({ data: { pages: ['1'] }, hasNextPage: true, isFetching: false, isFetchingNextPage: false, isSuccess: true, }) }) it('should render correct states even in case of concurrent renders with different properties', async () => { const key = queryKey() const states: UseInfiniteQueryResult<number>[] = [] let concurrent = false const originalUseEffect = React.useEffect const dummyUseEffect = (...args: any[]) => { originalUseEffect(() => { return }, args[1]) } function Page() { const [count, setCount] = React.useState(0) if (concurrent) { React.useEffect = dummyUseEffect } const state = useInfiniteQuery( [key, count], async () => { await sleep(10) return count }, { staleTime: Infinity, keepPreviousData: true, getNextPageParam: () => (count === 0 ? undefined : count + 1), } ) if (concurrent) { React.useEffect = originalUseEffect } states.push(state) React.useEffect(() => { setActTimeout(() => { setCount(1) }, 20) // Try to simulate concurrent render which does not trigger effects setActTimeout(() => { concurrent = true setCount(0) }, 40) setActTimeout(() => { concurrent = false setCount(2) }, 60) }, []) return null } renderWithClient(queryClient, <Page />) await sleep(100) expect(states.length).toBe(9) // Load query 0 expect(states[0]).toMatchObject({ status: 'loading', data: undefined, isFetching: true, isPreviousData: false, hasNextPage: undefined, }) // Fetch done expect(states[1]).toMatchObject({ status: 'success', data: { pageParams: [undefined], pages: [0] }, isFetching: false, isPreviousData: false, hasNextPage: false, }) // Set state to query 1 expect(states[2]).toMatchObject({ status: 'success', data: { pageParams: [undefined], pages: [0] }, isFetching: true, isPreviousData: true, hasNextPage: undefined, }) // Fetch start expect(states[3]).toMatchObject({ status: 'success', data: { pageParams: [undefined], pages: [0] }, isFetching: true, isPreviousData: true, hasNextPage: undefined, }) // Fetch done expect(states[4]).toMatchObject({ status: 'success', data: { pageParams: [undefined], pages: [1] }, isFetching: false, isPreviousData: false, hasNextPage: true, }) // Concurrent render for query 0 expect(states[5]).toMatchObject({ status: 'success', data: { pageParams: [undefined], pages: [0] }, isFetching: false, isPreviousData: false, hasNextPage: false, }) // Set state to query 2 (should have query 1 has previous data) expect(states[6]).toMatchObject({ status: 'success', data: { pageParams: [undefined], pages: [1] }, isFetching: true, isPreviousData: true, hasNextPage: undefined, }) // Fetch start expect(states[7]).toMatchObject({ status: 'success', data: { pageParams: [undefined], pages: [1] }, isFetching: true, isPreviousData: true, hasNextPage: undefined, }) // Fetch done expect(states[8]).toMatchObject({ status: 'success', data: { pageParams: [undefined], pages: [2] }, isFetching: false, isPreviousData: false, hasNextPage: true, }) }) it('should build fresh cursors on refetch', async () => { const key = queryKey() const genItems = (size: number) => [...new Array(size)].fill(null).map((_, d) => d) const items = genItems(15) const limit = 3 const fetchItemsWithLimit = async (cursor = 0, ts: number) => { await sleep(10) return { nextId: cursor + limit, items: items.slice(cursor, cursor + limit), ts, } } function Page() { const fetchCountRef = React.useRef(0) const { status, data, error, isFetchingNextPage, fetchNextPage, hasNextPage, refetch, } = useInfiniteQuery<Result, Error>( key, ({ pageParam = 0 }) => fetchItemsWithLimit(pageParam, fetchCountRef.current++), { getNextPageParam: lastPage => lastPage.nextId, } ) return ( <div> <h1>Pagination</h1> {status === 'loading' ? ( 'Loading...' ) : status === 'error' ? ( <span>Error: {error?.message}</span> ) : ( <> <div>Data:</div> {data?.pages.map((page, i) => ( <div key={i}> <div> Page {i}: {page.ts} </div> <div key={i}> {page.items.map(item => ( <p key={item}>Item: {item}</p> ))} </div> </div> ))} <div> <button onClick={() => fetchNextPage()} disabled={!hasNextPage || Boolean(isFetchingNextPage)} > {isFetchingNextPage ? 'Loading more...' : hasNextPage ? 'Load More' : 'Nothing more to load'} </button> <button onClick={() => refetch()}>Refetch</button> <button onClick={() => { // Imagine that this mutation happens somewhere else // makes an actual network request // and calls invalidateQueries in an onSuccess items.splice(4, 1) queryClient.invalidateQueries(key) }} > Remove item </button> </div> <div>{!isFetchingNextPage ? 'Background Updating...' : null}</div> </> )} </div> ) } const rendered = renderWithClient(queryClient, <Page />) rendered.getByText('Loading...') await waitFor(() => rendered.getByText('Item: 2')) await waitFor(() => rendered.getByText('Page 0: 0')) fireEvent.click(rendered.getByText('Load More')) await waitFor(() => rendered.getByText('Loading more...')) await waitFor(() => rendered.getByText('Item: 5')) await waitFor(() => rendered.getByText('Page 0: 0')) await waitFor(() => rendered.getByText('Page 1: 1')) fireEvent.click(rendered.getByText('Load More')) await waitFor(() => rendered.getByText('Loading more...')) await waitFor(() => rendered.getByText('Item: 8')) await waitFor(() => rendered.getByText('Page 0: 0')) await waitFor(() => rendered.getByText('Page 1: 1')) await waitFor(() => rendered.getByText('Page 2: 2')) fireEvent.click(rendered.getByText('Refetch')) await waitFor(() => rendered.getByText('Background Updating...')) await waitFor(() => rendered.getByText('Item: 8')) await waitFor(() => rendered.getByText('Page 0: 3')) await waitFor(() => rendered.getByText('Page 1: 4')) await waitFor(() => rendered.getByText('Page 2: 5')) // ensure that Item: 4 is rendered before removing it expect(rendered.queryAllByText('Item: 4')).toHaveLength(1) // remove Item: 4 fireEvent.click(rendered.getByText('Remove item')) await waitFor(() => rendered.getByText('Background Updating...')) // ensure that an additional item is rendered (it means that cursors were properly rebuilt) await waitFor(() => rendered.getByText('Item: 9')) await waitFor(() => rendered.getByText('Page 0: 6')) await waitFor(() => rendered.getByText('Page 1: 7')) await waitFor(() => rendered.getByText('Page 2: 8')) // ensure that Item: 4 is no longer rendered expect(rendered.queryAllByText('Item: 4')).toHaveLength(0) }) it('should compute hasNextPage correctly for falsy getFetchMore return value on refetching', async () => { const key = queryKey() const MAX = 2 function Page() { const fetchCountRef = React.useRef(0) const [isRemovedLastPage, setIsRemovedLastPage] = React.useState<boolean>( false ) const { status, data, error, isFetching, isFetchingNextPage, fetchNextPage, hasNextPage, refetch, } = useInfiniteQuery<Result, Error>( key, ({ pageParam = 0 }) => fetchItems( pageParam, fetchCountRef.current++, pageParam === MAX || (pageParam === MAX - 1 && isRemovedLastPage) ), { getNextPageParam: lastPage => lastPage.nextId, } ) return ( <div> <h1>Pagination</h1> {status === 'loading' ? ( 'Loading...' ) : status === 'error' ? ( <span>Error: {error?.message}</span> ) : ( <> <div>Data:</div> {data?.pages.map((page, i) => ( <div key={i}> <div> Page {i}: {page.ts} </div> <div key={i}> {page.items.map(item => ( <p key={item}>Item: {item}</p> ))} </div> </div> ))} <div> <button onClick={() => fetchNextPage()} disabled={!hasNextPage || Boolean(isFetchingNextPage)} > {isFetchingNextPage ? 'Loading more...' : hasNextPage ? 'Load More' : 'Nothing more to load'} </button> <button onClick={() => refetch()}>Refetch</button> <button onClick={() => setIsRemovedLastPage(true)}> Remove Last Page </button> </div> <div> {isFetching && !isFetchingNextPage ? 'Background Updating...' : null} </div> </> )} </div> ) } const rendered = renderWithClient(queryClient, <Page />) rendered.getByText('Loading...') await waitFor(() => { rendered.getByText('Item: 9') rendered.getByText('Page 0: 0') }) fireEvent.click(rendered.getByText('Load More')) await waitFor(() => rendered.getByText('Loading more...')) await waitFor(() => { rendered.getByText('Item: 19') rendered.getByText('Page 0: 0') rendered.getByText('Page 1: 1') }) fireEvent.click(rendered.getByText('Load More')) await waitFor(() => rendered.getByText('Loading more...')) await waitFor(() => { rendered.getByText('Item: 29') rendered.getByText('Page 0: 0') rendered.getByText('Page 1: 1') rendered.getByText('Page 2: 2') }) rendered.getByText('Nothing more to load') fireEvent.click(rendered.getByText('Remove Last Page')) await sleep(10) fireEvent.click(rendered.getByText('Refetch')) await waitFor(() => rendered.getByText('Background Updating...')) await waitFor(() => { rendered.getByText('Page 0: 3') rendered.getByText('Page 1: 4') }) expect(rendered.queryByText('Item: 29')).toBeNull() expect(rendered.queryByText('Page 2: 5')).toBeNull() rendered.getByText('Nothing more to load') }) it('should cancel the query function when there are no more subscriptions', async () => { const key = queryKey() let cancelFn: jest.Mock = jest.fn() const queryFn = () => { const promise = new Promise<string>((resolve, reject) => { cancelFn = jest.fn(() => reject('Cancelled')) sleep(10).then(() => resolve('OK')) }) ;(promise as any).cancel = cancelFn return promise } function Page() { const state = useInfiniteQuery(key, queryFn) return ( <div> <h1>Status: {state.status}</h1> </div> ) } const rendered = renderWithClient( queryClient, <Blink duration={5}> <Page /> </Blink> ) await waitFor(() => rendered.getByText('off')) expect(cancelFn).toHaveBeenCalled() }) })
the_stack
import {exactMatchOptions, subsetMatchOptions} from '../src/router'; import {containsTree, DefaultUrlSerializer} from '../src/url_tree'; describe('UrlTree', () => { const serializer = new DefaultUrlSerializer(); describe('DefaultUrlSerializer', () => { let serializer: DefaultUrlSerializer; beforeEach(() => { serializer = new DefaultUrlSerializer(); }); it('should parse query parameters', () => { const tree = serializer.parse('/path/to?k=v&k/(a;b)=c'); expect(tree.queryParams).toEqual({ 'k': 'v', 'k/(a;b)': 'c', }); }); it('should allow question marks in query param values', () => { const tree = serializer.parse('/path/to?first=http://foo/bar?baz=true&second=123'); expect(tree.queryParams).toEqual({'first': 'http://foo/bar?baz=true', 'second': '123'}); }); }); describe('containsTree', () => { describe('exact = true', () => { it('should return true when two tree are the same', () => { const url = '/one/(one//left:three)(right:four)'; const t1 = serializer.parse(url); const t2 = serializer.parse(url); expect(containsTree(t1, t2, exactMatchOptions)).toBe(true); expect(containsTree(t2, t1, exactMatchOptions)).toBe(true); }); it('should return true when queryParams are the same', () => { const t1 = serializer.parse('/one/two?test=1&page=5'); const t2 = serializer.parse('/one/two?test=1&page=5'); expect(containsTree(t1, t2, exactMatchOptions)).toBe(true); }); it('should return true when queryParams are the same but with diffrent order', () => { const t1 = serializer.parse('/one/two?test=1&page=5'); const t2 = serializer.parse('/one/two?page=5&test=1'); expect(containsTree(t1, t2, exactMatchOptions)).toBe(true); }); it('should return true when queryParams contains array params that are the same', () => { const t1 = serializer.parse('/one/two?test=a&test=b&pages=5&pages=6'); const t2 = serializer.parse('/one/two?test=a&test=b&pages=5&pages=6'); expect(containsTree(t1, t2, exactMatchOptions)).toBe(true); }); it('should return false when queryParams contains array params but are not the same', () => { const t1 = serializer.parse('/one/two?test=a&test=b&pages=5&pages=6'); const t2 = serializer.parse('/one/two?test=a&test=b&pages=5&pages=7'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(false); }); it('should return false when queryParams are not the same', () => { const t1 = serializer.parse('/one/two?test=1&page=5'); const t2 = serializer.parse('/one/two?test=1'); expect(containsTree(t1, t2, exactMatchOptions)).toBe(false); }); it('should return false when queryParams are not the same', () => { const t1 = serializer.parse('/one/two?test=4&test=4&test=2'); const t2 = serializer.parse('/one/two?test=4&test=3&test=2'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(false); }); it('should return true when queryParams are the same in different order', () => { const t1 = serializer.parse('/one/two?test=4&test=3&test=2'); const t2 = serializer.parse('/one/two?test=2&test=3&test=4'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(true); }); it('should return true when queryParams are the same in different order', () => { const t1 = serializer.parse('/one/two?test=4&test=4&test=1'); const t2 = serializer.parse('/one/two?test=1&test=4&test=4'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(true); }); it('should return false when containee is missing queryParams', () => { const t1 = serializer.parse('/one/two?page=5'); const t2 = serializer.parse('/one/two'); expect(containsTree(t1, t2, exactMatchOptions)).toBe(false); }); it('should return false when paths are not the same', () => { const t1 = serializer.parse('/one/two(right:three)'); const t2 = serializer.parse('/one/two2(right:three)'); expect(containsTree(t1, t2, exactMatchOptions)).toBe(false); }); it('should return false when container has an extra child', () => { const t1 = serializer.parse('/one/two(right:three)'); const t2 = serializer.parse('/one/two'); expect(containsTree(t1, t2, exactMatchOptions)).toBe(false); }); it('should return false when containee has an extra child', () => { const t1 = serializer.parse('/one/two'); const t2 = serializer.parse('/one/two(right:three)'); expect(containsTree(t1, t2, exactMatchOptions)).toBe(false); }); }); describe('exact = false', () => { it('should return true when containee is missing a segment', () => { const t1 = serializer.parse('/one/(two//left:three)(right:four)'); const t2 = serializer.parse('/one/(two//left:three)'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(true); }); it('should return true when containee is missing some paths', () => { const t1 = serializer.parse('/one/two/three'); const t2 = serializer.parse('/one/two'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(true); }); it('should return true container has its paths split into multiple segments', () => { const t1 = serializer.parse('/one/(two//left:three)'); const t2 = serializer.parse('/one/two'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(true); }); it('should return false when containee has extra segments', () => { const t1 = serializer.parse('/one/two'); const t2 = serializer.parse('/one/(two//left:three)'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(false); }); it('should return false containee has segments that the container does not have', () => { const t1 = serializer.parse('/one/(two//left:three)'); const t2 = serializer.parse('/one/(two//right:four)'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(false); }); it('should return false when containee has extra paths', () => { const t1 = serializer.parse('/one'); const t2 = serializer.parse('/one/two'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(false); }); it('should return true when queryParams are the same', () => { const t1 = serializer.parse('/one/two?test=1&page=5'); const t2 = serializer.parse('/one/two?test=1&page=5'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(true); }); it('should return true when container contains containees queryParams', () => { const t1 = serializer.parse('/one/two?test=1&u=5'); const t2 = serializer.parse('/one/two?u=5'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(true); }); it('should return true when containee does not have queryParams', () => { const t1 = serializer.parse('/one/two?page=5'); const t2 = serializer.parse('/one/two'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(true); }); it('should return false when containee has but container does not have queryParams', () => { const t1 = serializer.parse('/one/two'); const t2 = serializer.parse('/one/two?page=1'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(false); }); it('should return true when container has array params but containee does not have', () => { const t1 = serializer.parse('/one/two?test=a&test=b&pages=5&pages=6'); const t2 = serializer.parse('/one/two?test=a&test=b'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(true); }); it('should return false when containee has array params but container does not have', () => { const t1 = serializer.parse('/one/two?test=a&test=b'); const t2 = serializer.parse('/one/two?test=a&test=b&pages=5&pages=6'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(false); }); it('should return false when containee has different queryParams', () => { const t1 = serializer.parse('/one/two?page=5'); const t2 = serializer.parse('/one/two?test=1'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(false); }); it('should return false when containee has more queryParams than container', () => { const t1 = serializer.parse('/one/two?page=5'); const t2 = serializer.parse('/one/two?page=5&test=1'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(false); }); }); describe('ignored query params', () => { it('should return true when queryParams differ but are ignored', () => { const t1 = serializer.parse('/?test=1&page=2'); const t2 = serializer.parse('/?test=3&page=4&x=y'); expect(containsTree(t1, t2, {...exactMatchOptions, queryParams: 'ignored'})).toBe(true); }); }); describe('fragment', () => { it('should return false when fragments differ but options require exact match', () => { const t1 = serializer.parse('/#fragment1'); const t2 = serializer.parse('/#fragment2'); expect(containsTree(t1, t2, {...exactMatchOptions, fragment: 'exact'})).toBe(false); }); it('should return true when fragments differ but options ignore the fragment', () => { const t1 = serializer.parse('/#fragment1'); const t2 = serializer.parse('/#fragment2'); expect(containsTree(t1, t2, {...exactMatchOptions, fragment: 'ignored'})).toBe(true); }); }); describe('matrix params', () => { describe('ignored', () => { it('returns true when matrix params differ but are ignored', () => { const t1 = serializer.parse('/a;id=15;foo=foo'); const t2 = serializer.parse('/a;abc=123'); expect(containsTree(t1, t2, {...exactMatchOptions, matrixParams: 'ignored'})).toBe(true); }); }); describe('exact match', () => { const matrixParams = 'exact'; it('returns true when matrix params match', () => { const t1 = serializer.parse('/a;id=15;foo=foo'); const t2 = serializer.parse('/a;id=15;foo=foo'); expect(containsTree(t1, t2, {...exactMatchOptions, matrixParams})).toBe(true); }); it('returns false when matrix params differ', () => { const t1 = serializer.parse('/a;id=15;foo=foo'); const t2 = serializer.parse('/a;abc=123'); expect(containsTree(t1, t2, {...exactMatchOptions, matrixParams})).toBe(false); }); it('returns true when matrix params match on the subset of the matched url tree', () => { const t1 = serializer.parse('/a;id=15;foo=bar/c'); const t2 = serializer.parse('/a;id=15;foo=bar'); expect(containsTree(t1, t2, {...subsetMatchOptions, matrixParams})).toBe(true); }); it('should return true when matrix params match on subset of urlTree match ' + 'with container paths split into multiple segments', () => { const t1 = serializer.parse('/one;a=1/(two;b=2//left:three)'); const t2 = serializer.parse('/one;a=1/two;b=2'); expect(containsTree(t1, t2, {...subsetMatchOptions, matrixParams})).toBe(true); }); }); describe('subset match', () => { const matrixParams = 'subset'; it('returns true when matrix params match', () => { const t1 = serializer.parse('/a;id=15;foo=foo'); const t2 = serializer.parse('/a;id=15;foo=foo'); expect(containsTree(t1, t2, {...exactMatchOptions, matrixParams})).toBe(true); }); it('returns true when container has extra matrix params', () => { const t1 = serializer.parse('/a;id=15;foo=foo'); const t2 = serializer.parse('/a;id=15'); expect(containsTree(t1, t2, {...exactMatchOptions, matrixParams})).toBe(true); }); it('returns false when matrix params differ', () => { const t1 = serializer.parse('/a;id=15;foo=foo'); const t2 = serializer.parse('/a;abc=123'); expect(containsTree(t1, t2, {...exactMatchOptions, matrixParams})).toBe(false); }); it('returns true when matrix params match on the subset of the matched url tree', () => { const t1 = serializer.parse('/a;id=15;foo=bar/c'); const t2 = serializer.parse('/a;id=15;foo=bar'); expect(containsTree(t1, t2, {...subsetMatchOptions, matrixParams})).toBe(true); }); it('should return true when matrix params match on subset of urlTree match ' + 'with container paths split into multiple segments', () => { const t1 = serializer.parse('/one;a=1/(two;b=2//left:three)'); const t2 = serializer.parse('/one;a=1/two'); expect(containsTree(t1, t2, {...subsetMatchOptions, matrixParams})).toBe(true); }); }); }); }); });
the_stack
import { TypeMap, Watchers, WiredProperties, WiredMethods, AirwireException, AirwirePromise, ComponentResponse, Magic, TypeName, TypeNames } from 'airwire' export class Component<AirwireComponent = TypeMap[keyof TypeMap]> { public proxy: any; public loading: boolean = false; public errors: Record<string, string[]> = {}; public _proxyTarget: Component<AirwireComponent>; public watchers: Watchers<AirwireComponent> = { responses: [], errors: [] }; public pausedRequests: boolean = false; public pendingChanges: Partial<{ [key in keyof WiredProperties<AirwireComponent>]: any }> = {}; public pendingCalls: Partial<{ [key in keyof WiredMethods<AirwireComponent>]: any }> = {}; public readonly: Partial<{ [key in keyof WiredProperties<AirwireComponent>]: any }> = {}; public reactive: CallableFunction; constructor( public alias: keyof TypeMap, public state: any, reactive: CallableFunction|null = null, ) { this.reactive = reactive ?? window.Airwire.reactive; this.readonly = state.readonly ?? {}; delete this.state.readonly; let component: Component<AirwireComponent> = this._proxyTarget = this.reactive(this); window.Airwire.components[alias] ??= []; window.Airwire.components[alias]?.push(component as any); // We never use `this` in this class, because we always want to refer to the singleton reactive proxy component.watch(response => { let mount = (response.metadata.calls as any)?.mount; if (mount) { component.replaceState(mount, response.metadata.readonly); } }); this.proxy = new Proxy(component.state, { get(target, property: string | symbol) { if (property === 'deferred') { return new Proxy(component.state, { get(target, property) { return component.proxy[property] }, set(target, property, value) { component.pendingChanges[property as keyof WiredProperties<AirwireComponent>] = value; return true } }); } if (property === 'readonly') { return component.readonly; } if (property === '$component') { return component; } // Methods are returned using wrapper methods bypass the Proxy let methods = ['watch', 'defer', 'refresh', 'remount']; if (typeof property === 'string' && methods.includes(property)) { return function (...args: any[]) { return component[property as keyof typeof component](...args); }; } // Whitelisted Component properties let properties = ['errors', 'loading']; if (typeof property === 'string' && properties.includes(property)) { return component[property as keyof typeof component]; } if (typeof property === 'string' && Object.keys(component.state).includes(property)) { return component.state[property]; } if (typeof property === 'string' && Object.keys(component.readonly).includes(property)) { return component.readonly[property as keyof WiredProperties<AirwireComponent>]; } if (typeof property === 'string' && !property.startsWith('__v') && property !== 'toJSON') { return function (...args: any[]) { return component.call.apply(component, [ property as keyof WiredMethods<AirwireComponent>, ...args ]); } } }, set(target, property: string, value) { component.update(property as keyof WiredProperties<AirwireComponent>, value); return true } }) } public update(property: keyof WiredProperties<AirwireComponent>, value: any): Promise<ComponentResponse<AirwireComponent>> | null { this.state[property] = value; if (this.pausedRequests) { this.pendingChanges[property] = value; return null; } return this.request(property, { changes: { [property]: value } }, (json: ComponentResponse<AirwireComponent>) => { if (json?.metadata?.exceptions) { return Promise.reject(json.metadata.exceptions); } return json }) } public call(method: keyof WiredMethods<AirwireComponent>, ...args: any[]): AirwirePromise<any> | null { if (this.pausedRequests) { this.pendingCalls[method] = args; return null; } return this.request(method, { calls: { [method]: args } }, (json: ComponentResponse<AirwireComponent>) => { if (json?.metadata?.exceptions) { return Promise.reject(json.metadata.exceptions[method] ?? json.metadata.exceptions); } return json; }).then((json: ComponentResponse<AirwireComponent>) => json?.metadata?.calls?.[method] ?? null); } public request(target: string, data: { calls?: { [key in string]: any[] }, changes?: { [key in string]: any }, }, callback: (json: ComponentResponse<AirwireComponent>) => any = (json: ComponentResponse<AirwireComponent>) => json): AirwirePromise<ComponentResponse<AirwireComponent>> { this.loading = true; let pendingChanges = this.pendingChanges; this.pendingChanges = {}; let pendingCalls = this.pendingCalls; this.pendingCalls = {}; let path = window.Airwire.route; return fetch(`${path}/${this.alias}/${target}`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', }, body: JSON.stringify({ state: this.state, calls: { ...pendingCalls, ...data?.calls ?? {} }, changes: { ...pendingChanges, ...data?.changes ?? {} }, }) }) .then(response => response.json()) .then((json: ComponentResponse<AirwireComponent>) => { this.loading = false window.Airwire.watchers.responses.forEach((watcher: any) => watcher(json as any)) this.watchers.responses.forEach(watcher => watcher(json)) return callback(json) }) .catch((reason: AirwireException) => { this.loading = false window.Airwire.watchers.errors.forEach((watcher: any) => watcher(reason)) this.watchers.errors.forEach(watcher => watcher(reason)) return reason }) .then((json: ComponentResponse<AirwireComponent>) => { if (json?.metadata?.errors) { this.errors = json.metadata.errors } this.replaceState(json.data, json?.metadata?.readonly) return json }) } public replaceState(state: any, readonly: any[]) { Object.entries(state).forEach(([key, value]) => { if (readonly && readonly.includes && readonly.includes(key)) { this.readonly[key as keyof WiredProperties<AirwireComponent>] = value; // Clean up state if the property wasn't readonly from the beginning if (this.state[key] !== undefined) { delete this.state[key]; } } else { this.state[key] = value; } }) } public watch(responses: (response: ComponentResponse<AirwireComponent>) => void, errors?: (error: AirwireException) => void): void { this.watchers.responses.push(responses); if (errors) { this.watchers.errors.push(errors); } } public defer<T>(callback: () => T): T | null { this.pausedRequests = true; let result = null; try { result = callback(); } catch (e) { this.pausedRequests = false; throw e } this.pausedRequests = false; return result; } public refresh() { return this.request('refresh', {}); } public remount(...args: any[]) { return this.request('mount', { calls: { mount: args, } }); } } export class Airwire { public route: string = '/airwire'; public watchers: Watchers<TypeMap[keyof TypeMap]> = { responses: [], errors: [] }; public components: Partial<{ [T in keyof TypeMap]: Array<Component<TypeMap[T]>> }> = {}; public constructor( public componentDefaults: any = {}, public reactive: CallableFunction = (component: Component) => component, ) { } public watch(responses: (response: ComponentResponse<TypeMap[keyof TypeMap]>) => void, errors?: (error: AirwireException) => void): Airwire { this.watchers.responses.push(responses); if (errors) { this.watchers.errors.push(errors); } return this; } public remount(aliases: keyof TypeMap | Array<keyof TypeMap> | null = null): void { this.refresh(aliases, true) } public refresh(aliases: keyof TypeMap | Array<keyof TypeMap> | null = null, remount: boolean = false): void { if (typeof aliases === 'string') { aliases = [aliases]; } if (! aliases) { aliases = Object.keys(this.components) as Array<keyof TypeMap>; } for (const alias of aliases) { this.components[alias]?.forEach((component: Component<any>) => { if (remount) { component.remount(); } else { component.refresh(); } }); } } public component<K extends TypeNames>(alias: K, state: WiredProperties<TypeName<K>>, reactive: CallableFunction | null = null): Magic<TypeName<K>> { const component = new Component<TypeName<K>>(alias, { ...this.componentDefaults[alias] ?? {}, ...state }, reactive); return component.proxy as TypeName<K>; } public plugin(name: string) { return require('./plugins/' + name).default; } } export default Airwire;
the_stack
import React, { useEffect, useState, useRef, useCallback } from "react"; import EditorView from "./EditorView"; import ListView from "./ListView"; import GraphView from "./GraphView"; import LoginView from "./LoginView"; import ConfirmationServiceProvider from "./ConfirmationServiceProvider"; import AppMenu from "./AppMenu"; import ExportDatabaseDialog from "./ExportDatabaseDialog"; import { paths } from "../lib/config"; import { Routes, Route, Navigate, useNavigate, } from "react-router-dom"; import useIsSmallScreen from "../hooks/useIsSmallScreen"; import FloatingActionButton from "./FloatingActionButton"; import { DatabaseMode } from "../enum/DatabaseMode.js"; import { DialogType } from "../enum/DialogType"; import StatsView from "./StatsView"; import NoteListItemType from "../../../lib/notes/interfaces/NoteListItem"; import * as Config from "../lib/config"; import ImportLinksDialog from "./ImportLinksDialog"; import FilesView from "./FilesView"; import FileView from "./FileView"; const App = ({ localDatabaseProvider, serverDatabaseProvider, }) => { const [unsavedChanges, setUnsavedChanges] = useState<boolean>(false); const [isAppMenuOpen, setIsAppMenuOpen] = useState<boolean>(false); const [openDialog, setOpenDialog] = useState<DialogType>(DialogType.NONE); const [databaseMode, setDatabaseMode] = useState<DatabaseMode>(DatabaseMode.NONE); /* states for note list */ const currentRequestId = useRef<string>(""); const [noteListItems, setNoteListItems] = useState<NoteListItemType[]>([]); const [numberOfResults, setNumberOfResults] = useState<number>(NaN); const [noteListScrollTop, setNoteListScrollTop] = useState<number>(0); const [page, setPage] = useState<number>(1); const [noteListIsBusy, setNoteListIsBusy] = useState<boolean>(true); const [stats, setStats] = useState(null); const [sortMode, setSortMode] = useState("UPDATE_DATE_DESCENDING"); const [searchValue, setSearchValue] = useState<string>(""); const [pinnedNotes, setPinnedNotes] = useState<any[]>([]); const databaseProvider = databaseMode === DatabaseMode.LOCAL ? localDatabaseProvider : ( databaseMode === DatabaseMode.SERVER ? serverDatabaseProvider : null ); const navigate = useNavigate(); const isSmallScreen = useIsSmallScreen(); const handleSearchInputChange = (value) => { setSearchValue(value); setNoteListScrollTop(0); setPage(1); }; const refreshStats = () => { if (!databaseProvider) return; databaseProvider.getStats({ includeMetadata: false, includeAnalysis: false, }) .then((stats) => { setStats(stats); }) .catch((e) => { // if credentials are invalid, it's fine, refeshNotesList takes care of // this. if there is another error, throw. if (e.message !== "INVALID_CREDENTIALS") { throw new Error(e); } }); }; const handleInvalidCredentialsError = async () => { await databaseProvider.removeAccess(); setDatabaseMode(DatabaseMode.NONE); navigate(paths.login); }; const refreshNotesList = useCallback( async () => { if (!databaseProvider) return; refreshStats(); setNoteListItems([]); // if searchValue is given but below MINIMUM_SEARCH_QUERY_LENGTH, // we don't do anything and leave the note list empty if ( searchValue.length > 0 && searchValue.length < Config.MINIMUM_SEARCH_QUERY_LENGTH ) { return; } setNoteListIsBusy(true); const options = { page, sortMode, searchString: "", caseSensitive: false, }; if (searchValue.length >= Config.MINIMUM_SEARCH_QUERY_LENGTH) { options.searchString = searchValue; } // @ts-ignore randomUUID not yet in types const requestId = crypto.randomUUID(); currentRequestId.current = requestId; try { const { results, numberOfResults, } = await databaseProvider.getNotes(options); // ... some time later - check if this is the current request if (currentRequestId.current === requestId) { setNoteListItems(results); setNumberOfResults(numberOfResults); setNoteListIsBusy(false); } const pinnedNotes = await databaseProvider.getPins(); setPinnedNotes(pinnedNotes); } catch (e) { // if credentials are invalid, go to LoginView. If not, throw. if (e.message === "INVALID_CREDENTIALS") { await handleInvalidCredentialsError(); } else { throw new Error(e); } } }, [searchValue, page, sortMode, databaseProvider], ); const handleSortModeChange = (sortMode) => { setNoteListScrollTop(0); setSortMode(sortMode); setPage(1); }; useEffect(() => { refreshNotesList(); }, [searchValue, page, sortMode, databaseProvider]); const beforeUnload = function(e) { if (unsavedChanges) { // Cancel the event e.preventDefault(); // If you prevent default behavior in Mozilla Firefox prompt will // always be shown // Chrome requires returnValue to be set e.returnValue = ""; } else { // the absence of a returnValue property on the event will guarantee // the browser unload happens delete e.returnValue; } }; useEffect(() => { const handleKeyPress = (e) => { if (e.key === "Escape") { setOpenDialog(DialogType.NONE); } }; window.addEventListener("beforeunload", beforeUnload); document.addEventListener("keydown", handleKeyPress); return () => { window.removeEventListener("beforeunload", beforeUnload); document.removeEventListener("keydown", handleKeyPress); }; }, [beforeUnload]); const toggleAppMenu = () => { setIsAppMenuOpen(!isAppMenuOpen); }; const importLinksAsNotes = async (links) => { await databaseProvider.importLinksAsNotes(links); setOpenDialog(DialogType.NONE); refreshNotesList(); }; const startApp = async () => { if (await serverDatabaseProvider?.isAuthenticated()) { setDatabaseMode(DatabaseMode.SERVER); if ( location.pathname.startsWith(paths.login) || location.pathname === "/" ) { navigate(isSmallScreen ? paths.list : paths.editorWithNewNote); } } else { navigate(paths.login); } }; useEffect(() => { startApp(); }, []); return <ConfirmationServiceProvider> <Routes> {/* this route is just to get rid of a react-router warning startApp() will take care of navigating to the correct start route */} <Route path="/" element={ <></> } /> <Route path={paths.login} element={ <LoginView setDatabaseMode={setDatabaseMode} serverDatabaseProvider={serverDatabaseProvider} localDatabaseProvider={localDatabaseProvider} /> } /> <Route path={paths.editor} element={ <Navigate to={paths.editorWithNewNote} replace /> } /> <Route path={paths.editor + "/:activeNoteId"} element={ databaseProvider ? <EditorView databaseProvider={databaseProvider} unsavedChanges={unsavedChanges} setUnsavedChanges={setUnsavedChanges} toggleAppMenu={toggleAppMenu} setOpenDialog={setOpenDialog} openDialog={openDialog} handleInvalidCredentialsError={handleInvalidCredentialsError} refreshNotesList={refreshNotesList} stats={stats} pinnedNotes={pinnedNotes} handleSearchInputChange={handleSearchInputChange} setPinnedNotes={setPinnedNotes} searchValue={searchValue} sortMode={sortMode} handleSortModeChange={handleSortModeChange} noteListItems={noteListItems} numberOfResults={numberOfResults} noteListIsBusy={noteListIsBusy} noteListScrollTop={noteListScrollTop} setNoteListScrollTop={setNoteListScrollTop} page={page} setPage={setPage} setSearchValue={setSearchValue} /> : null } /> <Route path={paths.list} element={ databaseProvider ? <> <ListView toggleAppMenu={toggleAppMenu} openDialog={openDialog} setOpenDialog={setOpenDialog} refreshNotesList={refreshNotesList} stats={stats} pinnedNotes={pinnedNotes} handleSearchInputChange={handleSearchInputChange} searchValue={searchValue} sortMode={sortMode} handleSortModeChange={handleSortModeChange} noteListItems={noteListItems} numberOfResults={numberOfResults} noteListIsBusy={noteListIsBusy} noteListScrollTop={noteListScrollTop} setNoteListScrollTop={setNoteListScrollTop} page={page} setPage={setPage} setSearchValue={setSearchValue} unsavedChanges={unsavedChanges} setUnsavedChanges={setUnsavedChanges} /> <FloatingActionButton title="New note" icon="add" onClick={() => navigate(paths.editorWithNewNote)} ></FloatingActionButton> </> : null } /> <Route path={paths.graph} element={ <GraphView unsavedChanges={unsavedChanges} setUnsavedChanges={setUnsavedChanges} databaseProvider={databaseProvider} toggleAppMenu={toggleAppMenu} handleInvalidCredentialsError={handleInvalidCredentialsError} /> } /> <Route path={paths.files} element={ <FilesView databaseProvider={databaseProvider} toggleAppMenu={toggleAppMenu} /> } /> <Route path={paths.files + "/:fileId"} element={ <FileView databaseProvider={databaseProvider} toggleAppMenu={toggleAppMenu} /> } /> <Route path={paths.stats} element={ <StatsView databaseProvider={databaseProvider} toggleAppMenu={toggleAppMenu} /> } /> </Routes> { isAppMenuOpen ? <AppMenu openExportDatabaseDialog={ () => setOpenDialog(DialogType.EXPORT_DATABASE) } onClose={() => setIsAppMenuOpen(false)} unsavedChanges={unsavedChanges} setUnsavedChanges={setUnsavedChanges} databaseProvider={databaseProvider} openImportLinksDialog={() => setOpenDialog(DialogType.IMPORT_LINKS)} /> : null } { openDialog === DialogType.EXPORT_DATABASE ? <ExportDatabaseDialog onCancel={() => setOpenDialog(DialogType.NONE)} databaseProvider={databaseProvider} /> : null } { openDialog === DialogType.IMPORT_LINKS ? <ImportLinksDialog importLinksAsNotes={importLinksAsNotes} onCancel={() => setOpenDialog(DialogType.NONE)} /> : null } </ConfirmationServiceProvider>; }; export default App;
the_stack
import Vue from 'vue' import { mount, Wrapper, MountOptions, } from '@vue/test-utils' import VTreeview from '../VTreeview' import { ExtractVue } from '../../../util/mixins' import { wait } from '../../../../test' const singleRootTwoChildren = [ { id: 0, name: 'Root', children: [{ id: 1, name: 'Child' }, { id: 2, name: 'Child 2' }] }, ] const threeLevels = [ { id: 0, name: 'Root', children: [{ id: 1, name: 'Child', children: [{ id: 2, name: 'Grandchild' }] }, { id: 3, name: 'Child' }] }, ] describe('VTreeView.ts', () => { // eslint-disable-line max-statements type Instance = ExtractVue<typeof VTreeview> let mountFunction: (options?: MountOptions<Instance>) => Wrapper<Instance> beforeEach(() => { mountFunction = (options?: MountOptions<Instance>) => { return mount(VTreeview, { // https://github.com/vuejs/vue-test-utils/issues/1130 sync: false, ...options, }) } }) it('should render items', async () => { const wrapper = mountFunction({ propsData: { items: singleRootTwoChildren, }, }) expect(wrapper.html()).toMatchSnapshot() }) it('should render items in dense mode', async () => { const wrapper = mountFunction({ propsData: { items: singleRootTwoChildren, dense: true, }, }) expect(wrapper.html()).toMatchSnapshot() }) // TODO: this fails without sync, nextTick doesn't help // https://github.com/vuejs/vue-test-utils/issues/1130 it.skip('should select all leaf nodes', async () => { const wrapper = mountFunction({ propsData: { items: threeLevels, selectable: true, }, }) const fn = jest.fn() wrapper.vm.$on('input', fn) wrapper.find('.v-treeview-node__checkbox').trigger('click') await wrapper.vm.$nextTick() expect(fn).toHaveBeenCalledTimes(1) expect(fn).toHaveBeenCalledWith([3, 2]) expect(wrapper.html()).toMatchSnapshot() }) // TODO: this fails without sync, nextTick doesn't help // https://github.com/vuejs/vue-test-utils/issues/1130 it.skip('should select only leaf nodes', async () => { const wrapper = mountFunction({ propsData: { items: threeLevels, selectable: true, }, }) const fn = jest.fn() wrapper.vm.$on('input', fn) wrapper.find('.v-treeview-node__toggle').trigger('click') await wrapper.vm.$nextTick() wrapper.findAll('.v-treeview-node__checkbox').at(2).trigger('click') await wrapper.vm.$nextTick() expect(fn).toHaveBeenCalledTimes(1) expect(fn).toHaveBeenCalledWith([3]) expect(wrapper.html()).toMatchSnapshot() }) // TODO: this fails without sync, nextTick doesn't help // https://github.com/vuejs/vue-test-utils/issues/1130 it.skip('should select only root node', async () => { const wrapper = mountFunction({ propsData: { items: threeLevels, selectable: true, selectionType: 'independent', }, }) const fn = jest.fn() wrapper.vm.$on('input', fn) wrapper.find('.v-treeview-node__checkbox').trigger('click') await wrapper.vm.$nextTick() expect(fn).toHaveBeenCalledTimes(1) expect(fn).toHaveBeenCalledWith([0]) expect(wrapper.html()).toMatchSnapshot() }) // TODO: fails with TS 3.9 it.skip('should load children when expanding', async () => { const loadChildren = item => { item.children.push({ id: 1, name: 'Child' }) } const wrapper = mountFunction({ propsData: { items: [{ id: 0, name: 'Root', children: [] }], loadChildren, }, }) expect(wrapper.html()).toMatchSnapshot() wrapper.find('.v-treeview-node__toggle').trigger('click') await wrapper.vm.$nextTick() expect(wrapper.html()).toMatchSnapshot() expect(`[Vue warn]: Error in created hook: "TypeError: Cannot set property 'vnode' of undefined"`).toHaveBeenWarned() expect(`TypeError: Cannot set property 'vnode' of undefined`).toHaveBeenWarned() }) it('should load children when selecting, but not render', async () => { const loadChildren = item => { item.children = [{ id: 1, name: 'Child' }] } const wrapper = mountFunction({ propsData: { items: [{ id: 0, name: 'Root', children: [] }], selectable: true, loadChildren, }, }) const fn = jest.fn() wrapper.vm.$on('input', fn) expect(wrapper.html()).toMatchSnapshot() wrapper.find('.v-treeview-node__checkbox').trigger('click') await wait() expect(fn).toHaveBeenCalledTimes(1) expect(fn).toHaveBeenCalledWith([0]) expect(wrapper.html()).toMatchSnapshot() }) it('should emit active node when clicking on it', async () => { const wrapper = mountFunction({ propsData: { items: [{ id: 0, name: 'Root' }, { id: 1, name: 'Root' }], activatable: true, }, }) const fn = jest.fn() wrapper.vm.$on('update:active', fn) wrapper.find('.v-treeview-node__root').trigger('click') await wrapper.vm.$nextTick() expect(fn).toHaveBeenCalledTimes(1) expect(fn).toHaveBeenCalledWith([0]) wrapper.find('.v-treeview-node__root').trigger('click') await wrapper.vm.$nextTick() expect(fn).toHaveBeenCalledWith([]) }) it('should allow multiple active nodes with prop multipleActive', async () => { const wrapper = mountFunction({ propsData: { items: [{ id: 0, name: 'Root' }, { id: 1, name: 'Root' }], multipleActive: true, activatable: true, }, }) const fn = jest.fn() wrapper.vm.$on('update:active', fn) wrapper.findAll('.v-treeview-node__root').wrappers.forEach(vm => vm.trigger('click')) await wrapper.vm.$nextTick() expect(fn).toHaveBeenCalledTimes(2) expect(fn).toHaveBeenLastCalledWith([0, 1]) }) // TODO: fails with TS 3.9 it.skip('should update selection when selected prop changes', async () => { const wrapper = mountFunction({ propsData: { items: [{ id: 0, name: 'Root', children: [{ id: 1, name: 'Child' }] }], value: [], selectable: true, }, }) expect(wrapper.html()).toMatchSnapshot() wrapper.find('.v-treeview-node__toggle').trigger('click') wrapper.setProps({ value: [1] }) await wrapper.vm.$nextTick() expect(wrapper.findAll('.v-treeview-node')).toHaveLength(2) expect(wrapper.findAll('.v-treeview-node--selected')).toHaveLength(2) expect(wrapper.html()).toMatchSnapshot() wrapper.setProps({ value: [] }) await wrapper.vm.$nextTick() expect(wrapper.html()).toMatchSnapshot() }) it('should open all children when using open-all prop', async () => { const wrapper = mountFunction({ propsData: { items: threeLevels, openAll: true, }, }) await wrapper.vm.$nextTick() expect(wrapper.html()).toMatchSnapshot() }) it('should open/close all children when using updateAll', async () => { const wrapper = mountFunction({ propsData: { items: threeLevels, }, }) const updateOpen = jest.fn() wrapper.vm.$on('update:open', updateOpen) wrapper.vm.updateAll(true) expect(updateOpen).toHaveBeenCalledTimes(1) expect(updateOpen).toHaveBeenCalledWith([0, 1]) wrapper.vm.updateAll(false) expect(updateOpen).toHaveBeenCalledTimes(2) expect(updateOpen).toHaveBeenCalledWith([]) }) it('should react to open changes', async () => { const wrapper = mountFunction({ propsData: { items: threeLevels, open: [1], }, }) const fn = jest.fn() wrapper.vm.$on('update:open', fn) wrapper.setProps({ open: [0, 1] }) await wrapper.vm.$nextTick() expect(wrapper.html()).toMatchSnapshot() wrapper.setProps({ open: [0] }) await wrapper.vm.$nextTick() expect(wrapper.html()).toMatchSnapshot() wrapper.setProps({ open: [0, 1] }) await wrapper.vm.$nextTick() expect(wrapper.html()).toMatchSnapshot() expect(fn).toHaveBeenCalledWith([0, 1]) // Should not update open values that do not exist in the tree wrapper.setProps({ open: [7] }) await wrapper.vm.$nextTick() expect(wrapper.html()).toMatchSnapshot() expect(fn).toHaveBeenCalledWith([]) }) it('should update selected and active on created', async () => { const wrapper = mountFunction({ propsData: { items: threeLevels, active: [2], value: [1], }, }) // TODO: I can not find away in avoriaz // to catch events being emitted from a // lifecycle hook. We should not assert // internal state. expect([...wrapper.vm.activeCache]).toEqual([2]) expect([...wrapper.vm.selectedCache]).toEqual([2]) }) it('should react to changes for active items', async () => { const wrapper = mountFunction({ propsData: { items: threeLevels, active: [2], }, }) const active = jest.fn() wrapper.vm.$on('update:active', active) wrapper.setProps({ active: [] }) await wrapper.vm.$nextTick() expect(active).toHaveBeenCalledWith([]) // without multiple-active, it will use last value in array wrapper.setProps({ active: [1, 3] }) await wrapper.vm.$nextTick() expect(active).toHaveBeenCalledWith([3]) wrapper.setProps({ multipleActive: true, active: [1, 3] }) await wrapper.vm.$nextTick() expect(active).toHaveBeenCalledWith([1, 3]) // 7 does not exist, we get nothing back wrapper.setProps({ active: [7] }) await wrapper.vm.$nextTick() expect(active).toHaveBeenCalledWith([]) wrapper.setProps({ active: [0], items: singleRootTwoChildren }) await wrapper.vm.$nextTick() expect(active).toHaveBeenCalledWith([0]) }) it('should react to changes for selected items', async () => { const wrapper = mountFunction({ propsData: { items: threeLevels, value: [2], }, }) const value = jest.fn() wrapper.vm.$on('input', value) wrapper.setProps({ value: [] }) await wrapper.vm.$nextTick() expect(value).toHaveBeenCalledWith([]) wrapper.setProps({ value: [3] }) await wrapper.vm.$nextTick() expect(value).toHaveBeenCalledWith([3]) // 7 does not exist, we get nothing back wrapper.setProps({ value: [7] }) await wrapper.vm.$nextTick() expect(value).toHaveBeenCalledWith([]) wrapper.setProps({ value: [0] }) await wrapper.vm.$nextTick() expect(value).toHaveBeenLastCalledWith([3, 2]) }) it('should accept string value for id', async () => { const wrapper = mountFunction({ propsData: { itemKey: 'name' }, }) wrapper.setProps({ items: [{ name: 'Foobar' }] }) await wrapper.vm.$nextTick() expect(wrapper.vm.nodes.Foobar).toBeTruthy() wrapper.setProps({ value: ['Foobar'] }) await wrapper.vm.$nextTick() }) it('should warn developer when using non-scoped slots', () => { mountFunction({ slots: { prepend: [{ render: h => h('div') }], append: [{ render: h => h('div') }], }, }) expect('[Vuetify] The prepend and append slots require a slot-scope attribute').toHaveBeenTipped() }) it('should not show expand icon when children is empty', () => { const wrapper = mountFunction({ propsData: { items: [ { text: 'root', children: [], }, ], }, }) expect(wrapper.html()).toMatchSnapshot() expect(wrapper.findAll('.v-treeview-node__toggle')).toHaveLength(0) }) it('should show expand icon when children is empty and load-children prop used', () => { const wrapper = mountFunction({ propsData: { loadChildren: () => {}, items: [ { text: 'root', children: [], }, ], }, }) expect(wrapper.html()).toMatchSnapshot() expect(wrapper.findAll('.v-treeview-node__toggle')).toHaveLength(1) }) it('should recalculate tree when loading async children using custom key', async () => { const items = [ { id: 1, name: 'One', __children: [], }, ] const wrapper = mountFunction({ propsData: { items, itemChildren: '__children', loadChildren: () => { const newItems = [...items] items[0].__children.push({ id: 2, name: 'Two' }) wrapper.setProps({ items: newItems, }) }, }, }) wrapper.find('.v-treeview-node__toggle').trigger('click') await wrapper.vm.$nextTick() expect(wrapper.html()).toMatchSnapshot() }) it('should remove old nodes', async () => { const wrapper = mountFunction({ propsData: { items: [ { id: 1, name: 'one', }, { id: 2, name: 'two', }, ], }, }) expect(wrapper.html()).toMatchSnapshot() wrapper.setProps({ items: [ { id: 1, name: 'one', }, ], }) await wrapper.vm.$nextTick() expect(wrapper.html()).toMatchSnapshot() wrapper.setProps({ items: [ { id: 1, name: 'one', }, { id: 3, name: 'three', }, ], }) await wrapper.vm.$nextTick() expect(wrapper.html()).toMatchSnapshot() expect(Object.keys(wrapper.vm.nodes)).toHaveLength(2) }) it('should filter items', async () => { const wrapper = mountFunction({ propsData: { items: [ { id: 1, name: 'one', }, { id: 2, name: 'two', }, ], }, }) expect(wrapper.html()).toMatchSnapshot() wrapper.setProps({ search: 'two', }) await wrapper.vm.$nextTick() expect(wrapper.html()).toMatchSnapshot() }) it('should filter items using custom item filter', async () => { const wrapper = mountFunction({ propsData: { filter: (item, search, textKey) => item.special === search, items: [ { id: 1, name: 'one', special: 'yes', }, { id: 2, name: 'two', special: 'no', }, ], search: 'NO', }, }) expect(wrapper.html()).toMatchSnapshot() wrapper.setProps({ search: 'yes', }) await wrapper.vm.$nextTick() expect(wrapper.html()).toMatchSnapshot() }) // TODO: fails with TS 3.9 it.skip('should emit objects when return-object prop is used', async () => { const items = [{ id: 0, name: 'Root', children: [{ id: 1, name: 'Child' }] }] const wrapper = mountFunction({ propsData: { items, activatable: true, selectable: true, returnObject: true, }, }) const active = jest.fn() wrapper.vm.$on('update:active', active) const selected = jest.fn() wrapper.vm.$on('input', selected) const open = jest.fn() wrapper.vm.$on('update:open', open) wrapper.find('.v-treeview-node__root').trigger('click') await wrapper.vm.$nextTick() expect(active).toHaveBeenCalledTimes(1) expect(active).toHaveBeenCalledWith([items[0]]) wrapper.find('.v-treeview-node__checkbox').trigger('click') await wrapper.vm.$nextTick() expect(selected).toHaveBeenCalledTimes(1) expect(selected).toHaveBeenCalledWith([items[0].children[0]]) wrapper.find('.v-treeview-node__toggle').trigger('click') await wrapper.vm.$nextTick() expect(open).toHaveBeenCalledTimes(1) expect(open).toHaveBeenCalledWith([items[0]]) }) it('should handle replacing items with new array of equal length', async () => { const wrapper = mountFunction({ propsData: { items: [ { id: 1, name: 'one', }, { id: 2, name: 'two', }, ], }, }) expect(wrapper.html()).toMatchSnapshot() wrapper.setProps({ items: [ { id: 1, name: 'one', }, { id: 3, name: 'three', }, ], }) await wrapper.vm.$nextTick() expect(wrapper.html()).toMatchSnapshot() }) // https://github.com/vuetifyjs/vuetify/issues/8709 it('should handle initial active/open/selected values when using return-object prop', async () => { const one = { id: '1', name: 'One' } const three = { id: '3', name: 'Three' } const two = { id: '2', name: 'Two', children: [three] } const wrapper = mountFunction({ propsData: { returnObject: true, selectable: true, activatable: true, items: [one, two], value: [one], open: [two], active: [three], }, }) await wrapper.vm.$nextTick() expect(wrapper.html()).toMatchSnapshot() }) it('should set correct state when updating nodes', async () => { const children = [ { id: 2, name: 'Bar' }, { id: 3, name: 'Fizz' }, { id: 4, name: 'Buzz' }, ] const item = { id: 1, name: 'Foo', } const wrapper = mountFunction({ propsData: { items: [{ ...item, children }], value: [4], }, }) wrapper.setProps({ items: [{ ...item, children: [ ...children, { id: 5, name: 'FizzBuzz' }, ], }], }) await wrapper.vm.$nextTick() expect(wrapper.vm.nodes['5'].isIndeterminate).toBeUndefined() }) // https://github.com/vuetifyjs/vuetify/issues/8720 it('should set correct selection when updating items', async () => { const items = [{ id: 1, name: 'Foo', children: [ { id: 2, name: 'Bar' }, { id: 3, name: 'Fizz' }, { id: 4, name: 'Buzz' }, ], }] const input = jest.fn() const wrapper = mountFunction({ propsData: { items, value: [2, 3, 4], selectionType: 'leaf', selectable: true, }, listeners: { input, }, }) wrapper.setProps({ items: [{ id: 1, name: 'Foo', children: [ { id: 2, name: 'Bar' }, { id: 3, name: 'Fizz' }, { id: 4, name: 'Buzz' }, ], }], }) await wrapper.vm.$nextTick() expect(input).not.toHaveBeenCalled() }) // https://github.com/vuetifyjs/vuetify/issues/8244 // TODO: fails with TS 3.9 it.skip('should not touch disabled items when selecting', async () => { const items = [{ id: 1, name: 'Foo', children: [ { id: 2, name: 'Bar', disabled: true }, { id: 3, name: 'Fizz' }, { id: 4, name: 'Buzz' }, ], }] const input = jest.fn() const wrapper = mountFunction({ propsData: { items, value: [], selectionType: 'leaf', selectable: true, }, listeners: { input, }, }) wrapper.find('.v-treeview-node__checkbox').trigger('click') await wrapper.vm.$nextTick() expect(input).toHaveBeenLastCalledWith([3, 4]) wrapper.setProps({ value: [2, 3, 4], items: [{ id: 1, name: 'Foo', children: [ { id: 2, name: 'Bar', disabled: true }, { id: 3, name: 'Fizz' }, { id: 4, name: 'Buzz' }, ], }], }) await wrapper.vm.$nextTick() wrapper.find('.v-treeview-node__checkbox').trigger('click') await wrapper.vm.$nextTick() expect(input).toHaveBeenLastCalledWith([2]) }) // https://github.com/vuetifyjs/vuetify/issues/10990 // https://github.com/vuetifyjs/vuetify/issues/10770 // TODO: fails with TS 3.9 it.skip('should not disable children of disabled parent when in independent mode', async () => { const items = [{ id: 1, name: 'Foo', disabled: true, children: [ { id: 2, name: 'Bar' }, { id: 3, name: 'Fizz', disabled: true }, { id: 4, name: 'Buzz' }, ], }] const input = jest.fn() const wrapper = mountFunction({ propsData: { items, value: [], open: [1], selectionType: 'independent', selectable: true, }, listeners: { input, }, }) await wrapper.vm.$nextTick() wrapper.findAll('.v-treeview-node__checkbox').at(1).trigger('click') await wrapper.vm.$nextTick() expect(input).toHaveBeenLastCalledWith([2]) wrapper.findAll('.v-treeview-node__checkbox').at(2).trigger('click') await wrapper.vm.$nextTick() expect(input).toHaveBeenCalledTimes(1) }) // https://github.com/vuetifyjs/vuetify/issues/9693 // TODO: fails with TS 3.9 it.skip('should emit opened node when using open-on-click and load-children', async () => { const open = jest.fn() const wrapper = mountFunction({ propsData: { items: [{ id: 0, name: 'Root', children: [] }], loadChildren: () => wrapper.setProps({ items: [{ id: 0, name: 'Root', children: [{ id: 1, name: 'Child' }] }], }), openOnClick: true, }, listeners: { 'update:open': open, }, }) expect(wrapper.html()).toMatchSnapshot() wrapper.find('.v-treeview-node__root').trigger('click') await wrapper.vm.$nextTick() expect(wrapper.html()).toMatchSnapshot() expect(open).toHaveBeenLastCalledWith([0]) }) })
the_stack
import { nextTick } from 'vue' import XEUtils from 'xe-utils' import { VXETable } from '../../v-x-e-table' import { toFilters, handleFieldOrColumn } from '../../table/src/util' import { getDomNode, triggerEvent } from '../../tools/dom' import { VxeGlobalHooksHandles, TableFilterMethods, TableFilterPrivateMethods } from '../../../types/all' const tableFilterMethodKeys: (keyof TableFilterMethods)[] = ['setFilter', 'clearFilter', 'getCheckedFilters'] const tableFilterHook: VxeGlobalHooksHandles.HookOptions = { setupTable ($xetable) { const { reactData, internalData } = $xetable const { refTableBody, refTableFilter } = $xetable.getRefMaps() const { computeFilterOpts } = $xetable.getComputeMaps() const filterPrivateMethods: TableFilterPrivateMethods = { checkFilterOptions () { const { filterStore } = reactData filterStore.isAllSelected = filterStore.options.every((item: any) => item._checked) filterStore.isIndeterminate = !filterStore.isAllSelected && filterStore.options.some((item: any) => item._checked) }, /** * 点击筛选事件 * 当筛选图标被点击时触发 * 更新选项是否全部状态 * 打开筛选面板 * @param {Event} evnt 事件 * @param {ColumnInfo} column 列配置 * @param {Object} params 参数 */ triggerFilterEvent (evnt, column, params) { const { initStore, filterStore } = reactData if (filterStore.column === column && filterStore.visible) { filterStore.visible = false } else { const { target: targetElem, pageX } = evnt const { visibleWidth } = getDomNode() const { filters, filterMultiple, filterRender } = column const compConf = filterRender ? VXETable.renderer.get(filterRender.name) : null const filterRecoverMethod = column.filterRecoverMethod || (compConf ? compConf.filterRecoverMethod : null) internalData._currFilterParams = params Object.assign(filterStore, { multiple: filterMultiple, options: filters, column, style: null }) // 复原状态 filterStore.options.forEach((option: any) => { const { _checked, checked } = option option._checked = checked if (!checked && _checked !== checked) { if (filterRecoverMethod) { filterRecoverMethod({ option, column, $table: $xetable }) } } }) this.checkFilterOptions() filterStore.visible = true initStore.filter = true nextTick(() => { const tableBody = refTableBody.value const bodyElem = tableBody.$el as HTMLDivElement const tableFilter = refTableFilter.value const filterWrapperElem = tableFilter ? tableFilter.$el as HTMLDivElement : null let filterWidth = 0 let filterHeight = 0 let filterHeadElem: HTMLDivElement | null = null let filterFootElem: HTMLDivElement | null = null if (filterWrapperElem) { filterWidth = filterWrapperElem.offsetWidth filterHeight = filterWrapperElem.offsetHeight filterHeadElem = filterWrapperElem.querySelector('.vxe-table--filter-header') filterFootElem = filterWrapperElem.querySelector('.vxe-table--filter-footer') } const centerWidth = filterWidth / 2 const minMargin = 10 const maxLeft = bodyElem.clientWidth - filterWidth - minMargin let left, right const style: any = { top: `${targetElem.offsetTop + targetElem.offsetParent.offsetTop + targetElem.offsetHeight + 8}px` } // 判断面板不能大于表格高度 let maxHeight = null if (filterHeight >= bodyElem.clientHeight) { maxHeight = Math.max(60, bodyElem.clientHeight - (filterFootElem ? filterFootElem.offsetHeight : 0) - (filterHeadElem ? filterHeadElem.offsetHeight : 0)) } if (column.fixed === 'left') { left = targetElem.offsetLeft + targetElem.offsetParent.offsetLeft - centerWidth } else if (column.fixed === 'right') { right = (targetElem.offsetParent.offsetWidth - targetElem.offsetLeft) + (targetElem.offsetParent.offsetParent.offsetWidth - targetElem.offsetParent.offsetLeft) - column.renderWidth - centerWidth } else { left = targetElem.offsetLeft + targetElem.offsetParent.offsetLeft - centerWidth - bodyElem.scrollLeft } if (left) { const overflowWidth = (pageX + filterWidth - centerWidth + minMargin) - visibleWidth if (overflowWidth > 0) { left -= overflowWidth } style.left = `${Math.min(maxLeft, Math.max(minMargin, left))}px` } else if (right) { const overflowWidth = (pageX + filterWidth - centerWidth + minMargin) - visibleWidth if (overflowWidth > 0) { right += overflowWidth } style.right = `${Math.max(minMargin, right)}px` } filterStore.style = style filterStore.maxHeight = maxHeight }) } $xetable.dispatchEvent('filter-visible', { column, field: column.field, property: column.field, filterList: $xetable.getCheckedFilters(), visible: filterStore.visible }, evnt) }, handleClearFilter (column) { if (column) { const { filters, filterRender } = column if (filters) { const compConf = filterRender ? VXETable.renderer.get(filterRender.name) : null const filterResetMethod = column.filterResetMethod || (compConf ? compConf.filterResetMethod : null) filters.forEach((item: any) => { item._checked = false item.checked = false if (!filterResetMethod) { item.data = XEUtils.clone(item.resetValue, true) } }) if (filterResetMethod) { filterResetMethod({ options: filters, column, $table: $xetable }) } } } }, /** * 确认筛选 * 当筛选面板中的确定按钮被按下时触发 * @param {Event} evnt 事件 */ confirmFilterEvent (evnt: Event) { const { filterStore, scrollXLoad: oldScrollXLoad, scrollYLoad: oldScrollYLoad } = reactData const filterOpts = computeFilterOpts.value const { column } = filterStore const { field } = column const values: any[] = [] const datas: any[] = [] column.filters.forEach((item: any) => { if (item.checked) { values.push(item.value) datas.push(item.data) } }) const filterList = $xetable.getCheckedFilters() // 如果是服务端筛选,则跳过本地筛选处理 if (!filterOpts.remote) { $xetable.handleTableData(true) $xetable.checkSelectionStatus() } $xetable.dispatchEvent('filter-change', { column, field, property: field, values, datas, filters: filterList, filterList }, evnt) $xetable.closeFilter() $xetable.updateFooter().then(() => { const { scrollXLoad, scrollYLoad } = reactData if ((oldScrollXLoad || scrollXLoad) || (oldScrollYLoad || scrollYLoad)) { if (oldScrollXLoad || scrollXLoad) { $xetable.updateScrollXSpace() } if (oldScrollYLoad || scrollYLoad) { $xetable.updateScrollYSpace() } return $xetable.refreshScroll() } }).then(() => { $xetable.updateCellAreas() return $xetable.recalculate(true) }).then(() => { // 存在滚动行为未结束情况 setTimeout(() => $xetable.recalculate(), 50) }) } } const filterMethods: TableFilterMethods = { /** * 手动弹出筛选面板 * @param column */ openFilter (fieldOrColumn) { const column = handleFieldOrColumn($xetable, fieldOrColumn) if (column && column.filters) { const { elemStore } = internalData const { fixed } = column return $xetable.scrollToColumn(column).then(() => { const headerWrapperRef = elemStore[`${fixed || 'main'}-header-wrapper`] || elemStore['main-header-wrapper'] const headerWrapperElem = headerWrapperRef ? headerWrapperRef.value : null if (headerWrapperElem) { const filterBtnElem = headerWrapperElem.querySelector(`.vxe-header--column.${column.id} .vxe-filter--btn`) as HTMLElement triggerEvent(filterBtnElem, 'click') } }) } return nextTick() }, /** * 修改筛选条件列表 * @param {ColumnInfo} fieldOrColumn 列或字段名 * @param {Array} options 选项 */ setFilter (fieldOrColumn, options) { const column = handleFieldOrColumn($xetable, fieldOrColumn) if (column && column.filters && options) { column.filters = toFilters(options) } return nextTick() }, /** * 清空指定列的筛选条件 * 如果为空则清空所有列的筛选条件 * @param {String} fieldOrColumn 列或字段名 */ clearFilter (fieldOrColumn) { const { filterStore } = reactData const { tableFullColumn } = internalData const filterOpts = computeFilterOpts.value let column if (fieldOrColumn) { column = handleFieldOrColumn($xetable, fieldOrColumn) if (column) { filterPrivateMethods.handleClearFilter(column) } } else { tableFullColumn.forEach(filterPrivateMethods.handleClearFilter) } if (!fieldOrColumn || column !== filterStore.column) { Object.assign(filterStore, { isAllSelected: false, isIndeterminate: false, style: null, options: [], column: null, multiple: false, visible: false }) } if (!filterOpts.remote) { return $xetable.updateData() } return nextTick() }, getCheckedFilters () { const { tableFullColumn } = internalData const filterList: any[] = [] tableFullColumn.filter((column) => { const { field, filters } = column const valueList: any[] = [] const dataList: any[] = [] if (filters && filters.length) { filters.forEach((item) => { if (item.checked) { valueList.push(item.value) dataList.push(item.data) } }) if (valueList.length) { filterList.push({ column, field, property: field, values: valueList, datas: dataList }) } } }) return filterList } } return { ...filterMethods, ...filterPrivateMethods } }, setupGrid ($xegrid) { return $xegrid.extendTableMethods(tableFilterMethodKeys) } } export default tableFilterHook
the_stack
import { OrderDiscountCommonInput, OrderErrorCode, OrderEventsEmailsEnum, OrderEventsEnum, FulfillmentStatus, PaymentChargeStatusEnum, OrderStatus, OrderAction, JobStatusEnum } from "./../../types/globalTypes"; // ==================================================== // GraphQL mutation operation: OrderLineDiscountAdd // ==================================================== export interface OrderLineDiscountAdd_orderLineDiscountAdd_errors { __typename: "OrderError"; code: OrderErrorCode; field: string | null; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_metadata { __typename: "MetadataItem"; key: string; value: string; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_privateMetadata { __typename: "MetadataItem"; key: string; value: string; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_billingAddress_country { __typename: "CountryDisplay"; code: string; country: string; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_billingAddress { __typename: "Address"; city: string; cityArea: string; companyName: string; country: OrderLineDiscountAdd_orderLineDiscountAdd_order_billingAddress_country; countryArea: string; firstName: string; id: string; lastName: string; phone: string | null; postalCode: string; streetAddress1: string; streetAddress2: string; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_events_relatedOrder { __typename: "Order"; id: string; number: string | null; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_events_user { __typename: "User"; id: string; email: string; firstName: string; lastName: string; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_events_lines_orderLine { __typename: "OrderLine"; id: string; productName: string; variantName: string; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_events_lines { __typename: "OrderEventOrderLineObject"; quantity: number | null; orderLine: OrderLineDiscountAdd_orderLineDiscountAdd_order_events_lines_orderLine | null; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_events { __typename: "OrderEvent"; id: string; amount: number | null; shippingCostsIncluded: boolean | null; date: any | null; email: string | null; emailType: OrderEventsEmailsEnum | null; invoiceNumber: string | null; relatedOrder: OrderLineDiscountAdd_orderLineDiscountAdd_order_events_relatedOrder | null; message: string | null; quantity: number | null; transactionReference: string | null; type: OrderEventsEnum | null; user: OrderLineDiscountAdd_orderLineDiscountAdd_order_events_user | null; lines: (OrderLineDiscountAdd_orderLineDiscountAdd_order_events_lines | null)[] | null; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_fulfillments_lines_orderLine_variant { __typename: "ProductVariant"; id: string; quantityAvailable: number; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_fulfillments_lines_orderLine_unitPrice_gross { __typename: "Money"; amount: number; currency: string; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_fulfillments_lines_orderLine_unitPrice_net { __typename: "Money"; amount: number; currency: string; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_fulfillments_lines_orderLine_unitPrice { __typename: "TaxedMoney"; currency: string; gross: OrderLineDiscountAdd_orderLineDiscountAdd_order_fulfillments_lines_orderLine_unitPrice_gross; net: OrderLineDiscountAdd_orderLineDiscountAdd_order_fulfillments_lines_orderLine_unitPrice_net; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_fulfillments_lines_orderLine_thumbnail { __typename: "Image"; url: string; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_fulfillments_lines_orderLine { __typename: "OrderLine"; id: string; isShippingRequired: boolean; variant: OrderLineDiscountAdd_orderLineDiscountAdd_order_fulfillments_lines_orderLine_variant | null; productName: string; productSku: string; quantity: number; quantityFulfilled: number; unitPrice: OrderLineDiscountAdd_orderLineDiscountAdd_order_fulfillments_lines_orderLine_unitPrice; thumbnail: OrderLineDiscountAdd_orderLineDiscountAdd_order_fulfillments_lines_orderLine_thumbnail | null; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_fulfillments_lines { __typename: "FulfillmentLine"; id: string; quantity: number; orderLine: OrderLineDiscountAdd_orderLineDiscountAdd_order_fulfillments_lines_orderLine | null; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_fulfillments_warehouse { __typename: "Warehouse"; id: string; name: string; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_fulfillments { __typename: "Fulfillment"; id: string; lines: (OrderLineDiscountAdd_orderLineDiscountAdd_order_fulfillments_lines | null)[] | null; fulfillmentOrder: number; status: FulfillmentStatus; trackingNumber: string; warehouse: OrderLineDiscountAdd_orderLineDiscountAdd_order_fulfillments_warehouse | null; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_lines_variant { __typename: "ProductVariant"; id: string; quantityAvailable: number; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_lines_unitPrice_gross { __typename: "Money"; amount: number; currency: string; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_lines_unitPrice_net { __typename: "Money"; amount: number; currency: string; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_lines_unitPrice { __typename: "TaxedMoney"; currency: string; gross: OrderLineDiscountAdd_orderLineDiscountAdd_order_lines_unitPrice_gross; net: OrderLineDiscountAdd_orderLineDiscountAdd_order_lines_unitPrice_net; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_lines_thumbnail { __typename: "Image"; url: string; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_lines { __typename: "OrderLine"; id: string; isShippingRequired: boolean; variant: OrderLineDiscountAdd_orderLineDiscountAdd_order_lines_variant | null; productName: string; productSku: string; quantity: number; quantityFulfilled: number; unitPrice: OrderLineDiscountAdd_orderLineDiscountAdd_order_lines_unitPrice; thumbnail: OrderLineDiscountAdd_orderLineDiscountAdd_order_lines_thumbnail | null; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_shippingAddress_country { __typename: "CountryDisplay"; code: string; country: string; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_shippingAddress { __typename: "Address"; city: string; cityArea: string; companyName: string; country: OrderLineDiscountAdd_orderLineDiscountAdd_order_shippingAddress_country; countryArea: string; firstName: string; id: string; lastName: string; phone: string | null; postalCode: string; streetAddress1: string; streetAddress2: string; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_shippingMethod { __typename: "ShippingMethod"; id: string; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_shippingPrice_gross { __typename: "Money"; amount: number; currency: string; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_shippingPrice { __typename: "TaxedMoney"; gross: OrderLineDiscountAdd_orderLineDiscountAdd_order_shippingPrice_gross; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_subtotal_gross { __typename: "Money"; amount: number; currency: string; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_subtotal { __typename: "TaxedMoney"; gross: OrderLineDiscountAdd_orderLineDiscountAdd_order_subtotal_gross; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_total_gross { __typename: "Money"; amount: number; currency: string; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_total_tax { __typename: "Money"; amount: number; currency: string; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_total { __typename: "TaxedMoney"; gross: OrderLineDiscountAdd_orderLineDiscountAdd_order_total_gross; tax: OrderLineDiscountAdd_orderLineDiscountAdd_order_total_tax; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_totalAuthorized { __typename: "Money"; amount: number; currency: string; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_totalCaptured { __typename: "Money"; amount: number; currency: string; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_user { __typename: "User"; id: string; email: string; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_availableShippingMethods_price { __typename: "Money"; amount: number; currency: string; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_availableShippingMethods { __typename: "ShippingMethod"; id: string; name: string; price: OrderLineDiscountAdd_orderLineDiscountAdd_order_availableShippingMethods_price | null; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_discount { __typename: "Money"; amount: number; currency: string; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_invoices { __typename: "Invoice"; id: string; number: string | null; createdAt: any; url: string | null; status: JobStatusEnum; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order_channel { __typename: "Channel"; isActive: boolean; id: string; name: string; currencyCode: string; } export interface OrderLineDiscountAdd_orderLineDiscountAdd_order { __typename: "Order"; id: string; metadata: (OrderLineDiscountAdd_orderLineDiscountAdd_order_metadata | null)[]; privateMetadata: (OrderLineDiscountAdd_orderLineDiscountAdd_order_privateMetadata | null)[]; billingAddress: OrderLineDiscountAdd_orderLineDiscountAdd_order_billingAddress | null; canFinalize: boolean; created: any; customerNote: string; events: (OrderLineDiscountAdd_orderLineDiscountAdd_order_events | null)[] | null; fulfillments: (OrderLineDiscountAdd_orderLineDiscountAdd_order_fulfillments | null)[]; lines: (OrderLineDiscountAdd_orderLineDiscountAdd_order_lines | null)[]; number: string | null; paymentStatus: PaymentChargeStatusEnum; shippingAddress: OrderLineDiscountAdd_orderLineDiscountAdd_order_shippingAddress | null; shippingMethod: OrderLineDiscountAdd_orderLineDiscountAdd_order_shippingMethod | null; shippingMethodName: string | null; shippingPrice: OrderLineDiscountAdd_orderLineDiscountAdd_order_shippingPrice; status: OrderStatus; subtotal: OrderLineDiscountAdd_orderLineDiscountAdd_order_subtotal; total: OrderLineDiscountAdd_orderLineDiscountAdd_order_total; actions: (OrderAction | null)[]; totalAuthorized: OrderLineDiscountAdd_orderLineDiscountAdd_order_totalAuthorized; totalCaptured: OrderLineDiscountAdd_orderLineDiscountAdd_order_totalCaptured; user: OrderLineDiscountAdd_orderLineDiscountAdd_order_user | null; userEmail: string | null; availableShippingMethods: (OrderLineDiscountAdd_orderLineDiscountAdd_order_availableShippingMethods | null)[] | null; discount: OrderLineDiscountAdd_orderLineDiscountAdd_order_discount | null; invoices: (OrderLineDiscountAdd_orderLineDiscountAdd_order_invoices | null)[] | null; channel: OrderLineDiscountAdd_orderLineDiscountAdd_order_channel; isPaid: boolean; } export interface OrderLineDiscountAdd_orderLineDiscountAdd { __typename: "OrderLineDiscountAdd"; errors: OrderLineDiscountAdd_orderLineDiscountAdd_errors[]; order: OrderLineDiscountAdd_orderLineDiscountAdd_order | null; } export interface OrderLineDiscountAdd { orderLineDiscountAdd: OrderLineDiscountAdd_orderLineDiscountAdd | null; } export interface OrderLineDiscountAddVariables { input: OrderDiscountCommonInput; orderLineId: string; }
the_stack
* @fileoverview Computes the difference between two texts to create a patch. * Applies the patch onto another text, allowing for errors. * @author fraser@google.com (Neil Fraser) */ /** * CHANGES by pedrottimark to diff_match_patch_uncompressed.ts file: * * 1. Delete anything not needed to use diff_cleanupSemantic method * 2. Convert from prototype properties to var declarations * 3. Convert Diff to class from constructor and prototype * 4. Add type annotations for arguments and return values * 5. Add exports */ /** * The data structure representing a diff is an array of tuples: * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']] * which means: delete 'Hello', add 'Goodbye' and keep ' world.' */ var DIFF_DELETE = -1; var DIFF_INSERT = 1; var DIFF_EQUAL = 0; /** * Class representing one diff tuple. * Attempts to look like a two-element array (which is what this used to be). * @param {number} op Operation, one of: DIFF_DELETE, DIFF_INSERT, DIFF_EQUAL. * @param {string} text Text to be deleted, inserted, or retained. * @constructor */ class Diff { 0: number; 1: string; constructor(op: number, text: string) { this[0] = op; this[1] = text; } } /** * Determine the common prefix of two strings. * @param {string} text1 First string. * @param {string} text2 Second string. * @return {number} The number of characters common to the start of each * string. */ var diff_commonPrefix = function(text1: string, text2: string): number { // Quick check for common null cases. if (!text1 || !text2 || text1.charAt(0) != text2.charAt(0)) { return 0; } // Binary search. // Performance analysis: https://neil.fraser.name/news/2007/10/09/ var pointermin = 0; var pointermax = Math.min(text1.length, text2.length); var pointermid = pointermax; var pointerstart = 0; while (pointermin < pointermid) { if (text1.substring(pointerstart, pointermid) == text2.substring(pointerstart, pointermid)) { pointermin = pointermid; pointerstart = pointermin; } else { pointermax = pointermid; } pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); } return pointermid; }; /** * Determine the common suffix of two strings. * @param {string} text1 First string. * @param {string} text2 Second string. * @return {number} The number of characters common to the end of each string. */ var diff_commonSuffix = function(text1: string, text2: string): number { // Quick check for common null cases. if (!text1 || !text2 || text1.charAt(text1.length - 1) != text2.charAt(text2.length - 1)) { return 0; } // Binary search. // Performance analysis: https://neil.fraser.name/news/2007/10/09/ var pointermin = 0; var pointermax = Math.min(text1.length, text2.length); var pointermid = pointermax; var pointerend = 0; while (pointermin < pointermid) { if (text1.substring(text1.length - pointermid, text1.length - pointerend) == text2.substring(text2.length - pointermid, text2.length - pointerend)) { pointermin = pointermid; pointerend = pointermin; } else { pointermax = pointermid; } pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); } return pointermid; }; /** * Determine if the suffix of one string is the prefix of another. * @param {string} text1 First string. * @param {string} text2 Second string. * @return {number} The number of characters common to the end of the first * string and the start of the second string. * @private */ var diff_commonOverlap_ = function(text1: string, text2: string): number { // Cache the text lengths to prevent multiple calls. var text1_length = text1.length; var text2_length = text2.length; // Eliminate the null case. if (text1_length == 0 || text2_length == 0) { return 0; } // Truncate the longer string. if (text1_length > text2_length) { text1 = text1.substring(text1_length - text2_length); } else if (text1_length < text2_length) { text2 = text2.substring(0, text1_length); } var text_length = Math.min(text1_length, text2_length); // Quick check for the worst case. if (text1 == text2) { return text_length; } // Start by looking for a single character match // and increase length until no match is found. // Performance analysis: https://neil.fraser.name/news/2010/11/04/ var best = 0; var length = 1; while (true) { var pattern = text1.substring(text_length - length); var found = text2.indexOf(pattern); if (found == -1) { return best; } length += found; if (found == 0 || text1.substring(text_length - length) == text2.substring(0, length)) { best = length; length++; } } }; /** * Reduce the number of edits by eliminating semantically trivial equalities. * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples. */ var diff_cleanupSemantic = function(diffs: Array<Diff>) { var changes = false; var equalities = []; // Stack of indices where equalities are found. var equalitiesLength = 0; // Keeping our own length var is faster in JS. /** @type {?string} */ var lastEquality = null; // Always equal to diffs[equalities[equalitiesLength - 1]][1] var pointer = 0; // Index of current position. // Number of characters that changed prior to the equality. var length_insertions1 = 0; var length_deletions1 = 0; // Number of characters that changed after the equality. var length_insertions2 = 0; var length_deletions2 = 0; while (pointer < diffs.length) { if (diffs[pointer][0] == DIFF_EQUAL) { // Equality found. equalities[equalitiesLength++] = pointer; length_insertions1 = length_insertions2; length_deletions1 = length_deletions2; length_insertions2 = 0; length_deletions2 = 0; lastEquality = diffs[pointer][1]; } else { // An insertion or deletion. if (diffs[pointer][0] == DIFF_INSERT) { length_insertions2 += diffs[pointer][1].length; } else { length_deletions2 += diffs[pointer][1].length; } // Eliminate an equality that is smaller or equal to the edits on both // sides of it. if (lastEquality && (lastEquality.length <= Math.max(length_insertions1, length_deletions1)) && (lastEquality.length <= Math.max(length_insertions2, length_deletions2))) { // Duplicate record. diffs.splice(equalities[equalitiesLength - 1], 0, new Diff(DIFF_DELETE, lastEquality)); // Change second copy to insert. diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT; // Throw away the equality we just deleted. equalitiesLength--; // Throw away the previous equality (it needs to be reevaluated). equalitiesLength--; pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1; length_insertions1 = 0; // Reset the counters. length_deletions1 = 0; length_insertions2 = 0; length_deletions2 = 0; lastEquality = null; changes = true; } } pointer++; } // Normalize the diff. if (changes) { diff_cleanupMerge(diffs); } diff_cleanupSemanticLossless(diffs); // Find any overlaps between deletions and insertions. // e.g: <del>abcxxx</del><ins>xxxdef</ins> // -> <del>abc</del>xxx<ins>def</ins> // e.g: <del>xxxabc</del><ins>defxxx</ins> // -> <ins>def</ins>xxx<del>abc</del> // Only extract an overlap if it is as big as the edit ahead or behind it. pointer = 1; while (pointer < diffs.length) { if (diffs[pointer - 1][0] == DIFF_DELETE && diffs[pointer][0] == DIFF_INSERT) { var deletion = diffs[pointer - 1][1]; var insertion = diffs[pointer][1]; var overlap_length1 = diff_commonOverlap_(deletion, insertion); var overlap_length2 = diff_commonOverlap_(insertion, deletion); if (overlap_length1 >= overlap_length2) { if (overlap_length1 >= deletion.length / 2 || overlap_length1 >= insertion.length / 2) { // Overlap found. Insert an equality and trim the surrounding edits. diffs.splice(pointer, 0, new Diff(DIFF_EQUAL, insertion.substring(0, overlap_length1))); diffs[pointer - 1][1] = deletion.substring(0, deletion.length - overlap_length1); diffs[pointer + 1][1] = insertion.substring(overlap_length1); pointer++; } } else { if (overlap_length2 >= deletion.length / 2 || overlap_length2 >= insertion.length / 2) { // Reverse overlap found. // Insert an equality and swap and trim the surrounding edits. diffs.splice(pointer, 0, new Diff(DIFF_EQUAL, deletion.substring(0, overlap_length2))); diffs[pointer - 1][0] = DIFF_INSERT; diffs[pointer - 1][1] = insertion.substring(0, insertion.length - overlap_length2); diffs[pointer + 1][0] = DIFF_DELETE; diffs[pointer + 1][1] = deletion.substring(overlap_length2); pointer++; } } pointer++; } pointer++; } }; /** * Look for single edits surrounded on both sides by equalities * which can be shifted sideways to align the edit to a word boundary. * e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came. * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples. */ var diff_cleanupSemanticLossless = function(diffs: Array<Diff>) { /** * Given two strings, compute a score representing whether the internal * boundary falls on logical boundaries. * Scores range from 6 (best) to 0 (worst). * Closure, but does not reference any external variables. * @param {string} one First string. * @param {string} two Second string. * @return {number} The score. * @private */ function diff_cleanupSemanticScore_(one: string, two: string): number { if (!one || !two) { // Edges are the best. return 6; } // Each port of this function behaves slightly differently due to // subtle differences in each language's definition of things like // 'whitespace'. Since this function's purpose is largely cosmetic, // the choice has been made to use each language's native features // rather than force total conformity. var char1 = one.charAt(one.length - 1); var char2 = two.charAt(0); var nonAlphaNumeric1 = char1.match(nonAlphaNumericRegex_); var nonAlphaNumeric2 = char2.match(nonAlphaNumericRegex_); var whitespace1 = nonAlphaNumeric1 && char1.match(whitespaceRegex_); var whitespace2 = nonAlphaNumeric2 && char2.match(whitespaceRegex_); var lineBreak1 = whitespace1 && char1.match(linebreakRegex_); var lineBreak2 = whitespace2 && char2.match(linebreakRegex_); var blankLine1 = lineBreak1 && one.match(blanklineEndRegex_); var blankLine2 = lineBreak2 && two.match(blanklineStartRegex_); if (blankLine1 || blankLine2) { // Five points for blank lines. return 5; } else if (lineBreak1 || lineBreak2) { // Four points for line breaks. return 4; } else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) { // Three points for end of sentences. return 3; } else if (whitespace1 || whitespace2) { // Two points for whitespace. return 2; } else if (nonAlphaNumeric1 || nonAlphaNumeric2) { // One point for non-alphanumeric. return 1; } return 0; } var pointer = 1; // Intentionally ignore the first and last element (don't need checking). while (pointer < diffs.length - 1) { if (diffs[pointer - 1][0] == DIFF_EQUAL && diffs[pointer + 1][0] == DIFF_EQUAL) { // This is a single edit surrounded by equalities. var equality1 = diffs[pointer - 1][1]; var edit = diffs[pointer][1]; var equality2 = diffs[pointer + 1][1]; // First, shift the edit as far left as possible. var commonOffset = diff_commonSuffix(equality1, edit); if (commonOffset) { var commonString = edit.substring(edit.length - commonOffset); equality1 = equality1.substring(0, equality1.length - commonOffset); edit = commonString + edit.substring(0, edit.length - commonOffset); equality2 = commonString + equality2; } // Second, step character by character right, looking for the best fit. var bestEquality1 = equality1; var bestEdit = edit; var bestEquality2 = equality2; var bestScore = diff_cleanupSemanticScore_(equality1, edit) + diff_cleanupSemanticScore_(edit, equality2); while (edit.charAt(0) === equality2.charAt(0)) { equality1 += edit.charAt(0); edit = edit.substring(1) + equality2.charAt(0); equality2 = equality2.substring(1); var score = diff_cleanupSemanticScore_(equality1, edit) + diff_cleanupSemanticScore_(edit, equality2); // The >= encourages trailing rather than leading whitespace on edits. if (score >= bestScore) { bestScore = score; bestEquality1 = equality1; bestEdit = edit; bestEquality2 = equality2; } } if (diffs[pointer - 1][1] != bestEquality1) { // We have an improvement, save it back to the diff. if (bestEquality1) { diffs[pointer - 1][1] = bestEquality1; } else { diffs.splice(pointer - 1, 1); pointer--; } diffs[pointer][1] = bestEdit; if (bestEquality2) { diffs[pointer + 1][1] = bestEquality2; } else { diffs.splice(pointer + 1, 1); pointer--; } } } pointer++; } }; // Define some regex patterns for matching boundaries. var nonAlphaNumericRegex_ = /[^a-zA-Z0-9]/; var whitespaceRegex_ = /\s/; var linebreakRegex_ = /[\r\n]/; var blanklineEndRegex_ = /\n\r?\n$/; var blanklineStartRegex_ = /^\r?\n\r?\n/; /** * Reorder and merge like edit sections. Merge equalities. * Any edit section can move as long as it doesn't cross an equality. * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples. */ var diff_cleanupMerge = function(diffs: Array<Diff>) { // Add a dummy entry at the end. diffs.push(new Diff(DIFF_EQUAL, '')); var pointer = 0; var count_delete = 0; var count_insert = 0; var text_delete = ''; var text_insert = ''; var commonlength; while (pointer < diffs.length) { switch (diffs[pointer][0]) { case DIFF_INSERT: count_insert++; text_insert += diffs[pointer][1]; pointer++; break; case DIFF_DELETE: count_delete++; text_delete += diffs[pointer][1]; pointer++; break; case DIFF_EQUAL: // Upon reaching an equality, check for prior redundancies. if (count_delete + count_insert > 1) { if (count_delete !== 0 && count_insert !== 0) { // Factor out any common prefixies. commonlength = diff_commonPrefix(text_insert, text_delete); if (commonlength !== 0) { if ((pointer - count_delete - count_insert) > 0 && diffs[pointer - count_delete - count_insert - 1][0] == DIFF_EQUAL) { diffs[pointer - count_delete - count_insert - 1][1] += text_insert.substring(0, commonlength); } else { diffs.splice(0, 0, new Diff(DIFF_EQUAL, text_insert.substring(0, commonlength))); pointer++; } text_insert = text_insert.substring(commonlength); text_delete = text_delete.substring(commonlength); } // Factor out any common suffixies. commonlength = diff_commonSuffix(text_insert, text_delete); if (commonlength !== 0) { diffs[pointer][1] = text_insert.substring(text_insert.length - commonlength) + diffs[pointer][1]; text_insert = text_insert.substring(0, text_insert.length - commonlength); text_delete = text_delete.substring(0, text_delete.length - commonlength); } } // Delete the offending records and add the merged ones. pointer -= count_delete + count_insert; diffs.splice(pointer, count_delete + count_insert); if (text_delete.length) { diffs.splice(pointer, 0, new Diff(DIFF_DELETE, text_delete)); pointer++; } if (text_insert.length) { diffs.splice(pointer, 0, new Diff(DIFF_INSERT, text_insert)); pointer++; } pointer++; } else if (pointer !== 0 && diffs[pointer - 1][0] == DIFF_EQUAL) { // Merge this equality with the previous one. diffs[pointer - 1][1] += diffs[pointer][1]; diffs.splice(pointer, 1); } else { pointer++; } count_insert = 0; count_delete = 0; text_delete = ''; text_insert = ''; break; } } if (diffs[diffs.length - 1][1] === '') { diffs.pop(); // Remove the dummy entry at the end. } // Second pass: look for single edits surrounded on both sides by equalities // which can be shifted sideways to eliminate an equality. // e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC var changes = false; pointer = 1; // Intentionally ignore the first and last element (don't need checking). while (pointer < diffs.length - 1) { if (diffs[pointer - 1][0] == DIFF_EQUAL && diffs[pointer + 1][0] == DIFF_EQUAL) { // This is a single edit surrounded by equalities. if (diffs[pointer][1].substring(diffs[pointer][1].length - diffs[pointer - 1][1].length) == diffs[pointer - 1][1]) { // Shift the edit over the previous equality. diffs[pointer][1] = diffs[pointer - 1][1] + diffs[pointer][1].substring(0, diffs[pointer][1].length - diffs[pointer - 1][1].length); diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1]; diffs.splice(pointer - 1, 1); changes = true; } else if (diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) == diffs[pointer + 1][1]) { // Shift the edit over the next equality. diffs[pointer - 1][1] += diffs[pointer + 1][1]; diffs[pointer][1] = diffs[pointer][1].substring(diffs[pointer + 1][1].length) + diffs[pointer + 1][1]; diffs.splice(pointer + 1, 1); changes = true; } } pointer++; } // If shifts were made, the diff needs reordering and another shift sweep. if (changes) { diff_cleanupMerge(diffs); } }; export { Diff, DIFF_EQUAL, DIFF_DELETE, DIFF_INSERT, diff_cleanupSemantic as cleanupSemantic, };
the_stack
import { expect } from 'chai'; import { firstValueFrom, of as observableOf, of } from 'rxjs'; import { catchError, map } from 'rxjs/operators'; import { NetworkConfigurationDTO, NodeRoutesApi } from 'symbol-openapi-typescript-fetch-client'; import { instance, mock, when } from 'ts-mockito'; import { AccountHttp, BlockHttp, ChainHttp, FinalizationHttp, HashLockHttp, Listener, MetadataHttp, MosaicHttp, MultisigHttp, NamespaceHttp, NamespaceRepository, NetworkHttp, NetworkRepository, NodeHttp, NodeRepository, ReceiptHttp, RepositoryFactoryHttp, RestrictionAccountHttp, RestrictionMosaicHttp, SecretLockHttp, TransactionGroup, TransactionHttp, TransactionStatusHttp, } from '../../src/infrastructure'; import { NetworkCurrencies } from '../../src/model/mosaic'; import { NodeInfo } from '../../src/model/node'; import { TestNetworkType } from '../conf/conf.spec'; describe('RepositoryFactory', () => { it('Should create repositories', () => { const repositoryFactory = new RepositoryFactoryHttp('http://localhost:3000', { networkType: TestNetworkType, generationHash: 'testHash', }); expect(repositoryFactory.createBlockRepository()).to.be.not.null; expect(repositoryFactory.createNetworkRepository()).to.be.not.null; expect(repositoryFactory.createNamespaceRepository()).to.be.not.null; expect(repositoryFactory.createAccountRepository()).to.be.not.null; expect(repositoryFactory.createChainRepository()).to.be.not.null; expect(repositoryFactory.createMetadataRepository()).to.be.not.null; expect(repositoryFactory.createMosaicRepository()).to.be.not.null; expect(repositoryFactory.createMultisigRepository()).to.be.not.null; expect(repositoryFactory.createNodeRepository()).to.be.not.null; expect(repositoryFactory.createReceiptRepository()).to.be.not.null; expect(repositoryFactory.createRestrictionAccountRepository()).to.be.not.null; expect(repositoryFactory.createRestrictionMosaicRepository()).to.be.not.null; expect(repositoryFactory.createTransactionRepository()).to.be.not.null; expect(repositoryFactory.createHashLockRepository()).to.be.not.null; expect(repositoryFactory.createSecretLockRepository()).to.be.not.null; expect(repositoryFactory.createFinalizationRepository()).to.be.not.null; }); it('Raise error without unhandled-rejections', async () => { const nodeRoutesApi: NodeRoutesApi = mock(); const fetchResponseMock: Partial<Response> = { status: 666, statusText: 'Some status text error', text: () => Promise.resolve('This is the body'), }; when(nodeRoutesApi.getNodeHealth()).thenReturn(Promise.reject(fetchResponseMock)); const url = 'https://invalid'; const repositoryFactory = new RepositoryFactoryHttp(url); try { const nodeRepository = repositoryFactory.createNodeRepository(); (nodeRepository as any).nodeRoutesApi = instance(nodeRoutesApi); await firstValueFrom(nodeRepository.getNodeHealth()); expect(true).to.be.false; } catch (e) { expect(e.message).eq('{"statusCode":666,"statusMessage":"Some status text error","body":"This is the body"}'); } }); it('Should get GenerationHash from cache', (done) => { let counter = 0; const repositoryMock: NodeRepository = mock(); const observableOfNodeInfo = observableOf({ networkGenerationHashSeed: 'aaaa' } as NodeInfo).pipe( map((v) => { counter++; return v; }), ); when(repositoryMock.getNodeInfo()).thenReturn(observableOfNodeInfo); expect(observableOfNodeInfo).to.be.equals(observableOfNodeInfo); const repositoryFactory = new (class RepositoryFactoryHttpForTest extends RepositoryFactoryHttp { createNodeRepository(): NodeRepository { return instance(repositoryMock); } })('http://localhost:3000', { networkType: TestNetworkType, }); expect(counter).to.be.equals(0); repositoryFactory.getGenerationHash().subscribe((gh) => { expect(counter).to.be.equals(1); expect(gh).to.be.equals('aaaa'); repositoryFactory.getGenerationHash().subscribe((g) => { expect(counter).to.be.equals(1); expect(g).to.be.equals('aaaa'); repositoryFactory.getGenerationHash().subscribe((h) => { expect(counter).to.be.equals(1); expect(h).to.be.equals('aaaa'); done(); }); }); }); }); it('Should get nodePubicKey from cache', (done) => { let counter = 0; const repositoryMock: NodeRepository = mock(); const observableOfNodeInfo = observableOf({ nodePublicKey: 'aaaa' } as NodeInfo).pipe( map((v) => { counter++; return v; }), ); when(repositoryMock.getNodeInfo()).thenReturn(observableOfNodeInfo); expect(observableOfNodeInfo).to.be.equals(observableOfNodeInfo); const repositoryFactory = new (class RepositoryFactoryHttpForTest extends RepositoryFactoryHttp { createNodeRepository(): NodeRepository { return instance(repositoryMock); } })('http://localhost:3000', { networkType: TestNetworkType, }); expect(counter).to.be.equals(0); repositoryFactory.getNodePublicKey().subscribe((gh) => { expect(counter).to.be.equals(1); expect(gh).to.be.equals('aaaa'); repositoryFactory.getNodePublicKey().subscribe((g) => { expect(counter).to.be.equals(1); expect(g).to.be.equals('aaaa'); repositoryFactory.getNodePublicKey().subscribe((h) => { expect(counter).to.be.equals(1); expect(h).to.be.equals('aaaa'); done(); }); }); }); }); it('Should get NetworkType from cache', (done) => { let counter = 0; const repositoryMock: NetworkRepository = mock(); const expectedNetworkType = TestNetworkType; const observableOfBlockInfo = observableOf(expectedNetworkType).pipe( map((v) => { counter++; return v; }), ); when(repositoryMock.getNetworkType()).thenReturn(observableOfBlockInfo); expect(observableOfBlockInfo).to.be.equals(observableOfBlockInfo); const repositoryFactory = new (class RepositoryFactoryHttpForTest extends RepositoryFactoryHttp { createNetworkRepository(): NetworkRepository { return instance(repositoryMock); } })('http://localhost:3000', { generationHash: 'testHash', epochAdjustment: 1573430400, }); expect(counter).to.be.equals(0); repositoryFactory.getNetworkType().subscribe((networkType) => { expect(counter).to.be.equals(1); expect(networkType).to.be.equals(expectedNetworkType); repositoryFactory.getNetworkType().subscribe((network) => { expect(counter).to.be.equals(1); expect(network).to.be.equals(expectedNetworkType); done(); }); }); }); it('Should get epochAdjustment from cache', (done) => { let counter = 0; const repositoryMock: NetworkRepository = mock(); const expectedepochAdjustment = 1573430400; const body: NetworkConfigurationDTO = { network: { identifier: 'public-test', nemesisSignerPublicKey: 'E3F04CA92250B49679EBEF98FAC87C1CECAC7E7491ECBB2307DF1AD65BED57FD', generationHashSeed: 'AE6488282F9C09457F017BE5EE26387B21EB15CF32D6DA1E9846C25E00828329', epochAdjustment: '1573430400s', }, chain: {}, plugins: {}, }; const observableOfNetworkProperties = observableOf(body).pipe( map((v) => { counter++; return v; }), ); when(repositoryMock.getNetworkProperties()).thenReturn(observableOfNetworkProperties); expect(observableOfNetworkProperties).to.be.equals(observableOfNetworkProperties); const repositoryFactory = new (class RepositoryFactoryHttpForTest extends RepositoryFactoryHttp { createNetworkRepository(): NetworkRepository { return instance(repositoryMock); } })('http://localhost:3000', { generationHash: 'testHash', networkType: 152, }); expect(counter).to.be.equals(0); repositoryFactory.getEpochAdjustment().subscribe((epoch) => { expect(counter).to.be.equals(1); expect(epoch).to.be.equals(expectedepochAdjustment); repositoryFactory.getEpochAdjustment().subscribe((network) => { expect(counter).to.be.equals(1); expect(network).to.be.equals(expectedepochAdjustment); done(); }); }); }); it('Should get NetworkType from memory', (done) => { let counter = 0; const repositoryMock: NetworkRepository = mock(); const expectedNetworkType = TestNetworkType; const observableOfBlockInfo = observableOf(expectedNetworkType).pipe( map((v) => { counter++; return v; }), ); when(repositoryMock.getNetworkType()).thenReturn(observableOfBlockInfo); expect(observableOfBlockInfo).to.be.equals(observableOfBlockInfo); const repositoryFactory = new (class RepositoryFactoryHttpForTest extends RepositoryFactoryHttp { createNetworkRepository(): NetworkRepository { return instance(repositoryMock); } })('http://localhost:3000', { networkType: expectedNetworkType, generationHash: 'testHash', epochAdjustment: 1573430400, }); expect(counter).to.be.equals(0); repositoryFactory.getNetworkType().subscribe((networkType) => { expect(counter).to.be.equals(0); expect(networkType).to.be.equals(expectedNetworkType); repositoryFactory.getNetworkType().subscribe((network) => { expect(counter).to.be.equals(0); expect(network).to.be.equals(expectedNetworkType); done(); }); }); }); it('Should get epochAdjustment from memory', (done) => { let counter = 0; const repositoryMock: NetworkRepository = mock(); const expectedepochAdjustment = 1573430400; const body: NetworkConfigurationDTO = { network: { identifier: 'public-test', nemesisSignerPublicKey: 'E3F04CA92250B49679EBEF98FAC87C1CECAC7E7491ECBB2307DF1AD65BED57FD', generationHashSeed: 'AE6488282F9C09457F017BE5EE26387B21EB15CF32D6DA1E9846C25E00828329', epochAdjustment: '1573430400s', }, chain: {}, plugins: {}, }; const observableOfNetworkProperties = observableOf(body).pipe( map((v) => { counter++; return v; }), ); when(repositoryMock.getNetworkProperties()).thenReturn(observableOfNetworkProperties); expect(observableOfNetworkProperties).to.be.equals(observableOfNetworkProperties); const repositoryFactory = new (class RepositoryFactoryHttpForTest extends RepositoryFactoryHttp { createNetworkRepository(): NetworkRepository { return instance(repositoryMock); } })('http://localhost:3000', { networkType: 152, generationHash: 'testHash', epochAdjustment: 1573430400, }); expect(counter).to.be.equals(0); repositoryFactory.getEpochAdjustment().subscribe((networkType) => { expect(counter).to.be.equals(0); expect(networkType).to.be.equals(expectedepochAdjustment); repositoryFactory.getEpochAdjustment().subscribe((network) => { expect(counter).to.be.equals(0); expect(network).to.be.equals(expectedepochAdjustment); done(); }); }); }); it('Should create listener object using injected ws', () => { class WebSocketMock { constructor(public readonly url: string) {} send(payload: string): void { throw new Error(payload); } } const namespaceRepository: NamespaceRepository = mock(); let repositoryFactory = new (class RepositoryFactoryHttpForTest extends RepositoryFactoryHttp { createNamespaceRepository(): NamespaceRepository { return instance(namespaceRepository); } })('http://localhost:3000', { networkType: TestNetworkType, generationHash: 'testHash', websocketInjected: WebSocketMock, }); let listener = repositoryFactory.createListener(); expect(listener.url).to.be.equal('http://localhost:3000/ws'); repositoryFactory = new (class RepositoryFactoryHttpForTest extends RepositoryFactoryHttp { createNamespaceRepository(): NamespaceRepository { return instance(namespaceRepository); } })('http://localhost:3000', { networkType: TestNetworkType, generationHash: 'testHash', websocketUrl: 'ws://localhost:3000/ws', websocketInjected: WebSocketMock, }); listener = repositoryFactory.createListener(); expect(listener.url).to.be.equal('ws://localhost:3000/ws'); }); it('Should create listener object using injected ws', () => { const factory = new RepositoryFactoryHttp('url', { networkType: TestNetworkType, generationHash: 'testHash', }); expect(factory.createAccountRepository() instanceof AccountHttp).to.be.true; expect(factory.createBlockRepository() instanceof BlockHttp).to.be.true; expect(factory.createChainRepository() instanceof ChainHttp).to.be.true; expect(factory.createListener() instanceof Listener).to.be.true; expect(factory.createMetadataRepository() instanceof MetadataHttp).to.be.true; expect(factory.createMosaicRepository() instanceof MosaicHttp).to.be.true; expect(factory.createMultisigRepository() instanceof MultisigHttp).to.be.true; expect(factory.createNamespaceRepository() instanceof NamespaceHttp).to.be.true; expect(factory.createNetworkRepository() instanceof NetworkHttp).to.be.true; expect(factory.createNodeRepository() instanceof NodeHttp).to.be.true; expect(factory.createReceiptRepository() instanceof ReceiptHttp).to.be.true; expect(factory.createRestrictionAccountRepository() instanceof RestrictionAccountHttp).to.be.true; expect(factory.createRestrictionMosaicRepository() instanceof RestrictionMosaicHttp).to.be.true; expect(factory.createTransactionRepository() instanceof TransactionHttp).to.be.true; expect(factory.createTransactionStatusRepository() instanceof TransactionStatusHttp).to.be.true; expect(factory.createHashLockRepository() instanceof HashLockHttp).to.be.true; expect(factory.createSecretLockRepository() instanceof SecretLockHttp).to.be.true; expect(factory.createFinalizationRepository() instanceof FinalizationHttp).to.be.true; }); it('Fail remote call ', async () => { const factory = new RepositoryFactoryHttp('http://localhost:2000'); try { await firstValueFrom(factory.getGenerationHash()); expect(true).eq(false); } catch (e) { expect(e.message).contains('request to http://localhost:2000'); } }); it('Fail remote call invalid transaction', async () => { const factory = new RepositoryFactoryHttp('http://localhost:3000'); try { await firstValueFrom(factory.createTransactionRepository().getTransaction('abc', TransactionGroup.Confirmed)); expect(true).eq(false); } catch (e) { if (await firstValueFrom(factory.getGenerationHash().pipe(catchError(() => of(false))))) { expect(e.message).contains('"statusCode":500,"statusMessage":"Internal Server Error"'); } else { expect(e.message).contains('request to http://localhost:3000'); } } }); it('Fail remote getCurrencies ', async () => { const factory = new RepositoryFactoryHttp('http://localhost:2000'); try { await firstValueFrom(factory.getCurrencies()); expect(true).eq(false); } catch (e) { expect(e.message).contains('request to http://localhost:2000'); } }); it('getCurrencies', async () => { const factory = new RepositoryFactoryHttp('http://localhost:2000', { networkCurrencies: NetworkCurrencies.PUBLIC }); const networkCurrencies = await firstValueFrom(factory.getCurrencies()); expect(networkCurrencies).eq(NetworkCurrencies.PUBLIC); }); });
the_stack
import * as os from 'os'; import * as path from 'path'; import { testDeprecated } from '@aws-cdk/cdk-build-tools'; import { FileAssetPackaging } from '@aws-cdk/cloud-assembly-schema'; import * as cxapi from '@aws-cdk/cx-api'; import * as fs from 'fs-extra'; import * as sinon from 'sinon'; import { App, AssetHashType, AssetStaging, DockerImage, BundlingOptions, BundlingOutput, FileSystem, Stack, Stage } from '../lib'; const STUB_INPUT_FILE = '/tmp/docker-stub.input'; const STUB_INPUT_CONCAT_FILE = '/tmp/docker-stub.input.concat'; enum DockerStubCommand { SUCCESS = 'DOCKER_STUB_SUCCESS', FAIL = 'DOCKER_STUB_FAIL', SUCCESS_NO_OUTPUT = 'DOCKER_STUB_SUCCESS_NO_OUTPUT', MULTIPLE_FILES = 'DOCKER_STUB_MULTIPLE_FILES', SINGLE_ARCHIVE = 'DOCKER_STUB_SINGLE_ARCHIVE', } const FIXTURE_TEST1_DIR = path.join(__dirname, 'fs', 'fixtures', 'test1'); const FIXTURE_TEST1_HASH = '2f37f937c51e2c191af66acf9b09f548926008ec68c575bd2ee54b6e997c0e00'; const FIXTURE_TARBALL = path.join(__dirname, 'fs', 'fixtures.tar.gz'); const userInfo = os.userInfo(); const USER_ARG = `-u ${userInfo.uid}:${userInfo.gid}`; // this is a way to provide a custom "docker" command for staging. process.env.CDK_DOCKER = `${__dirname}/docker-stub.sh`; describe('staging', () => { afterEach(() => { AssetStaging.clearAssetHashCache(); if (fs.existsSync(STUB_INPUT_FILE)) { fs.unlinkSync(STUB_INPUT_FILE); } if (fs.existsSync(STUB_INPUT_CONCAT_FILE)) { fs.unlinkSync(STUB_INPUT_CONCAT_FILE); } sinon.restore(); }); test('base case', () => { // GIVEN const stack = new Stack(); const sourcePath = FIXTURE_TEST1_DIR; // WHEN const staging = new AssetStaging(stack, 's1', { sourcePath }); expect(staging.assetHash).toEqual(FIXTURE_TEST1_HASH); expect(staging.sourcePath).toEqual(sourcePath); expect(path.basename(staging.absoluteStagedPath)).toEqual(`asset.${FIXTURE_TEST1_HASH}`); expect(path.basename(staging.relativeStagedPath(stack))).toEqual(`asset.${FIXTURE_TEST1_HASH}`); expect(staging.packaging).toEqual(FileAssetPackaging.ZIP_DIRECTORY); expect(staging.isArchive).toEqual(true); }); test('base case if source directory is a symlink', () => { // GIVEN const stack = new Stack(); const sourcePath = path.join(os.tmpdir(), 'asset-symlink'); if (fs.existsSync(sourcePath)) { fs.unlinkSync(sourcePath); } fs.symlinkSync(FIXTURE_TEST1_DIR, sourcePath); try { const staging = new AssetStaging(stack, 's1', { sourcePath }); // Should be the same asset hash as in the previous test expect(staging.assetHash).toEqual(FIXTURE_TEST1_HASH); } finally { if (fs.existsSync(sourcePath)) { fs.unlinkSync(sourcePath); } } }); test('staging of an archive file correctly sets packaging and isArchive', () => { // GIVEN const stack = new Stack(); const sourcePath = path.join(__dirname, 'archive', 'archive.zip'); // WHEN const staging = new AssetStaging(stack, 's1', { sourcePath }); expect(staging.packaging).toEqual(FileAssetPackaging.FILE); expect(staging.isArchive).toEqual(true); }); test('asset packaging type is correct when staging is skipped because of memory cache', () => { // GIVEN const stack = new Stack(); const sourcePath = path.join(__dirname, 'archive', 'archive.zip'); // WHEN const staging1 = new AssetStaging(stack, 's1', { sourcePath }); const staging2 = new AssetStaging(stack, 's2', { sourcePath }); expect(staging1.packaging).toEqual(FileAssetPackaging.FILE); expect(staging1.isArchive).toEqual(true); expect(staging2.packaging).toEqual(staging1.packaging); expect(staging2.isArchive).toEqual(staging1.isArchive); }); test('asset packaging type is correct when staging is skipped because of disk cache', () => { // GIVEN const TEST_OUTDIR = path.join(__dirname, 'cdk.out'); if (fs.existsSync(TEST_OUTDIR)) { fs.removeSync(TEST_OUTDIR); } const sourcePath = path.join(__dirname, 'archive', 'archive.zip'); const app1 = new App({ outdir: TEST_OUTDIR }); const stack1 = new Stack(app1, 'Stack'); const app2 = new App({ outdir: TEST_OUTDIR }); // same OUTDIR const stack2 = new Stack(app2, 'stack'); // WHEN const staging1 = new AssetStaging(stack1, 'Asset', { sourcePath }); // Now clear asset hash cache to show that during the second staging // even though the asset is already available on disk it will correctly // be considered as a FileAssetPackaging.FILE. AssetStaging.clearAssetHashCache(); const staging2 = new AssetStaging(stack2, 'Asset', { sourcePath }); // THEN expect(staging1.packaging).toEqual(FileAssetPackaging.FILE); expect(staging1.isArchive).toEqual(true); expect(staging2.packaging).toEqual(staging1.packaging); expect(staging2.isArchive).toEqual(staging1.isArchive); }); test('staging of a non-archive file correctly sets packaging and isArchive', () => { // GIVEN const stack = new Stack(); const sourcePath = __filename; // WHEN const staging = new AssetStaging(stack, 's1', { sourcePath }); expect(staging.packaging).toEqual(FileAssetPackaging.FILE); expect(staging.isArchive).toEqual(false); }); test('staging can be disabled through context', () => { // GIVEN const stack = new Stack(); stack.node.setContext(cxapi.DISABLE_ASSET_STAGING_CONTEXT, true); const sourcePath = path.join(__dirname, 'fs', 'fixtures', 'test1'); // WHEN const staging = new AssetStaging(stack, 's1', { sourcePath }); expect(staging.assetHash).toEqual(FIXTURE_TEST1_HASH); expect(staging.sourcePath).toEqual(sourcePath); expect(staging.absoluteStagedPath).toEqual(sourcePath); expect(staging.relativeStagedPath(stack)).toEqual(sourcePath); }); test('files are copied to the output directory during synth', () => { // GIVEN const app = new App({ context: { [cxapi.NEW_STYLE_STACK_SYNTHESIS_CONTEXT]: false } }); const stack = new Stack(app, 'stack'); // WHEN new AssetStaging(stack, 's1', { sourcePath: FIXTURE_TEST1_DIR }); new AssetStaging(stack, 'file', { sourcePath: FIXTURE_TARBALL }); // THEN const assembly = app.synth(); expect(fs.readdirSync(assembly.directory)).toEqual([ `asset.${FIXTURE_TEST1_HASH}`, 'asset.af10ac04b3b607b0f8659c8f0cee8c343025ee75baf0b146f10f0e5311d2c46b.gz', 'cdk.out', 'manifest.json', 'stack.template.json', 'tree.json', ]); }); test('assets in nested assemblies get staged into assembly root directory', () => { // GIVEN const app = new App(); const stack1 = new Stack(new Stage(app, 'Stage1'), 'Stack'); const stack2 = new Stack(new Stage(app, 'Stage2'), 'Stack'); // WHEN new AssetStaging(stack1, 's1', { sourcePath: FIXTURE_TEST1_DIR }); new AssetStaging(stack2, 's1', { sourcePath: FIXTURE_TEST1_DIR }); // THEN const assembly = app.synth(); // One asset directory at the top expect(fs.readdirSync(assembly.directory)).toEqual([ 'assembly-Stage1', 'assembly-Stage2', `asset.${FIXTURE_TEST1_HASH}`, 'cdk.out', 'manifest.json', 'tree.json', ]); }); test('allow specifying extra data to include in the source hash', () => { // GIVEN const app = new App(); const stack = new Stack(app, 'stack'); const directory = path.join(__dirname, 'fs', 'fixtures', 'test1'); // WHEN const withoutExtra = new AssetStaging(stack, 'withoutExtra', { sourcePath: directory }); const withExtra = new AssetStaging(stack, 'withExtra', { sourcePath: directory, extraHash: 'boom' }); // THEN expect(withoutExtra.assetHash).not.toEqual(withExtra.assetHash); expect(withoutExtra.assetHash).toEqual(FIXTURE_TEST1_HASH); expect(withExtra.assetHash).toEqual('c95c915a5722bb9019e2c725d11868e5a619b55f36172f76bcbcaa8bb2d10c5f'); }); test('with bundling', () => { // GIVEN const app = new App({ context: { [cxapi.NEW_STYLE_STACK_SYNTHESIS_CONTEXT]: false } }); const stack = new Stack(app, 'stack'); const directory = path.join(__dirname, 'fs', 'fixtures', 'test1'); const processStdErrWriteSpy = sinon.spy(process.stderr, 'write'); // WHEN new AssetStaging(stack, 'Asset', { sourcePath: directory, bundling: { image: DockerImage.fromRegistry('alpine'), command: [DockerStubCommand.SUCCESS], }, }); // THEN const assembly = app.synth(); expect( readDockerStubInput()).toEqual( `run --rm ${USER_ARG} -v /input:/asset-input:delegated -v /output:/asset-output:delegated -w /asset-input alpine DOCKER_STUB_SUCCESS`, ); expect(fs.readdirSync(assembly.directory)).toEqual([ 'asset.b1e32e86b3523f2fa512eb99180ee2975a50a4439e63e8badd153f2a68d61aa4', 'cdk.out', 'manifest.json', 'stack.template.json', 'tree.json', ]); // shows a message before bundling expect(processStdErrWriteSpy.calledWith('Bundling asset stack/Asset...\n')).toEqual(true); }); test('bundled resources have absolute path when staging is disabled', () => { // GIVEN const app = new App({ context: { [cxapi.NEW_STYLE_STACK_SYNTHESIS_CONTEXT]: false } }); const stack = new Stack(app, 'stack'); stack.node.setContext(cxapi.DISABLE_ASSET_STAGING_CONTEXT, true); const directory = path.join(__dirname, 'fs', 'fixtures', 'test1'); // WHEN const asset = new AssetStaging(stack, 'Asset', { sourcePath: directory, bundling: { image: DockerImage.fromRegistry('alpine'), command: [DockerStubCommand.SUCCESS], }, }); // THEN const assembly = app.synth(); expect(fs.readdirSync(assembly.directory)).toEqual([ 'asset.b1e32e86b3523f2fa512eb99180ee2975a50a4439e63e8badd153f2a68d61aa4', 'cdk.out', 'manifest.json', 'stack.template.json', 'tree.json', ]); expect(asset.assetHash).toEqual('b1e32e86b3523f2fa512eb99180ee2975a50a4439e63e8badd153f2a68d61aa4'); expect(asset.sourcePath).toEqual(directory); const resolvedStagePath = asset.relativeStagedPath(stack); // absolute path ending with bundling dir expect(path.isAbsolute(resolvedStagePath)).toEqual(true); expect(new RegExp('asset.b1e32e86b3523f2fa512eb99180ee2975a50a4439e63e8badd153f2a68d61aa4$').test(resolvedStagePath)).toEqual(true); }); test('bundler reuses its output when it can', () => { // GIVEN const app = new App({ context: { [cxapi.NEW_STYLE_STACK_SYNTHESIS_CONTEXT]: false } }); const stack = new Stack(app, 'stack'); const directory = path.join(__dirname, 'fs', 'fixtures', 'test1'); // WHEN new AssetStaging(stack, 'Asset', { sourcePath: directory, bundling: { image: DockerImage.fromRegistry('alpine'), command: [DockerStubCommand.SUCCESS], }, }); new AssetStaging(stack, 'AssetDuplicate', { sourcePath: directory, bundling: { image: DockerImage.fromRegistry('alpine'), command: [DockerStubCommand.SUCCESS], }, }); // THEN const assembly = app.synth(); // We're testing that docker was run exactly once even though there are two bundling assets. expect( readDockerStubInputConcat()).toEqual( `run --rm ${USER_ARG} -v /input:/asset-input:delegated -v /output:/asset-output:delegated -w /asset-input alpine DOCKER_STUB_SUCCESS`, ); expect(fs.readdirSync(assembly.directory)).toEqual([ 'asset.b1e32e86b3523f2fa512eb99180ee2975a50a4439e63e8badd153f2a68d61aa4', 'cdk.out', 'manifest.json', 'stack.template.json', 'tree.json', ]); }); test('uses asset hash cache with AssetHashType.OUTPUT', () => { // GIVEN const app = new App({ context: { [cxapi.NEW_STYLE_STACK_SYNTHESIS_CONTEXT]: false } }); const stack = new Stack(app, 'stack'); const directory = path.join(__dirname, 'fs', 'fixtures', 'test1'); const fingerPrintSpy = sinon.spy(FileSystem, 'fingerprint'); // WHEN new AssetStaging(stack, 'Asset', { sourcePath: directory, assetHashType: AssetHashType.OUTPUT, bundling: { image: DockerImage.fromRegistry('alpine'), command: [DockerStubCommand.SUCCESS], }, }); new AssetStaging(stack, 'AssetDuplicate', { sourcePath: directory, assetHashType: AssetHashType.OUTPUT, bundling: { // Same bundling but with keys ordered differently command: [DockerStubCommand.SUCCESS], image: DockerImage.fromRegistry('alpine'), }, }); // THEN const assembly = app.synth(); // We're testing that docker was run exactly once even though there are two bundling assets // and that the hash is based on the output expect( readDockerStubInputConcat()).toEqual( `run --rm ${USER_ARG} -v /input:/asset-input:delegated -v /output:/asset-output:delegated -w /asset-input alpine DOCKER_STUB_SUCCESS`, ); expect(fs.readdirSync(assembly.directory)).toEqual([ 'asset.33cbf2cae5432438e0f046bc45ba8c3cef7b6afcf47b59d1c183775c1918fb1f', 'cdk.out', 'manifest.json', 'stack.template.json', 'tree.json', ]); // Only one fingerprinting expect(fingerPrintSpy.calledOnce).toEqual(true); }); test('bundler considers its options when reusing bundle output', () => { // GIVEN const app = new App({ context: { [cxapi.NEW_STYLE_STACK_SYNTHESIS_CONTEXT]: false } }); const stack = new Stack(app, 'stack'); const directory = path.join(__dirname, 'fs', 'fixtures', 'test1'); // WHEN new AssetStaging(stack, 'Asset', { sourcePath: directory, bundling: { image: DockerImage.fromRegistry('alpine'), command: [DockerStubCommand.SUCCESS], }, }); new AssetStaging(stack, 'AssetWithDifferentBundlingOptions', { sourcePath: directory, bundling: { image: DockerImage.fromRegistry('alpine'), command: [DockerStubCommand.SUCCESS], environment: { UNIQUE_ENV_VAR: 'SOMEVALUE', }, }, }); // THEN const assembly = app.synth(); // We're testing that docker was run twice - once for each set of bundler options // operating on the same source asset. expect( readDockerStubInputConcat()).toEqual( `run --rm ${USER_ARG} -v /input:/asset-input:delegated -v /output:/asset-output:delegated -w /asset-input alpine DOCKER_STUB_SUCCESS\n` + `run --rm ${USER_ARG} -v /input:/asset-input:delegated -v /output:/asset-output:delegated --env UNIQUE_ENV_VAR=SOMEVALUE -w /asset-input alpine DOCKER_STUB_SUCCESS`, ); expect(fs.readdirSync(assembly.directory)).toEqual([ 'asset.b1e32e86b3523f2fa512eb99180ee2975a50a4439e63e8badd153f2a68d61aa4', // 'Asset' 'asset.e80bb8f931b87e84975de193f5a7ecddd7558d3caf3d35d3a536d9ae6539234f', // 'AssetWithDifferentBundlingOptions' 'cdk.out', 'manifest.json', 'stack.template.json', 'tree.json', ]); }); test('bundler outputs to intermediate dir and renames to asset', () => { // GIVEN const app = new App({ context: { [cxapi.NEW_STYLE_STACK_SYNTHESIS_CONTEXT]: false } }); const stack = new Stack(app, 'stack'); const directory = path.join(__dirname, 'fs', 'fixtures', 'test1'); const ensureDirSync = sinon.spy(fs, 'ensureDirSync'); const chmodSyncSpy = sinon.spy(fs, 'chmodSync'); const renameSyncSpy = sinon.spy(fs, 'renameSync'); // WHEN new AssetStaging(stack, 'Asset', { sourcePath: directory, assetHashType: AssetHashType.OUTPUT, bundling: { image: DockerImage.fromRegistry('alpine'), command: [DockerStubCommand.SUCCESS], }, }); // THEN const assembly = app.synth(); expect(ensureDirSync.calledWith(sinon.match(path.join(assembly.directory, 'bundling-temp-')))).toEqual(true); expect(chmodSyncSpy.calledWith(sinon.match(path.join(assembly.directory, 'bundling-temp-')), 0o777)).toEqual(true); expect(renameSyncSpy.calledWith(sinon.match(path.join(assembly.directory, 'bundling-temp-')), sinon.match(path.join(assembly.directory, 'asset.')))).toEqual(true); expect(fs.readdirSync(assembly.directory)).toEqual([ 'asset.33cbf2cae5432438e0f046bc45ba8c3cef7b6afcf47b59d1c183775c1918fb1f', // 'Asset' 'cdk.out', 'manifest.json', 'stack.template.json', 'tree.json', ]); }); test('bundling failure preserves the bundleDir for diagnosability', () => { // GIVEN const app = new App(); const stack = new Stack(app, 'stack'); const directory = path.join(__dirname, 'fs', 'fixtures', 'test1'); // WHEN expect(() => new AssetStaging(stack, 'Asset', { sourcePath: directory, bundling: { image: DockerImage.fromRegistry('alpine'), command: [DockerStubCommand.FAIL], }, })).toThrow(/Failed.*bundl.*asset.*-error/); // THEN const assembly = app.synth(); const dir = fs.readdirSync(assembly.directory); expect(dir.some(entry => entry.match(/asset.*-error/))).toEqual(true); }); test('bundler re-uses assets from previous synths', () => { // GIVEN const TEST_OUTDIR = path.join(__dirname, 'cdk.out'); if (fs.existsSync(TEST_OUTDIR)) { fs.removeSync(TEST_OUTDIR); } const app = new App({ outdir: TEST_OUTDIR, context: { [cxapi.NEW_STYLE_STACK_SYNTHESIS_CONTEXT]: false } }); const stack = new Stack(app, 'stack'); const directory = path.join(__dirname, 'fs', 'fixtures', 'test1'); // WHEN new AssetStaging(stack, 'Asset', { sourcePath: directory, bundling: { image: DockerImage.fromRegistry('alpine'), command: [DockerStubCommand.SUCCESS], }, }); // Clear asset hash cache to show that during the second synth bundling // will consider the existing bundling dir (file system cache). AssetStaging.clearAssetHashCache(); // GIVEN const app2 = new App({ outdir: TEST_OUTDIR, context: { [cxapi.NEW_STYLE_STACK_SYNTHESIS_CONTEXT]: false } }); const stack2 = new Stack(app2, 'stack'); // WHEN new AssetStaging(stack2, 'Asset', { sourcePath: directory, bundling: { image: DockerImage.fromRegistry('alpine'), command: [DockerStubCommand.SUCCESS], }, }); // THEN const appAssembly = app.synth(); const app2Assembly = app2.synth(); expect( readDockerStubInputConcat()).toEqual( `run --rm ${USER_ARG} -v /input:/asset-input:delegated -v /output:/asset-output:delegated -w /asset-input alpine DOCKER_STUB_SUCCESS`, ); expect(appAssembly.directory).toEqual(app2Assembly.directory); expect(fs.readdirSync(appAssembly.directory)).toEqual([ 'asset.b1e32e86b3523f2fa512eb99180ee2975a50a4439e63e8badd153f2a68d61aa4', 'cdk.out', 'manifest.json', 'stack.template.json', 'tree.json', ]); }); test('bundling throws when /asset-ouput is empty', () => { // GIVEN const app = new App(); const stack = new Stack(app, 'stack'); const directory = path.join(__dirname, 'fs', 'fixtures', 'test1'); // THEN expect(() => new AssetStaging(stack, 'Asset', { sourcePath: directory, bundling: { image: DockerImage.fromRegistry('alpine'), command: [DockerStubCommand.SUCCESS_NO_OUTPUT], }, })).toThrow(/Bundling did not produce any output/); expect( readDockerStubInput()).toEqual( `run --rm ${USER_ARG} -v /input:/asset-input:delegated -v /output:/asset-output:delegated -w /asset-input alpine DOCKER_STUB_SUCCESS_NO_OUTPUT`, ); }); testDeprecated('bundling with BUNDLE asset hash type', () => { // GIVEN const app = new App(); const stack = new Stack(app, 'stack'); const directory = path.join(__dirname, 'fs', 'fixtures', 'test1'); // WHEN const asset = new AssetStaging(stack, 'Asset', { sourcePath: directory, bundling: { image: DockerImage.fromRegistry('alpine'), command: [DockerStubCommand.SUCCESS], }, assetHashType: AssetHashType.BUNDLE, }); // THEN expect( readDockerStubInput()).toEqual( `run --rm ${USER_ARG} -v /input:/asset-input:delegated -v /output:/asset-output:delegated -w /asset-input alpine DOCKER_STUB_SUCCESS`, ); expect(asset.assetHash).toEqual('33cbf2cae5432438e0f046bc45ba8c3cef7b6afcf47b59d1c183775c1918fb1f'); }); test('bundling with docker security option', () => { // GIVEN const app = new App(); const stack = new Stack(app, 'stack'); const directory = path.join(__dirname, 'fs', 'fixtures', 'test1'); // WHEN const asset = new AssetStaging(stack, 'Asset', { sourcePath: directory, bundling: { image: DockerImage.fromRegistry('alpine'), command: [DockerStubCommand.SUCCESS], securityOpt: 'no-new-privileges', }, assetHashType: AssetHashType.BUNDLE, }); // THEN expect( readDockerStubInput()).toEqual( `run --rm --security-opt no-new-privileges ${USER_ARG} -v /input:/asset-input:delegated -v /output:/asset-output:delegated -w /asset-input alpine DOCKER_STUB_SUCCESS`, ); expect(asset.assetHash).toEqual('33cbf2cae5432438e0f046bc45ba8c3cef7b6afcf47b59d1c183775c1918fb1f'); }); test('bundling with OUTPUT asset hash type', () => { // GIVEN const app = new App(); const stack = new Stack(app, 'stack'); const directory = path.join(__dirname, 'fs', 'fixtures', 'test1'); // WHEN const asset = new AssetStaging(stack, 'Asset', { sourcePath: directory, bundling: { image: DockerImage.fromRegistry('alpine'), command: [DockerStubCommand.SUCCESS], }, assetHashType: AssetHashType.OUTPUT, }); // THEN expect(asset.assetHash).toEqual('33cbf2cae5432438e0f046bc45ba8c3cef7b6afcf47b59d1c183775c1918fb1f'); }); test('custom hash', () => { // GIVEN const app = new App(); const stack = new Stack(app, 'stack'); const directory = path.join(__dirname, 'fs', 'fixtures', 'test1'); // WHEN const asset = new AssetStaging(stack, 'Asset', { sourcePath: directory, assetHash: 'my-custom-hash', }); // THEN expect(fs.existsSync(STUB_INPUT_FILE)).toEqual(false); expect(asset.assetHash).toEqual('b9c77053f5b83bbe5ba343bc18e92db939a49017010813225fea91fa892c4823'); // hash of 'my-custom-hash' }); test('throws with assetHash and not CUSTOM hash type', () => { // GIVEN const app = new App(); const stack = new Stack(app, 'stack'); const directory = path.join(__dirname, 'fs', 'fixtures', 'test1'); // THEN expect(() => new AssetStaging(stack, 'Asset', { sourcePath: directory, bundling: { image: DockerImage.fromRegistry('alpine'), command: [DockerStubCommand.SUCCESS], }, assetHash: 'my-custom-hash', assetHashType: AssetHashType.OUTPUT, })).toThrow(/Cannot specify `output` for `assetHashType`/); }); testDeprecated('throws with BUNDLE hash type and no bundling', () => { // GIVEN const app = new App(); const stack = new Stack(app, 'stack'); const directory = path.join(__dirname, 'fs', 'fixtures', 'test1'); // THEN expect(() => new AssetStaging(stack, 'Asset', { sourcePath: directory, assetHashType: AssetHashType.BUNDLE, })).toThrow(/Cannot use `bundle` hash type when `bundling` is not specified/); expect(fs.existsSync(STUB_INPUT_FILE)).toEqual(false); }); test('throws with OUTPUT hash type and no bundling', () => { // GIVEN const app = new App(); const stack = new Stack(app, 'stack'); const directory = path.join(__dirname, 'fs', 'fixtures', 'test1'); // THEN expect(() => new AssetStaging(stack, 'Asset', { sourcePath: directory, assetHashType: AssetHashType.OUTPUT, })).toThrow(/Cannot use `output` hash type when `bundling` is not specified/); expect(fs.existsSync(STUB_INPUT_FILE)).toEqual(false); }); test('throws with CUSTOM and no hash', () => { // GIVEN const app = new App(); const stack = new Stack(app, 'stack'); const directory = path.join(__dirname, 'fs', 'fixtures', 'test1'); // THEN expect(() => new AssetStaging(stack, 'Asset', { sourcePath: directory, assetHashType: AssetHashType.CUSTOM, })).toThrow(/`assetHash` must be specified when `assetHashType` is set to `AssetHashType.CUSTOM`/); expect(fs.existsSync(STUB_INPUT_FILE)).toEqual(false); // "docker" not executed }); test('throws when bundling fails', () => { // GIVEN const app = new App(); const stack = new Stack(app, 'stack'); const directory = path.join(__dirname, 'fs', 'fixtures', 'test1'); // THEN expect(() => new AssetStaging(stack, 'Asset', { sourcePath: directory, bundling: { image: DockerImage.fromRegistry('this-is-an-invalid-docker-image'), command: [DockerStubCommand.FAIL], }, })).toThrow(/Failed to bundle asset stack\/Asset/); expect( readDockerStubInput()).toEqual( `run --rm ${USER_ARG} -v /input:/asset-input:delegated -v /output:/asset-output:delegated -w /asset-input this-is-an-invalid-docker-image DOCKER_STUB_FAIL`, ); }); test('with local bundling', () => { // GIVEN const app = new App(); const stack = new Stack(app, 'stack'); const directory = path.join(__dirname, 'fs', 'fixtures', 'test1'); // WHEN let dir: string | undefined; let opts: BundlingOptions | undefined; new AssetStaging(stack, 'Asset', { sourcePath: directory, bundling: { image: DockerImage.fromRegistry('alpine'), command: [DockerStubCommand.SUCCESS], local: { tryBundle(outputDir: string, options: BundlingOptions): boolean { dir = outputDir; opts = options; fs.writeFileSync(path.join(outputDir, 'hello.txt'), 'hello'); // output cannot be empty return true; }, }, }, }); // THEN expect(dir && /asset.[0-9a-f]{16,}/.test(dir)).toEqual(true); expect(opts?.command?.[0]).toEqual(DockerStubCommand.SUCCESS); expect(() => readDockerStubInput()).toThrow(); if (dir) { fs.removeSync(path.join(dir, 'hello.txt')); } }); test('with local bundling returning false', () => { // GIVEN const app = new App(); const stack = new Stack(app, 'stack'); const directory = path.join(__dirname, 'fs', 'fixtures', 'test1'); // WHEN new AssetStaging(stack, 'Asset', { sourcePath: directory, bundling: { image: DockerImage.fromRegistry('alpine'), command: [DockerStubCommand.SUCCESS], local: { tryBundle(_bundleDir: string): boolean { return false; }, }, }, }); // THEN expect(readDockerStubInput()).toBeDefined(); }); test('bundling can be skipped by setting context', () => { // GIVEN const app = new App(); const stack = new Stack(app, 'MyStack'); stack.node.setContext(cxapi.BUNDLING_STACKS, ['OtherStack']); const directory = path.join(__dirname, 'fs', 'fixtures', 'test1'); // WHEN const asset = new AssetStaging(stack, 'Asset', { sourcePath: directory, assetHashType: AssetHashType.OUTPUT, bundling: { image: DockerImage.fromRegistry('alpine'), command: [DockerStubCommand.SUCCESS], }, }); expect(() => readDockerStubInput()).toThrow(); // Bundling did not run expect(asset.sourcePath).toEqual(directory); expect(asset.stagedPath).toEqual(directory); expect(asset.relativeStagedPath(stack)).toEqual(directory); expect(asset.assetHash).toEqual('f66d7421aa2d044a6c1f60ddfc76dc78571fcd8bd228eb48eb394e2dbad94a5c'); }); test('correctly skips bundling with stack under stage', () => { // GIVEN const app = new App(); const stage = new Stage(app, 'Stage'); stage.node.setContext(cxapi.BUNDLING_STACKS, ['Stage/Stack1']); const stack1 = new Stack(stage, 'Stack1'); const stack2 = new Stack(stage, 'Stack2'); const directory = path.join(__dirname, 'fs', 'fixtures', 'test1'); new AssetStaging(stack1, 'Asset', { sourcePath: directory, assetHashType: AssetHashType.OUTPUT, bundling: { image: DockerImage.fromRegistry('alpine'), command: [DockerStubCommand.SUCCESS], }, }); new AssetStaging(stack2, 'Asset', { sourcePath: directory, assetHashType: AssetHashType.OUTPUT, bundling: { image: DockerImage.fromRegistry('alpine'), command: [DockerStubCommand.MULTIPLE_FILES], }, }); const dockerStubInput = readDockerStubInputConcat(); // Docker ran for the asset in Stack1 expect(dockerStubInput).toMatch(DockerStubCommand.SUCCESS); // DOcker did not run for the asset in Stack2 expect(dockerStubInput).not.toMatch(DockerStubCommand.MULTIPLE_FILES); }); test('bundling still occurs with partial wildcard', () => { // GIVEN const app = new App(); const stack = new Stack(app, 'MyStack'); stack.node.setContext(cxapi.BUNDLING_STACKS, ['*Stack']); const directory = path.join(__dirname, 'fs', 'fixtures', 'test1'); // WHEN const asset = new AssetStaging(stack, 'Asset', { sourcePath: directory, assetHashType: AssetHashType.OUTPUT, bundling: { image: DockerImage.fromRegistry('alpine'), command: [DockerStubCommand.SUCCESS], }, }); expect( readDockerStubInput()).toEqual( `run --rm ${USER_ARG} -v /input:/asset-input:delegated -v /output:/asset-output:delegated -w /asset-input alpine DOCKER_STUB_SUCCESS`, ); expect(asset.assetHash).toEqual('33cbf2cae5432438e0f046bc45ba8c3cef7b6afcf47b59d1c183775c1918fb1f'); // hash of MyStack/Asset }); test('bundling still occurs with full wildcard', () => { // GIVEN const app = new App(); const stack = new Stack(app, 'MyStack'); stack.node.setContext(cxapi.BUNDLING_STACKS, ['*']); const directory = path.join(__dirname, 'fs', 'fixtures', 'test1'); // WHEN const asset = new AssetStaging(stack, 'Asset', { sourcePath: directory, assetHashType: AssetHashType.OUTPUT, bundling: { image: DockerImage.fromRegistry('alpine'), command: [DockerStubCommand.SUCCESS], }, }); expect( readDockerStubInput()).toEqual( `run --rm ${USER_ARG} -v /input:/asset-input:delegated -v /output:/asset-output:delegated -w /asset-input alpine DOCKER_STUB_SUCCESS`, ); expect(asset.assetHash).toEqual('33cbf2cae5432438e0f046bc45ba8c3cef7b6afcf47b59d1c183775c1918fb1f'); // hash of MyStack/Asset }); test('bundling that produces a single archive file is autodiscovered', () => { // GIVEN const app = new App({ context: { [cxapi.NEW_STYLE_STACK_SYNTHESIS_CONTEXT]: false } }); const stack = new Stack(app, 'stack'); const directory = path.join(__dirname, 'fs', 'fixtures', 'test1'); // WHEN const staging = new AssetStaging(stack, 'Asset', { sourcePath: directory, bundling: { image: DockerImage.fromRegistry('alpine'), command: [DockerStubCommand.SINGLE_ARCHIVE], }, }); // THEN const assembly = app.synth(); expect(fs.readdirSync(assembly.directory)).toEqual([ 'asset.f43148c61174f444925231b5849b468f21e93b5d1469cd07c53625ffd039ef48', // this is the bundle dir 'asset.f43148c61174f444925231b5849b468f21e93b5d1469cd07c53625ffd039ef48.zip', 'cdk.out', 'manifest.json', 'stack.template.json', 'tree.json', ]); expect(fs.readdirSync(path.join(assembly.directory, 'asset.f43148c61174f444925231b5849b468f21e93b5d1469cd07c53625ffd039ef48'))).toEqual([ 'test.zip', // bundle dir with "touched" bundled output file ]); expect(staging.packaging).toEqual(FileAssetPackaging.FILE); expect(staging.isArchive).toEqual(true); }); test('bundling that produces a single archive file with disk cache', () => { // GIVEN const TEST_OUTDIR = path.join(__dirname, 'cdk.out'); if (fs.existsSync(TEST_OUTDIR)) { fs.removeSync(TEST_OUTDIR); } const directory = path.join(__dirname, 'fs', 'fixtures', 'test1'); const app1 = new App({ outdir: TEST_OUTDIR }); const stack1 = new Stack(app1, 'Stack'); const app2 = new App({ outdir: TEST_OUTDIR }); // same OUTDIR const stack2 = new Stack(app2, 'stack'); // WHEN const staging1 = new AssetStaging(stack1, 'Asset', { sourcePath: directory, bundling: { image: DockerImage.fromRegistry('alpine'), command: [DockerStubCommand.SINGLE_ARCHIVE], outputType: BundlingOutput.ARCHIVED, }, }); // Now clear asset hash cache to show that during the second staging // even though bundling is skipped it will correctly be considered // as a FileAssetPackaging.FILE. AssetStaging.clearAssetHashCache(); const staging2 = new AssetStaging(stack2, 'Asset', { sourcePath: directory, bundling: { image: DockerImage.fromRegistry('alpine'), command: [DockerStubCommand.SINGLE_ARCHIVE], outputType: BundlingOutput.ARCHIVED, }, }); // THEN expect(staging1.packaging).toEqual(FileAssetPackaging.FILE); expect(staging1.isArchive).toEqual(true); expect(staging2.packaging).toEqual(staging1.packaging); expect(staging2.isArchive).toEqual(staging1.isArchive); }); test('bundling that produces a single archive file with NOT_ARCHIVED', () => { // GIVEN const app = new App({ context: { [cxapi.NEW_STYLE_STACK_SYNTHESIS_CONTEXT]: false } }); const stack = new Stack(app, 'stack'); const directory = path.join(__dirname, 'fs', 'fixtures', 'test1'); // WHEN const staging = new AssetStaging(stack, 'Asset', { sourcePath: directory, bundling: { image: DockerImage.fromRegistry('alpine'), command: [DockerStubCommand.SINGLE_ARCHIVE], outputType: BundlingOutput.NOT_ARCHIVED, }, }); // THEN const assembly = app.synth(); expect(fs.readdirSync(assembly.directory)).toEqual([ 'asset.86ec07746e1d859290cfd8b9c648e581555649c75f51f741f11e22cab6775abc', 'cdk.out', 'manifest.json', 'stack.template.json', 'tree.json', ]); expect(staging.packaging).toEqual(FileAssetPackaging.ZIP_DIRECTORY); expect(staging.isArchive).toEqual(true); }); test('throws with ARCHIVED and bundling that does not produce a single archive file', () => { // GIVEN const app = new App(); const stack = new Stack(app, 'stack'); const directory = path.join(__dirname, 'fs', 'fixtures', 'test1'); // WHEN expect(() => new AssetStaging(stack, 'Asset', { sourcePath: directory, bundling: { image: DockerImage.fromRegistry('alpine'), command: [DockerStubCommand.MULTIPLE_FILES], outputType: BundlingOutput.ARCHIVED, }, })).toThrow(/Bundling output directory is expected to include only a single .zip or .jar file when `output` is set to `ARCHIVED`/); }); }); // Reads a docker stub and cleans the volume paths out of the stub. function readAndCleanDockerStubInput(file: string) { return fs .readFileSync(file, 'utf-8') .trim() .replace(/-v ([^:]+):\/asset-input/g, '-v /input:/asset-input') .replace(/-v ([^:]+):\/asset-output/g, '-v /output:/asset-output'); } // Last docker input since last teardown function readDockerStubInput() { return readAndCleanDockerStubInput(STUB_INPUT_FILE); } // Concatenated docker inputs since last teardown function readDockerStubInputConcat() { return readAndCleanDockerStubInput(STUB_INPUT_CONCAT_FILE); }
the_stack
import { Component, OnInit, OnDestroy, EventEmitter } from '@angular/core'; import { Router } from '@angular/router'; import { Store } from '@ngrx/store'; import { combineLatest, Subject } from 'rxjs'; import { NgrxStateAtom } from 'app/ngrx.reducers'; import { LayoutFacadeService, Sidebar } from 'app/entities/layout/layout.facade'; import { routeParams, routeURL } from 'app/route.selectors'; import { filter, pluck, takeUntil } from 'rxjs/operators'; import { identity } from 'lodash/fp'; import { infraRoleFromRoute } from 'app/entities/infra-roles/infra-role-details.selectors'; import { GetRole } from 'app/entities/infra-roles/infra-role.action'; import { GetRecipes } from 'app/entities/recipes/recipe.action'; import { GetRoleEnvironments } from 'app/entities/role-environments/role-environments.action'; import { GetRunlists } from 'app/entities/runlists/runlists.action'; import { allRecipes, getAllStatus as getAllRecipesForOrgStatus } from 'app/entities/recipes/recipe.selectors'; import { allRoleEnvironments, getAllStatus as getAllRoleEnvironmentsForOrgStatus } from 'app/entities/role-environments/role-environments.selectors'; import { allRunlist, getAllStatus as getAllRunlistForOrgStatus } from 'app/entities/runlists/runlists.selectors'; import { isNil } from 'lodash/fp'; import { InfraRole, RoleAttributes } from 'app/entities/infra-roles/infra-role.model'; import { EntityStatus } from 'app/entities/entities'; import { Node, Options } from '../tree-table/models'; import { ListItem } from '../select-box/src/lib/list-item.domain'; import { List, ExpandedChildList, Runlist } from 'app/entities/runlists/runlists.model'; import { AvailableType } from '../infra-roles/infra-roles.component'; export type InfraRoleTabName = 'runList' | 'attributes'; @Component({ selector: 'app-infra-role-details', templateUrl: './infra-role-details.component.html', styleUrls: ['./infra-role-details.component.scss'] }) export class InfraRoleDetailsComponent implements OnInit, OnDestroy { public conflictError = false; public role: InfraRole; public tabValue: InfraRoleTabName = 'runList'; public url: string; public serverId; public orgId; public name; public show = false; public showAttribute = false; public hasRun_List = false; public hasOverrideJson = true; public hasDefaultJson = true; public roleDetailsLoading = true; public roleAttributeLoading = true; public runListLoading = true; public openEdit = false; public editDisabled = false; public treeOptions: Options<ExpandedChildList> = { capitalizedHeader: true }; public arrayOfNodesTree: Node<ExpandedChildList>[]; public attributes = new RoleAttributes({ default_attributes: '', override_attributes: '' }); public availableType: AvailableType[] = []; public childNodes: Node<ExpandedChildList>[] = []; public expandedRunList: List[] = []; public idList: string[] = []; public recipes: string[] = []; public runList: string[]; public selected: ListItem[] = []; public jsonText: string; public label: string; public per_page = 9; public selectedAttrs: any; // precedence levels public default_attributes = 'default_attributes'; public override_attributes = 'override_attributes'; public all = 'all'; public env_id = '_default'; public selected_level = 'all'; public conflictErrorEvent = new EventEmitter<boolean>(); public openEnvironmentModal = new EventEmitter<boolean>(); private isDestroyed = new Subject<boolean>(); constructor( private store: Store<NgrxStateAtom>, private router: Router, private layoutFacade: LayoutFacadeService ) { } ngOnInit() { this.arrayOfNodesTree = []; this.childNodes = []; this.idList = []; this.layoutFacade.showSidebar(Sidebar.Infrastructure); this.store.select(routeURL).pipe(takeUntil(this.isDestroyed)) .subscribe((url: string) => { this.url = url; const [, fragment] = url.split('#'); this.tabValue = (fragment === 'attributes') ? 'attributes' : 'runList'; }); combineLatest([ this.store.select(routeParams).pipe(pluck('id'), filter(identity)), this.store.select(routeParams).pipe(pluck('org-id'), filter(identity)), this.store.select(routeParams).pipe(pluck('name'), filter(identity)) ]).pipe( takeUntil(this.isDestroyed) ).subscribe(([server_id, org_id, name]: string[]) => { this.serverId = server_id; this.orgId = org_id; this.name = name; this.store.dispatch(new GetRole({ server_id: server_id, org_id: org_id, name: name })); }); this.loadRecipes(); this.loadRoleEnvironments(); this.loadRunlists(this.env_id); this.store.select(infraRoleFromRoute).pipe( filter(identity), takeUntil(this.isDestroyed) ).subscribe(role => { this.show = true; this.showAttribute = true; this.role = role; this.runList = this.role.run_list; this.attributes = new RoleAttributes(this.role); this.hasDefaultJson = Object.keys( JSON.parse(this.role.default_attributes)).length > 0 ? true : false; this.hasOverrideJson = Object.keys( JSON.parse(this.role.override_attributes)).length > 0 ? true : false; // Settimeout - In the case of passing large attribute data sets setTimeout(() => this.filter(this.selected_level), 10); this.roleDetailsLoading = false; this.roleAttributeLoading = false; if (!this.idList.length) { this.idList[0] = this.env_id; } }); } ngOnDestroy(): void { this.isDestroyed.next(true); this.isDestroyed.complete(); } // retrieve attributes based on their level of precedence retrieve(level: string): Object { switch (level) { case this.all: { return this.attributes.all; } case this.default_attributes: { return this.attributes.default_attributes; } case this.override_attributes: { return this.attributes.override_attributes; } default: { return {}; } } } selectChangeHandler(id: string): void { this.env_id = id; this.editDisabled = (this.env_id === '_default') ? false : true; this.runListLoading = true; this.hasRun_List = false; this.arrayOfNodesTree = []; this.loadRunlists(this.env_id); } openEditModal(value, label: string): void { this.openEdit = true; const obj = JSON.parse(value); this.jsonText = JSON.stringify(obj, null, 4); this.label = label; this.openEnvironmentModal.emit(true); } onSelectedTab(event: { target: { value: InfraRoleTabName } }) { this.tabValue = event.target.value; this.router.navigate([this.url.split('#')[0]], { fragment: event.target.value }); this.filter(this.selected_level); } updateRunlist() { this.selectChangeHandler(this.env_id); } private loadRecipes(): void { this.store.dispatch(new GetRecipes({ server_id: this.serverId, org_id: this.orgId, name: '_default' })); combineLatest([ this.store.select(getAllRecipesForOrgStatus), this.store.select(allRecipes) ]).pipe(takeUntil(this.isDestroyed)) .subscribe(([getRecipesSt, allRecipesState]) => { if (getRecipesSt === EntityStatus.loadingSuccess && !isNil(allRecipesState)) { this.recipes = allRecipesState; if (this.recipes.length > 0) { this.recipes.forEach((recipe) => { this.availableType.push({ name: recipe, type: 'recipe' }); }); } } }); } private loadRoleEnvironments(): void { this.store.dispatch(new GetRoleEnvironments({ server_id: this.serverId, org_id: this.orgId, name: this.name })); combineLatest([ this.store.select(getAllRoleEnvironmentsForOrgStatus), this.store.select(allRoleEnvironments) ]).pipe(takeUntil(this.isDestroyed)) .subscribe(([getRoleEnvironmentsSt, allRoleEnvironmentsState]) => { if (getRoleEnvironmentsSt === EntityStatus.loadingSuccess && !isNil(allRoleEnvironmentsState)) { this.idList = allRoleEnvironmentsState; if (this.idList.length > 0) { this.env_id = this.idList[0]; } else { this.idList[0] = this.env_id; } this.show = true; } }); } private loadRunlists(environmentId: string): void { this.store.dispatch(new GetRunlists({ server_id: this.serverId, org_id: this.orgId, name: this.name, id: environmentId })); combineLatest([ this.store.select(getAllRunlistForOrgStatus), this.store.select(allRunlist) ]).pipe(takeUntil(this.isDestroyed)) .subscribe(([getRunlistSt, allRunlistState]) => { if (getRunlistSt === EntityStatus.loadingSuccess && !isNil(allRunlistState)) { if (allRunlistState && allRunlistState.length) { this.treeNodes(allRunlistState, environmentId); } else { this.runListLoading = false; } this.conflictError = false; } else if (getRunlistSt === EntityStatus.loadingFailure) { this.conflictError = true; this.hasRun_List = false; this.runListLoading = false; this.env_id = '_default'; } }); } // set selected item to selected_level private filter(precedence_level: string): void { this.selected_level = precedence_level; this.selectedAttrs = this.retrieve(precedence_level); } // 1. According to the environment ID getting the array. // 2. Then Convert our Particular Array data with parent, child nodes as tree structure. private treeNodes(expandedList: Runlist[], li: string) { this.arrayOfNodesTree = []; this.selected = []; for (let i = 0; i < expandedList.length; i++) { if (expandedList[i].id === li) { this.expandedRunList = expandedList[i].run_list; if (this.expandedRunList && this.expandedRunList.length) { for (let j = 0; j < this.expandedRunList.length; j++) { this.selected.push({ selected: false, type: this.expandedRunList[j].type, value: this.expandedRunList[j].name }); this.arrayOfNodesTree.push({ value: { name: this.expandedRunList[j].name, version: this.expandedRunList[j].version ? this.expandedRunList[j].version : '...', type: this.expandedRunList[j].type, error: this.expandedRunList[j].error, position: this.expandedRunList[j].position, skipped: this.expandedRunList[j].skipped }, children: this.expandedRunList[j].children && this.expandedRunList[j].children.length ? this.childNode(this.expandedRunList[j].children, []) : [] }); } this.hasRun_List = true; this.runListLoading = false; } else { this.hasRun_List = false; this.runListLoading = false; } } } this.show = true; } private childNode(child: List[], nodes: Node<ExpandedChildList>[]) { for (let i = 0; i < child.length; i++) { nodes.push({ value: { name: child[i].name, version: child[i].version ? child[i].version : '...', type: child[i].type, error: child[i].error, position: child[i].position, skipped: child[i].skipped }, children: child[i].children && child[i].children.length ? this.childNode(child[i].children, []) : [] }); } return nodes; } }
the_stack
module BABYLON { export class Text2DRenderCache extends ModelRenderCache { effectsReady: boolean = false; vb: WebGLBuffer = null; ib: WebGLBuffer = null; instancingAttributes: InstancingAttributeInfo[] = null; fontTexture: BaseFontTexture = null; effect: Effect = null; effectInstanced: Effect = null; fontPremulAlpha: boolean = false; render(instanceInfo: GroupInstanceInfo, context: Render2DContext): boolean { // Do nothing if the shader is still loading/preparing if (!this.effectsReady) { if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) { return false; } this.effectsReady = true; } let canvas = instanceInfo.owner.owner; var engine = canvas.engine; this.fontTexture.update(); let effect = context.useInstancing ? this.effectInstanced : this.effect; engine.enableEffect(effect); effect.setTexture("diffuseSampler", this.fontTexture); engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect); let sdf = this.fontTexture.isSignedDistanceField; // Enable alpha mode only if the texture is not using SDF, SDF is rendered in AlphaTest mode, which mean no alpha blend var curAlphaMode: number; if (!sdf) { curAlphaMode = engine.getAlphaMode(); engine.setAlphaMode(this.fontPremulAlpha ? Engine.ALPHA_PREMULTIPLIED : Engine.ALPHA_COMBINE, true); } let pid = context.groupInfoPartData[0]; if (context.useInstancing) { if (!this.instancingAttributes) { this.instancingAttributes = this.loadInstancingAttributes(Text2D.TEXT2D_MAINPARTID, effect); } let glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer; let count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount; canvas._addDrawCallCount(1, context.renderMode); engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes); engine.draw(true, 0, 6, count); engine.unbindInstanceAttributes(); } else { canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode); for (let i = context.partDataStartIndex; i < context.partDataEndIndex; i++) { this.setupUniforms(effect, 0, pid._partData, i); engine.draw(true, 0, 6); } } if (!sdf) { engine.setAlphaMode(curAlphaMode, true); } return true; } public dispose(): boolean { if (!super.dispose()) { return false; } if (this.vb) { this._engine._releaseBuffer(this.vb); this.vb = null; } if (this.ib) { this._engine._releaseBuffer(this.ib); this.ib = null; } if (this.fontTexture) { this.fontTexture.decCachedFontTextureCounter(); this.fontTexture = null; } this.effect = null; this.effectInstanced = null; return true; } } export class Text2DInstanceData extends InstanceDataBase { constructor(partId: number, dataElementCount: number) { super(partId, dataElementCount); } @instanceData() get topLeftUV(): Vector2 { return null; } set topLeftUV(value: Vector2) { } @instanceData() get sizeUV(): Vector2 { return null; } set sizeUV(value: Vector2) { } @instanceData() get textureSize(): Vector2 { return null; } set textureSize(value: Vector2) { } @instanceData() get color(): Color4 { return null; } set color(value: Color4) { } @instanceData() get superSampleFactor(): number { return null; } set superSampleFactor(value: number) { } } @className("Text2D", "BABYLON") /** * Primitive that render text using a specific font */ export class Text2D extends RenderablePrim2D { static TEXT2D_MAINPARTID = 1; static TEXT2D_CATEGORY_SDF = "SignedDistanceField"; static TEXT2D_CATEGORY_FONTTEXTURE = "FontTexture"; public static fontProperty: Prim2DPropInfo; public static defaultFontColorProperty: Prim2DPropInfo; public static textProperty: Prim2DPropInfo; public static sizeProperty: Prim2DPropInfo; public static fontSuperSampleProperty: Prim2DPropInfo; public static fontSignedDistanceFieldProperty: Prim2DPropInfo; public static textureIsPremulAlphaProperty: Prim2DPropInfo; public static fontTextureProperty: Prim2DPropInfo; /** * Alignment is made relative to the left edge of the Content Area. Valid for horizontal alignment only. */ public static get AlignLeft(): number { return Text2D._AlignLeft; } /** * Alignment is made relative to the top edge of the Content Area. Valid for vertical alignment only. */ public static get AlignTop(): number { return Text2D._AlignTop; } /** * Alignment is made relative to the right edge of the Content Area. Valid for horizontal alignment only. */ public static get AlignRight(): number { return Text2D._AlignRight; } /** * Alignment is made relative to the bottom edge of the Content Area. Valid for vertical alignment only. */ public static get AlignBottom(): number { return Text2D._AlignBottom; } /** * Alignment is made to center the text from equal distance to the opposite edges of the Content Area */ public static get AlignCenter(): number { return Text2D._AlignCenter; } private static _AlignLeft = 1; private static _AlignTop = 1; // Same as left private static _AlignRight = 2; private static _AlignBottom = 2; // Same as right private static _AlignCenter = 3; @modelLevelProperty(RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, pi => Text2D.fontProperty = pi, false, true) /** * Get/set the font name to use, using HTML CSS notation. * Set is not supported right now. */ public get fontName(): string { return this._fontName; } public set fontName(value: string) { if (this._fontName) { throw new Error("Font Name change is not supported right now."); } this._fontName = value; } @dynamicLevelProperty(RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, pi => Text2D.defaultFontColorProperty = pi) /** * Get/set the font default color */ public get defaultFontColor(): Color4 { return this._defaultFontColor; } public set defaultFontColor(value: Color4) { if (!this._defaultFontColor) { this._defaultFontColor = value.clone(); } else { this._defaultFontColor.copyFrom(value); } } @instanceLevelProperty(RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, pi => Text2D.textProperty = pi, false, true) /** * Get/set the text to render. * \n \t character are supported. */ public get text(): string { return this._text; } public set text(value: string) { if (!value) { value = ""; } this._text = value; this._textSize = null; // A change of text will reset the TextSize which will be recomputed next time it's used if(!this._sizeSetByUser){ this._size = null; this._actualSize = null; } this._updateCharCount(); // Trigger a textSize to for a sizeChange if necessary, which is needed for layout to recompute let s = this.textSize; } @instanceLevelProperty(RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, pi => Text2D.sizeProperty = pi) /** * Get/set the size of the area where the text is drawn. * You should not set this size, the default behavior compute the size based on the actual text. */ public get size(): Size { if (this._size != null) { return this._size; } return this.textSize; } public set size(value: Size) { this.internalSetSize(value); } @modelLevelProperty(RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, pi => Text2D.fontSuperSampleProperty = pi, false, false) /** * Get/set the font name to use, using HTML CSS notation. * Set is not supported right now. */ public get fontSuperSample(): boolean { return this._fontTexture && this._fontTexture.isSuperSampled; } @modelLevelProperty(RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 6, pi => Text2D.fontSignedDistanceFieldProperty = pi, false, false) /** * Get/set the font name to use, using HTML CSS notation. * Set is not supported right now. */ public get fontSignedDistanceField(): boolean { return this._fontTexture && this._fontTexture.isSignedDistanceField; } @instanceLevelProperty(RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 7, pi => Text2D.textureIsPremulAlphaProperty = pi) /** * Set to true if the FontTexture use Premultiplied Alpha, default is false */ public get textureIsPremulAlpha(): boolean { return this._textureIsPremulAlpha; } public set textureIsPremulAlpha(value: boolean) { this._textureIsPremulAlpha = value; } public get isSizeAuto(): boolean { return false; } public get isVerticalSizeAuto(): boolean { return false; } public get isHorizontalSizeAuto(): boolean { return false; } /** * Get the area that bounds the text associated to the primitive */ public get textSize(): Size { if (!this._textSize) { if (this.owner && this._text) { let ft = this.fontTexture; if (ft == null) { return Text2D.nullSize; } let newSize = ft.measureText(this._text, this._tabulationSize); if (!newSize.equals(this._textSize)) { this.onPrimitivePropertyDirty(Prim2DBase.sizeProperty.flagId); this._positioningDirty(); } this._textSize = newSize; } else { return Text2D.nullSize; } } return this._textSize; } protected onSetOwner() { if (!this._textSize) { this.onPrimitivePropertyDirty(Prim2DBase.sizeProperty.flagId); this._setLayoutDirty(); this._positioningDirty(); this._actualSize = null; this._setFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty|SmartPropertyPrim.flagBoundingInfoDirty); } } @modelLevelProperty(RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 8, pi => Text2D.fontTextureProperty = pi) public get fontTexture(): BaseFontTexture { if (this._fontTexture) { return this._fontTexture; } if (this.fontName == null || this.owner == null || this.owner.scene == null) { return null; } this._fontBilinearFiltering = (this._useBilinearFiltering === null) ? (this.owner instanceof WorldSpaceCanvas2D) : this._useBilinearFiltering; this._fontTexture = FontTexture.GetCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample, this._fontSDF, this._fontBilinearFiltering); this._textureIsPremulAlpha = this._fontTexture.isPremultipliedAlpha; return this._fontTexture; } /** * Dispose the primitive, remove it from its parent */ public dispose(): boolean { if (!super.dispose()) { return false; } if (this._fontTexture) { FontTexture.ReleaseCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample, this._fontSDF, this._fontBilinearFiltering); this._fontTexture = null; } return true; } protected updateLevelBoundingInfo() { if (!this.owner || !this._text) { return false; } let asize = this.actualSize; if (asize.width===0 && asize.height===0) { return false; } BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo); return true; } /** * You can get/set the text alignment through this property */ public get textAlignment(): string { return this._textAlignment; } public set textAlignment(value: string) { this._textAlignment = value; this._setTextAlignmentfromString(value); } /** * Create a Text primitive * @param text the text to display * @param settings a combination of settings, possible ones are * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting) * - children: an array of direct children * - id a text identifier, for information purpose * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0] * - rotation: the initial rotation (in radian) of the primitive. default is 0 * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property * - alignToPixel: if true the primitive will be aligned to the target rendering device's pixel * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent. * - zOrder: override the zOrder with the specified value * - origin: define the normalized origin point location, default [0.5;0.5] * - fontName: the name/size/style of the font to use, following the CSS notation. Default is "12pt Arial". * - fontSuperSample: if true the text will be rendered with a superSampled font (the font is twice the given size). Use this settings if the text lies in world space or if it's scaled in. * - signedDistanceField: if true the text will be rendered using the SignedDistanceField technique. This technique has the advantage to be rendered order independent (then much less drawing calls), but only works on font that are a little more than one pixel wide on the screen but the rendering quality is excellent whatever the font size is on the screen (which is the purpose of this technique). Outlining/Shadow is not supported right now. If you can, you should use this mode, the quality and the performances are the best. Note that fontSuperSample has no effect when this mode is on. * - bitmapFontTexture: set a BitmapFontTexture to use instead of a fontName. * - defaultFontColor: the color by default to apply on each letter of the text to display, default is plain white. * - useBilinearFiltering: if true a FontTexture using Bilinear filtering will be used, if false a FontTexture using Nearest filtering will be used. If not specified then bilinear will be chosen for Signed Distance Field mode or a Text2D inside a WorldSpaceCanvas2D, otherwise nearest will be chose. * - areaSize: the size of the area in which to display the text, default is auto-fit from text content. * - tabulationSize: number of space character to insert when a tabulation is encountered, default is 4 * - isVisible: true if the text must be visible, false for hidden. Default is true. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED! * - levelCollision: this primitive is an actor of the Collision Manager and only this level will be used for collision (i.e. not the children). Use deepCollision if you want collision detection on the primitives and its children. * - deepCollision: this primitive is an actor of the Collision Manager, this level AND ALSO its children will be used for collision (note: you don't need to set the children as level/deepCollision). * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString) * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString) * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString) * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString) * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString) * - marginHAlignment: one value of the PrimitiveAlignment type's static properties * - marginVAlignment: one value of the PrimitiveAlignment type's static properties * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString) * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString) * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString) * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString) * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString) * - textAlignmentH: align text horizontally (Text2D.AlignLeft, Text2D.AlignCenter, Text2D.AlignRight) * - textAlignmentV: align text vertically (Text2D.AlignTop, Text2D.AlignCenter, Text2D.AlignBottom) * - textAlignment: a string defining the text alignment, text can be: [<h:|horizontal:><left|right|center>], [<v:|vertical:><top|bottom|center>] * - wordWrap: if true the text will wrap inside content area */ constructor(text: string, settings?: { parent ?: Prim2DBase, children ?: Array<Prim2DBase>, id ?: string, position ?: Vector2, x ?: number, y ?: number, rotation ?: number, scale ?: number, scaleX ?: number, scaleY ?: number, dontInheritParentScale ?: boolean, alignToPixel ?: boolean, opacity ?: number, zOrder ?: number, origin ?: Vector2, fontName ?: string, fontSuperSample ?: boolean, fontSignedDistanceField ?: boolean, bitmapFontTexture ?: BitmapFontTexture, defaultFontColor ?: Color4, useBilinearFiltering ?: boolean, size ?: Size, tabulationSize ?: number, isVisible ?: boolean, isPickable ?: boolean, isContainer ?: boolean, childrenFlatZOrder ?: boolean, levelCollision ?: boolean, deepCollision ?: boolean, layoutData ?: ILayoutData, marginTop ?: number | string, marginLeft ?: number | string, marginRight ?: number | string, marginBottom ?: number | string, margin ?: number | string, marginHAlignment ?: number, marginVAlignment ?: number, marginAlignment ?: string, paddingTop ?: number | string, paddingLeft ?: number | string, paddingRight ?: number | string, paddingBottom ?: number | string, padding ?: number | string, textAlignmentH ?: number, textAlignmentV ?: number, textAlignment ?: string, wordWrap ?: boolean }) { if (!settings) { settings = {}; } super(settings); if (settings.bitmapFontTexture != null) { this._fontTexture = settings.bitmapFontTexture; this._fontName = null; this._fontSuperSample = false; this._fontSDF = false; this._textureIsPremulAlpha = this._fontTexture.isPremultipliedAlpha; let ft = this._fontTexture; if (ft != null && !ft.isReady()) { ft.onLoadObservable.add(() => { this._positioningDirty(); this._setLayoutDirty(); this._instanceDirtyFlags |= Prim2DBase.originProperty.flagId; // To make sure the Text2D is issued again for render }); } } else { this._fontName = (settings.fontName==null) ? "12pt Arial" : settings.fontName; this._fontSuperSample= (settings.fontSuperSample!=null && settings.fontSuperSample); this._fontSDF = (settings.fontSignedDistanceField!=null && settings.fontSignedDistanceField); } this._defaultFontColor = (settings.defaultFontColor == null) ? new Color4(1, 1, 1, 1) : settings.defaultFontColor.clone(); this._tabulationSize = (settings.tabulationSize == null) ? 4 : settings.tabulationSize; this._textureIsPremulAlpha = true;//settings.fontTexturePremulAlpha === true; this._textSize = null; this.text = text; if (settings.size != null){ this.size = settings.size; this._sizeSetByUser = true; }else{ this.size = null; } this._useBilinearFiltering = (settings.useBilinearFiltering != null) ? settings.useBilinearFiltering : null; this._fontBilinearFiltering = false; // Text rendering must always be aligned to the target's pixel to ensure a good quality this.alignToPixel = true; this.textAlignmentH = (settings.textAlignmentH==null) ? Text2D.AlignLeft : settings.textAlignmentH; this.textAlignmentV = (settings.textAlignmentV==null) ? Text2D.AlignTop : settings.textAlignmentV; this.textAlignment = (settings.textAlignment==null) ? "" : settings.textAlignment; this._wordWrap = (settings.wordWrap==null) ? false : settings.wordWrap; this._updateRenderMode(); } protected levelIntersect(intersectInfo: IntersectInfo2D): boolean { // For now I can't do something better that boundingInfo is a hit, detecting an intersection on a particular letter would be possible, but do we really need it? Not for now... return true; } protected createModelRenderCache(modelKey: string): ModelRenderCache { let renderCache = new Text2DRenderCache(this.owner.engine, modelKey); return renderCache; } protected setupModelRenderCache(modelRenderCache: ModelRenderCache) { let renderCache = <Text2DRenderCache>modelRenderCache; let engine = this.owner.engine; renderCache.fontTexture = this.fontTexture; renderCache.fontTexture.incCachedFontTextureCounter(); renderCache.fontPremulAlpha = this.textureIsPremulAlpha; let vb = new Float32Array(4); for (let i = 0; i < 4; i++) { vb[i] = i; } renderCache.vb = engine.createVertexBuffer(vb); let ib = new Float32Array(6); ib[0] = 0; ib[1] = 2; ib[2] = 1; ib[3] = 0; ib[4] = 3; ib[5] = 2; renderCache.ib = engine.createIndexBuffer(ib); // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one let ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], null, true); if (ei) { renderCache.effectInstanced = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null); } ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], null, false); renderCache.effect = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null); return renderCache; } protected createInstanceDataParts(): InstanceDataBase[] { return [new Text2DInstanceData(Text2D.TEXT2D_MAINPARTID, this._charCount)]; } // Looks like a hack!? Yes! Because that's what it is! // For the InstanceData layer to compute correctly we need to set all the properties involved, which won't be the case if there's no text // This method is called before the layout construction for us to detect this case, set some text and return the initial one to restore it after (there can be some text without char to display, say "\t\n" for instance) protected beforeRefreshForLayoutConstruction(part: InstanceDataBase): any { if (!this._charCount) { let curText = this._text; this.text = "A"; return curText; } } // if obj contains something, we restore the _text property protected afterRefreshForLayoutConstruction(part: InstanceDataBase, obj: any) { if (obj !== undefined) { this.text = obj; } } protected getUsedShaderCategories(dataPart: InstanceDataBase): string[] { var cat = super.getUsedShaderCategories(dataPart); if (this._fontSDF) { cat.push(Text2D.TEXT2D_CATEGORY_SDF); } if (this._fontTexture instanceof FontTexture) { cat.push(Text2D.TEXT2D_CATEGORY_FONTTEXTURE); } return cat; } protected refreshInstanceDataPart(part: InstanceDataBase): boolean { if (!super.refreshInstanceDataPart(part)) { return false; } if (part.id === Text2D.TEXT2D_MAINPARTID) { let d = <Text2DInstanceData>part; let ft = this.fontTexture; let texture = ft; if (!texture) { return false; } let superSampleFactor = texture.isSuperSampled ? 0.5 : 1; let ts = texture.getSize(); let offset = Vector2.Zero(); let lh = ft.lineHeight; d.dataElementCount = this._charCount; d.curElement = 0; let lineLengths = []; let charWidths = []; let charsPerLine = []; let numCharsCurrenLine = 0; let contentAreaWidth = this.contentArea.width; let contentAreaHeight = this.contentArea.height; let numCharsCurrentWord = 0; let widthCurrentWord = 0; let numWordsPerLine = 0; let text = this.text; let tabWidth = this._tabulationSize * texture.spaceWidth; // First pass: analyze the text to build data like pixel length of each lines, width of each char, number of char per line for (let i = 0; i < text.length; i++) { let char = text[i]; numCharsCurrenLine++; charWidths[i] = 0; // Line feed if (this._isWhiteSpaceCharVert(char)) { lineLengths.push(offset.x); charsPerLine.push(numCharsCurrenLine - 1); numCharsCurrenLine = 1; offset.x = 0; if (widthCurrentWord > 0) { numWordsPerLine++; } numWordsPerLine = 0; numCharsCurrentWord = 0; widthCurrentWord = 0; continue; } let ci = texture.getChar(char); let charWidth = 0; if (char === "\t") { charWidth = tabWidth; }else{ charWidth = ci.xAdvance; } offset.x += charWidth; charWidths[i] = charWidth; if (this._isWhiteSpaceCharHoriz(char)) { if (widthCurrentWord > 0) { numWordsPerLine++; } numCharsCurrentWord = 0; widthCurrentWord = 0; }else { widthCurrentWord += ci.xAdvance; numCharsCurrentWord++; } if (this._wordWrap && numWordsPerLine > 0 && offset.x > contentAreaWidth) { lineLengths.push(offset.x - widthCurrentWord); numCharsCurrenLine -= numCharsCurrentWord; let j = i - numCharsCurrentWord; //skip white space at the end of this line while (this._isWhiteSpaceCharHoriz(text[j])) { lineLengths[lineLengths.length - 1] -= charWidths[j]; j--; } charsPerLine.push(numCharsCurrenLine); if(this._isWhiteSpaceCharHoriz(text[i])){ //skip white space at the beginning of next line let numSpaces = 0; while (this._isWhiteSpaceCharHoriz(text[i+numSpaces])) { numSpaces++; charWidths[i+numSpaces] = 0; } i += numSpaces-1; offset.x = 0; numCharsCurrenLine = numSpaces-1; }else{ numCharsCurrenLine = numCharsCurrentWord; offset.x = widthCurrentWord; } numWordsPerLine = 0; } } lineLengths.push(offset.x); charsPerLine.push(numCharsCurrenLine); //skip white space at the end let i = text.length - 1; while (this._isWhiteSpaceCharHoriz(text[i])) { lineLengths[lineLengths.length - 1] -= charWidths[i]; i--; } let charNum = 0; let maxLineLen = 0; let alignH = this.textAlignmentH; let alignV = this.textAlignmentV; offset.x = 0; if (alignH == Text2D.AlignRight || alignH == Text2D.AlignCenter) { for (let i = 0; i < lineLengths.length; i++) { if (lineLengths[i] > maxLineLen) { maxLineLen = lineLengths[i]; } } } let textHeight = lineLengths.length * lh; let offsetX = this.padding.leftPixels; if (alignH == Text2D.AlignRight) { offsetX += contentAreaWidth - maxLineLen; } else if (alignH == Text2D.AlignCenter) { offsetX += (contentAreaWidth - maxLineLen) * .5; } offset.x += Math.floor(offsetX); offset.y += contentAreaHeight + textHeight - lh; offset.y += this.padding.bottomPixels; if (alignV == Text2D.AlignBottom) { offset.y -= contentAreaHeight; }else if (alignV == Text2D.AlignCenter) { offset.y -= (contentAreaHeight - textHeight) * .5 + lineLengths.length * lh; }else { offset.y -= lineLengths.length * lh; } let lineHeight = texture.lineHeight; for (let i = 0; i < lineLengths.length; i++) { let numChars = charsPerLine[i]; let lineLength = lineLengths[i]; if (alignH == Text2D.AlignRight) { offset.x += maxLineLen - lineLength; }else if (alignH == Text2D.AlignCenter) { offset.x += (maxLineLen - lineLength) * .5; } for (let j = 0; j < numChars; j++) { let char = text[charNum]; let charWidth = charWidths[charNum]; if(char !== "\t" && !this._isWhiteSpaceCharVert(char)){ //make sure space char gets processed here or overlapping can occur when text is set let ci = texture.getChar(char); let partOffset = new Vector2(Math.floor(offset.x + ci.xOffset), Math.floor(offset.y + ci.yOffset)); this.updateInstanceDataPart(d, partOffset); d.topLeftUV = ci.topLeftUV; let suv = ci.bottomRightUV.subtract(ci.topLeftUV); d.sizeUV = suv; d.textureSize = new BABYLON.Vector2(ts.width, ts.height); d.color = this.defaultFontColor; d.superSampleFactor = superSampleFactor; //console.log(`Char: ${char}, Offset: ${partOffset}`); ++d.curElement; } offset.x += Math.floor(charWidth); charNum++; } offset.x = offsetX; offset.y -= lineHeight; } } return true; } private _isWhiteSpaceCharHoriz(char): boolean { if(char === " " || char === "\t"){ return true; } } private _isWhiteSpaceCharVert(char): boolean { if(char === "\n" || char === "\r"){ return true; } } private _updateCharCount() { let count = 0; for (let char of this._text) { if (char === "\r" || char === "\n" || char === "\t" || char < " ") { continue; } ++count; } this._charCount = count; } private _setTextAlignmentfromString(value: string) { let m = value.trim().split(","); for (let v of m) { v = v.toLocaleLowerCase().trim(); // Horizontal let i = v.indexOf("h:"); if (i === -1) { i = v.indexOf("horizontal:"); } if (i !== -1) { v = v.substr(v.indexOf(":") + 1); this._setTextAlignmentHorizontal(v); continue; } // Vertical i = v.indexOf("v:"); if (i === -1) { i = v.indexOf("vertical:"); } if (i !== -1) { v = v.substr(v.indexOf(":") + 1); this._setTextAlignmentVertical(v); continue; } } } private _setTextAlignmentHorizontal(text: string) { let v = text.trim().toLocaleLowerCase(); switch (v) { case "left": this.textAlignmentH = Text2D.AlignLeft; return; case "right": this.textAlignmentH = Text2D.AlignRight; return; case "center": this.textAlignmentH = Text2D.AlignCenter; return; } } private _setTextAlignmentVertical(text: string) { let v = text.trim().toLocaleLowerCase(); switch (v) { case "top": this.textAlignmentV = Text2D.AlignTop; return; case "bottom": this.textAlignmentV = Text2D.AlignBottom; return; case "center": this.textAlignmentV = Text2D.AlignCenter; return; } } protected _useTextureAlpha(): boolean { return this._fontSDF; } protected _shouldUseAlphaFromTexture(): boolean { return !this._fontSDF; } private _fontTexture: BaseFontTexture; private _tabulationSize: number; private _charCount: number; private _fontName: string; private _fontSuperSample: boolean; private _fontSDF: boolean; private _defaultFontColor: Color4; private _text: string; private _textSize: Size; private _wordWrap: boolean; private _textAlignment: string; private _sizeSetByUser: boolean; private _textureIsPremulAlpha: boolean; private _useBilinearFiltering: boolean; private _fontBilinearFiltering: boolean; public textAlignmentH: number; public textAlignmentV: number; } }
the_stack
import * as Boom from "@hapi/boom"; import * as Hapi from "@hapi/hapi"; import * as HapiAuthBearer from 'hapi-auth-bearer-token'; import * as Joi from "@hapi/joi"; import { Connection, PaperSelector } from "./db-connection"; import * as s2Api from "./s2-api"; import { Entity, EntityCreatePayload, EntityUpdatePayload, EntityType, Paper, PaperWithIdInfo, Paginated } from "./types/api"; import * as validation from "./types/validation"; import * as conf from "./conf"; interface ApiOptions { connection: Connection; config: conf.Config; } function firstQueryStringValue(request: Hapi.Request, name: string): string | undefined { const v = request.query[name]; return Array.isArray(v) ? v.shift() : v; } function firstIntOrDefault(request: Hapi.Request, name: string, defaultValue: number): number { const v = parseInt(firstQueryStringValue(request, name) || ""); if (isNaN(v)) { return defaultValue; } return v; } // Intended for use after validating the parameter. function parsePaperSelector(rawSelector: string): PaperSelector { return rawSelector.startsWith("arxiv:") ? { arxiv_id: rawSelector.replace("arxiv:", ""), } : { s2_id: rawSelector, }; } /** * For example usages of each route, see the unit tests. */ export const plugin = { name: "API", version: "0.0.2", register: async function (server: Hapi.Server, options: ApiOptions) { const { connection: dbConnection, config } = options; await server.register(HapiAuthBearer); server.auth.strategy('admin-token', 'bearer-access-token', { allowQueryToken: true, validate: async (request, token, h) => { const credentials = { token }; const artifacts = { }; // if no token has been set, fail all requests if(!token) { return { isValid: false, credentials, artifacts}; } const isValid = token === config.adminToken; return { isValid, credentials, artifacts }; } }); server.route({ method: "GET", path: "papers/list", handler: async (request) => { const offset = firstIntOrDefault(request, "offset", 0); const size = firstIntOrDefault(request, "size", 25); const papers = await dbConnection.getAllPapers(offset, size); const paperIds = papers.rows.map(p => p.s2_id); // We fetch metadata about each paper (it's title, author names, etc) from S2's public // API and merged them into the result set. const s2PaperInfoByPaperId: { [pid: string]: Paper } = {}; for (const s2Paper of await s2Api.getPapers(paperIds, config.s2.apiKey, false)) { if (!s2Paper) { continue; } if (s2Paper.s2Id in s2PaperInfoByPaperId) { console.warn(`Duplicate paper id: ${s2Paper.s2Id}`); continue; } s2PaperInfoByPaperId[s2Paper.s2Id] = s2Paper; } const mergedPapers: PaperWithIdInfo[] = []; for (const paper of papers.rows) { const maybeS2Paper = s2PaperInfoByPaperId[paper.s2_id]; mergedPapers.push({ ...paper, abstract: maybeS2Paper?.abstract, authors: maybeS2Paper?.authors, title: maybeS2Paper?.title, url: maybeS2Paper?.url, venue: maybeS2Paper?.venue, year: maybeS2Paper?.year, influentialCitationCount: maybeS2Paper?.influentialCitationCount, citationVelocity: maybeS2Paper?.citationVelocity }); } const response: Paginated<PaperWithIdInfo> = { ...papers, ...{ rows: mergedPapers } }; return response; }, }); server.route({ method: "GET", path: "paper/{s2Id}", handler: async (request) => { const s2Id = request.params.s2Id; try { const resp = await s2Api.getPaperUncached(s2Id, config.s2.apiKey); return resp.data; } catch (error) { switch(error.response?.status) { case 404: throw Boom.notFound(`not found: ${s2Id}`); case 500: throw Boom.internal(`S2 API Error accessing paper ${s2Id}`); default: throw Boom.internal(`Internal Error: ${error}`); } } }, options: { validate: { params: Joi.object({ s2Id: validation.s2paperId }) } } }); server.route({ method: "GET", path: "papers", handler: async (request) => { let idString; if (typeof request.query.id === "string") { idString = request.query.id; } else { idString = request.query.id.join(","); } const ids = idString.split(","); const uniqueIds = ids.filter((id, index) => { return ids.indexOf(id) === index; }); const data = (await s2Api.getPapers(uniqueIds, config.s2.apiKey)) .filter((paper) => paper !== undefined) .map((paper) => paper as Paper); return data; }, options: { validate: { query: Joi.object({ /* * Papers can be filtered using a comma-separated list of IDs. For now, ID filter is * required, as pagination over all resources hasn't been implemented. */ id: Joi.string() .pattern(/^$|[a-f0-9]{40}(,[a-f0-9]{40}){0,199}/) .required(), }), }, }, }); server.route({ method: "GET", path: "papers/{paperSelector}", handler: async (request, h) => { const paperSelector = parsePaperSelector(request.params.paperSelector); const exists = await dbConnection.checkPaper(paperSelector); return exists ? h.response().code(204) : h.response().code(404); }, options: { validate: { params: validation.paperSelector, }, }, }); server.route({ method: "GET", path: "papers/{paperSelector}/entities", handler: async (request, h) => { const paperSelector = parsePaperSelector(request.params.paperSelector); // Runtime type-checked during validation. const entityTypes = request.query.type as EntityType[]; // pretty sure Joi is actually making this a boolean, despite Hapi saying it's a string const slim = !!request.query.slim; let res: Entity[] = []; try { res = await dbConnection.getEntitiesForPaper(paperSelector, entityTypes, true, slim); } catch (e) { console.log(e); return h.response().code(500); } if (slim) { res = res.map(e => { // tags are unused, don't return them if (e.attributes.tags) { delete e.attributes.tags; } return e; }); } return { data: res }; }, options: { validate: { params: validation.paperSelector, query: Joi.object({ type: validation.apiEntityTypes, slim: Joi.boolean(), }) }, }, }); /** * The default implementation above is enormously wasteful in terms of space, * due to a quadratic blowout in identical data. * This route exists as a temporary fixture during development to dedupe data, * accomplished via surgical DB queries rather than exhaustive ones. */ server.route({ method: "GET", path: "papers/{paperSelector}/entities-deduped", handler: async (request, h) => { const paperSelector = parsePaperSelector(request.params.paperSelector); // Runtime type-checked during validation. const entityTypes = request.query.type as EntityType[]; let res; try { res = await dbConnection.getDedupedEntitiesForPaper(paperSelector, entityTypes); } catch (e) { console.log(e); return h.response().code(500); } // tags are unused, don't return them res.entities = res.entities.map(e => { if (e.attributes.tags) { delete e.attributes.tags; } return e; }); return res; }, options: { validate: { params: validation.paperSelector, query: Joi.object({ type: validation.apiEntityTypes }) }, }, }); server.route({ method: "POST", path: "papers/{arxivSelector}/entities", handler: async (request, h) => { const paperSelector = parsePaperSelector(request.params.arxivSelector); const entity = await dbConnection.createEntity( paperSelector, (request.payload as EntityCreatePayload).data ); return h.response({ data: entity }).code(201); }, options: { validate: { params: validation.arxivOnlySelector, payload: validation.entityPost, }, }, }); server.route({ method: "PATCH", path: "papers/{arxivSelector}/entities/{id}", handler: async (request, h) => { await dbConnection.updateEntity( (request.payload as EntityUpdatePayload).data ); return h.response({}).code(204); }, options: { auth: 'admin-token', validate: { params: validation.arxivOnlySelector.append({ id: Joi.string().required(), }), payload: validation.entityPatch, }, }, }); server.route({ method: "DELETE", path: "papers/{arxivSelector}/entities/{id}", handler: async (request, h) => { const { id } = request.params; await dbConnection.deleteEntity(id); return h.response().code(204); }, options: { auth: 'admin-token', validate: { params: validation.arxivOnlySelector.append({ id: Joi.string().required(), }), }, }, }); server.route({ method: "GET", path: "papers/{arxivSelector}/version", handler: async (request, h) => { const paperSelector = parsePaperSelector(request.params.arxivSelector); const version = await dbConnection.getLatestProcessedArxivVersion(paperSelector); const citationCount = version !== null ? await dbConnection.getPaperEntityCount(paperSelector, 'citation'): null; if(citationCount && citationCount > 0) { return h.response({ version }).code(200); } else { // We don't have version info for this ID, or no citations were extracted so we consider // it unsuccessfully processed. return h.response().code(404); } }, options: { validate: { params: validation.arxivOnlySelector, }, }, }); }, };
the_stack
import { DinoContainer, IDinoContainerConfig, DIContainer, RouteTable, ObjectUtility, DinoUtility, RequestStartMiddleware, IRouteTable, DinoErrorController, ControllerAction, DinoController, RequestEndMiddleware, ErrorMiddleware, Constants, IActionMethodAttribute, AppStartMiddleware } from '../../index'; describe('modules.core.dino.container.spec', () => { it('resolve.dino_properties_undefined', () => { let config: IDinoContainerConfig = { enableTaskContext: false } as any; spyOn(DIContainer, 'create').and.callFake(() => { return { resolve: m => { expect(m).toBe(String); return 'resolved'; } }; }); spyOn(RouteTable, 'create').and.callFake(() => null); spyOn(ObjectUtility, 'replaceObjectReferences').and.callFake(() => 'replaced'); let dinoContainer = new DinoContainer(config); let obj = dinoContainer.resolve(String, undefined); // following expects are common for every constructor execution // do not delete these test case expect(RouteTable.create).toHaveBeenCalledTimes(1); expect(DIContainer.create).toHaveBeenCalledTimes(1); expect(obj).toBe('resolved'); expect(ObjectUtility.replaceObjectReferences).toHaveBeenCalledTimes(0); }); it('resolve.dino_properties_null', () => { let config: IDinoContainerConfig = { enableTaskContext: false } as any; spyOn(DIContainer, 'create').and.callFake(() => { return { resolve: m => { expect(m).toBe(String); return 'resolved'; } }; }); spyOn(RouteTable, 'create').and.callFake(() => null); spyOn(ObjectUtility, 'replaceObjectReferences').and.callFake(() => 'replaced'); let dinoContainer = new DinoContainer(config); let obj = dinoContainer.resolve(String, undefined); // following expects are common for every constructor execution // do not delete these test case expect(RouteTable.create).toHaveBeenCalledTimes(1); expect(DIContainer.create).toHaveBeenCalledTimes(1); expect(obj).toBe('resolved'); expect(ObjectUtility.replaceObjectReferences).toHaveBeenCalledTimes(0); }); it('resolve.enableTaskContext_false', () => { let config: IDinoContainerConfig = { enableTaskContext: false } as any; spyOn(DIContainer, 'create').and.callFake(() => { return { resolve: m => { expect(m).toBe(String); return 'resolved'; } }; }); spyOn(RouteTable, 'create').and.callFake(() => null); spyOn(ObjectUtility, 'replaceObjectReferences').and.callFake(() => 'replaced'); let dinoContainer = new DinoContainer(config); let obj = dinoContainer.resolve(String, { context: 'test' }); // following expects are common for every constructor execution // do not delete these test case expect(RouteTable.create).toHaveBeenCalledTimes(1); expect(DIContainer.create).toHaveBeenCalledTimes(1); expect(obj).toBe('resolved'); expect(ObjectUtility.replaceObjectReferences).toHaveBeenCalledTimes(0); }); it('resolve.enableTaskContext_true', () => { let config: IDinoContainerConfig = { enableTaskContext: true } as any; spyOn(DIContainer, 'create').and.callFake(() => { return { resolve: m => { expect(m).toBe(String); return 'resolved'; } }; }); spyOn(RouteTable, 'create').and.callFake(() => null); spyOn(ObjectUtility, 'replaceObjectReferences').and.callFake(() => 'replaced'); let dinoContainer = new DinoContainer(config); let obj = dinoContainer.resolve(String, { context: 'test' }); expect(obj).toBe('replaced'); }); it('static_create.invoke_constructor', () => { let config: IDinoContainerConfig = {} as any; spyOn(DIContainer, 'create').and.callFake(() => null); spyOn(RouteTable, 'create').and.callFake(() => null); let dinoContainer = DinoContainer.create(config); expect(dinoContainer instanceof DinoContainer).toBeTruthy(); }); it('routeNotFoundMiddleware.when_isSyncRequestStartMiddleware_true', () => { const _req = { req: 'uri' }; const _res = { res: 'express' }; const _next = () => null; class RoutNotFoundMiddlewareFake extends RequestStartMiddleware { constructor (route: IRouteTable) { super(); expect(route).toBeNull(); } invoke(req, res, next): void { expect(req).toBe(_req); expect(res).toBe(_res); expect(next()).toBeNull(); } } let callback; let config: IDinoContainerConfig = { baseUri: 'testuri', app: { use: (uri, cb) => { expect(uri).toBe('testuri'); callback = cb; } } } as any; spyOn(DIContainer, 'create').and.callFake(() => null); spyOn(RouteTable, 'create').and.callFake(() => null); spyOn(DinoUtility, 'isSyncRequestStartMiddleware') .and.callFake(m => { expect(m).toBe(RoutNotFoundMiddlewareFake); return true; }); let dinoContainer = new DinoContainer(config); dinoContainer.routeNotFoundMiddleware(RoutNotFoundMiddlewareFake); expect(DinoUtility.isSyncRequestStartMiddleware).toHaveBeenCalledTimes(1); callback(_req, _res, _next); }); it('routeNotFoundMiddleware.when_isSyncRequestStartMiddleware_false', () => { let callback; let config: IDinoContainerConfig = {} as any; spyOn(DIContainer, 'create').and.callFake(() => null); spyOn(RouteTable, 'create').and.callFake(() => null); spyOn(DinoUtility, 'isSyncRequestStartMiddleware') .and.callFake(m => { expect(m).toBe(Function); return false; }); let dinoContainer = new DinoContainer(config); dinoContainer.routeNotFoundMiddleware(Function); expect(callback).toBeUndefined(); expect(DinoUtility.isSyncRequestStartMiddleware).toHaveBeenCalledTimes(1); }); it('builtInRequestStartMiddleWare.when_isSyncRequestStartMiddleware_true', () => { const _req = { req: 'uri' }; const _res = { res: 'express' }; const _next = () => null; class RequestStartFake extends RequestStartMiddleware { invoke(req, res, next): void { expect(req).toBe(_req); expect(res).toBe(_res); expect(next()).toBeNull(); } } let callback; let config: IDinoContainerConfig = { baseUri: 'testuri', app: { use: (uri, cb) => { expect(uri).toBe('testuri'); callback = cb; } } } as any; spyOn(DIContainer, 'create').and.callFake(() => null); spyOn(RouteTable, 'create').and.callFake(() => null); spyOn(DinoUtility, 'isSyncRequestStartMiddleware') .and.callFake(m => { expect(m).toBe(RequestStartFake); return true; }); let dinoContainer = new DinoContainer(config); dinoContainer.builtInRequestStartMiddleware(RequestStartFake); expect(DinoUtility.isSyncRequestStartMiddleware).toHaveBeenCalledTimes(1); callback(_req, _res, _next); }); it('builtInRequestStartMiddleWare.when_isSyncRequestStartMiddleware_false', () => { let callback; let config: IDinoContainerConfig = {} as any; spyOn(DIContainer, 'create').and.callFake(() => null); spyOn(RouteTable, 'create').and.callFake(() => null); spyOn(DinoUtility, 'isSyncRequestStartMiddleware') .and.callFake(m => { expect(m).toBe(Function); return false; }); let dinoContainer = new DinoContainer(config); dinoContainer.builtInRequestStartMiddleware(Function); expect(callback).toBeUndefined(); expect(DinoUtility.isSyncRequestStartMiddleware).toHaveBeenCalledTimes(1); }); it('appStartMiddleware.when_isSyncAppStartMiddleware_true', () => { let invoked = false; class AppStartFake extends AppStartMiddleware { invoke(): void { invoked = true; } } let obj = new AppStartFake(); spyOn(DIContainer, 'create').and.callFake(() => null); spyOn(RouteTable, 'create').and.callFake(() => null); spyOn(DinoUtility, 'isSyncAppStartMiddleware') .and.callFake(m => { expect(m).toBe(AppStartFake); return true; }); let dinoContainer = new DinoContainer({} as any); spyOn(dinoContainer, 'resolve').and.callFake(() => obj); dinoContainer.appStartMiddleware(AppStartFake); expect(DinoUtility.isSyncAppStartMiddleware).toHaveBeenCalledTimes(1); expect(invoked).toBeTruthy(); }); it('appStartMiddleware.when_isSyncAppStartMiddleware_false', () => { let config: IDinoContainerConfig = {} as any; spyOn(DIContainer, 'create').and.callFake(() => null); spyOn(RouteTable, 'create').and.callFake(() => null); spyOn(DinoUtility, 'isSyncAppStartMiddleware') .and.callFake(m => false); let dinoContainer = new DinoContainer(config); dinoContainer.appStartMiddleware(Function); expect(DinoUtility.isSyncAppStartMiddleware).toHaveBeenCalledTimes(1); }); it('builtInRequestEndMiddleWare.when_isSyncRequestEndMiddleware_true', () => { const _req = { req: 'uri' }; const _res = { locals: { dino: { result: 'express' } } }; const _next = () => null; class RequestEndFake extends RequestEndMiddleware { invoke(req, res, next): void { expect(req).toBe(_req); expect(res).toBe(_res); expect(next()).toBeNull(); } } let callback; let config: IDinoContainerConfig = { baseUri: 'testuri', app: { use: (uri, cb) => { expect(uri).toBe('testuri'); callback = cb; } } } as any; spyOn(DIContainer, 'create').and.callFake(() => null); spyOn(RouteTable, 'create').and.callFake(() => null); spyOn(DinoUtility, 'isSyncRequestEndMiddleware') .and.callFake(m => { expect(m).toBe(RequestEndFake); return true; }); let dinoContainer = new DinoContainer(config); dinoContainer.builtInRequestEndMiddleware(RequestEndFake); callback(_req, _res, _next); expect(DinoUtility.isSyncRequestEndMiddleware).toHaveBeenCalledTimes(1); }); it('builtInRequestEndMiddleWare.when_isSyncRequestEndMiddleware_false', () => { let callback; let config: IDinoContainerConfig = { baseUri: 'testuri', app: { use: (uri, cb) => { expect(uri).toBe('testuri'); callback = cb; } } } as any; spyOn(DIContainer, 'create').and.callFake(() => null); spyOn(RouteTable, 'create').and.callFake(() => null); spyOn(DinoUtility, 'isSyncRequestEndMiddleware') .and.callFake(m => false); let dinoContainer = new DinoContainer(config); dinoContainer.builtInRequestEndMiddleware(Function); expect(callback).toBeUndefined(); expect(DinoUtility.isSyncRequestEndMiddleware).toHaveBeenCalledTimes(1); }); it('builtInErrorMiddleWare.when_isSyncErrorMiddleware_true', () => { const _req = { req: 'uri' }; const _res = { res: 'express' }; const _err = new Error('testerror'); const _next = () => null; class ErrorFake extends ErrorMiddleware { invoke(err, req, res, next): void { expect(err).toBe(_err); expect(req).toBe(_req); expect(res).toBe(_res); expect(next()).toBeNull(); } } let callback; let config: IDinoContainerConfig = { baseUri: 'testuri', app: { use: (uri, cb) => { expect(uri).toBe('testuri'); callback = cb; } } } as any; spyOn(DIContainer, 'create').and.callFake(() => null); spyOn(RouteTable, 'create').and.callFake(() => null); spyOn(DinoUtility, 'isSyncErrorMiddleware') .and.callFake(m => { expect(m).toBe(ErrorFake); return true; }); let dinoContainer = new DinoContainer(config); dinoContainer.builtInErrorMiddleware(ErrorFake); callback(_err, _req, _res, _next); expect(DinoUtility.isSyncErrorMiddleware).toHaveBeenCalledTimes(1); }); it('builtInErrorMiddleWare.when_isSyncErrorMiddleware_false', () => { let callback; let config: IDinoContainerConfig = { baseUri: 'testuri', app: { use: (uri, cb) => { expect(uri).toBe('testuri'); callback = cb; } } } as any; spyOn(DIContainer, 'create').and.callFake(() => null); spyOn(RouteTable, 'create').and.callFake(() => null); spyOn(DinoUtility, 'isSyncErrorMiddleware') .and.callFake(m => false); let dinoContainer = new DinoContainer(config); dinoContainer.builtInErrorMiddleware(Function); expect(callback).toBeUndefined(); expect(DinoUtility.isSyncErrorMiddleware).toHaveBeenCalledTimes(1); }); it('requestStartMiddleWare.when_isSyncRequestStartMiddleware', () => { let invoked = false; let callback; let request = { path: 'test' }; let config: IDinoContainerConfig = { baseUri: 'testuri', app: { use: (uri, cb) => { expect(uri).toBe('testuri'); callback = cb; } } } as any; let res = { locals: { dino: 45 } }; spyOn(DIContainer, 'create').and.callFake(() => null); spyOn(RouteTable, 'create').and.callFake(() => null); spyOn(DinoUtility, 'isSyncRequestStartMiddleware').and.callFake(() => true); let dinoContainer = new DinoContainer(config); // Spy on the same object method itself spyOn(dinoContainer, 'resolve') .and.callFake((middleware, dino) => { expect(middleware).toBe(String); expect(dino).toBe(res.locals.dino); return { invoke: (req, resp, next) => { expect(req).toBe(request); expect(resp).toBe(res); expect(next()).toBe('invoked'); invoked = true; } }; }); dinoContainer.requestStartMiddleware(String); callback(request, res, () => 'invoked'); expect(DinoUtility.isSyncRequestStartMiddleware).toHaveBeenCalledTimes(1); expect(dinoContainer.resolve).toHaveBeenCalledTimes(1); expect(invoked).toBeTruthy(); }); it('requestStartMiddleWare.when_isAsyncRequestStartMiddleware', async () => { let invoked = false; let callback; let request = { path: 'test' }; let config: IDinoContainerConfig = { baseUri: 'testuri', app: { use: (uri, cb) => { expect(uri).toBe('testuri'); callback = cb; } } } as any; let res = { locals: { dino: 45 } }; spyOn(DinoUtility, 'isSyncRequestStartMiddleware').and.callFake(() => false); spyOn(DinoUtility, 'isAsyncRequestStartMiddleware').and.callFake(() => true); spyOn(DIContainer, 'create').and.callFake(() => null); spyOn(RouteTable, 'create').and.callFake(() => null); let dinoContainer = new DinoContainer(config); // Spy on the same object method itself spyOn(dinoContainer, 'resolve') .and.callFake((middleware, dino) => { expect(middleware).toBe(String); expect(dino).toBe(res.locals.dino); return { invoke: (req, resp, next) => { expect(req).toBe(request); expect(resp).toBe(res); expect(next()).toBe('invoked'); invoked = true; } }; }); dinoContainer.requestStartMiddleware(String); await callback(request, res, () => 'invoked'); expect(DinoUtility.isSyncRequestStartMiddleware).toHaveBeenCalledTimes(1); expect(DinoUtility.isAsyncRequestStartMiddleware).toHaveBeenCalledTimes(1); expect(dinoContainer.resolve).toHaveBeenCalledTimes(1); expect(invoked).toBeTruthy(); }); it('requestStartMiddleWare.throwsError_when_isAsyncRequestStartMiddleware', async () => { let err; let callback; let request = { path: 'test' }; let config: IDinoContainerConfig = { baseUri: 'testuri', app: { use: (uri, cb) => { expect(uri).toBe('testuri'); callback = cb; } } } as any; let res = { locals: { dino: 45 } }; spyOn(DinoUtility, 'isSyncRequestStartMiddleware').and.callFake(() => false); spyOn(DinoUtility, 'isAsyncRequestStartMiddleware').and.callFake(() => true); spyOn(DIContainer, 'create').and.callFake(() => null); spyOn(RouteTable, 'create').and.callFake(() => null); let dinoContainer = new DinoContainer(config); // Spy on the same object method itself spyOn(dinoContainer, 'resolve') .and.callFake((middleware, dino) => { expect(middleware).toBe(String); expect(dino).toBe(res.locals.dino); return { invoke: (req, resp, next) => { expect(req).toBe(request); expect(resp).toBe(res); throw new Error('TestError'); } }; }); dinoContainer.requestStartMiddleware(String); await callback(request, res, e => err = e); expect(DinoUtility.isSyncRequestStartMiddleware).toHaveBeenCalledTimes(1); expect(DinoUtility.isAsyncRequestStartMiddleware).toHaveBeenCalledTimes(1); expect(err).toEqual(new Error('TestError')); }); it('requestStartMiddleWare.when_not_a_RequestStartMiddleware', () => { let callback; let config: IDinoContainerConfig = { baseUri: 'testuri', app: { use: (uri, cb) => { expect(uri).toBe('testuri'); callback = cb; } } } as any; spyOn(DinoUtility, 'isSyncRequestStartMiddleware').and.callFake(() => false); spyOn(DinoUtility, 'isAsyncRequestStartMiddleware').and.callFake(() => false); spyOn(DIContainer, 'create').and.callFake(() => null); spyOn(RouteTable, 'create').and.callFake(() => null); let dinoContainer = new DinoContainer(config); dinoContainer.requestStartMiddleware(String); expect(callback).toBeUndefined(); expect(DinoUtility.isSyncRequestStartMiddleware).toHaveBeenCalledTimes(1); expect(DinoUtility.isAsyncRequestStartMiddleware).toHaveBeenCalledTimes(1); }); it('requestEndMiddleWare.when_isSyncRequestEndMiddleware', () => { let invoked = false; let callback; let request = { path: 'test' }; let config: IDinoContainerConfig = { baseUri: 'testuri', app: { use: (uri, cb) => { expect(uri).toBe('testuri'); callback = cb; } } } as any; let requestEndProps = { result: 45 }; let res = { locals: { dino: requestEndProps } }; spyOn(DinoUtility, 'isSyncRequestEndMiddleware').and.callFake(() => true); spyOn(DIContainer, 'create').and.callFake(() => null); spyOn(RouteTable, 'create').and.callFake(() => null); let dinoContainer = new DinoContainer(config); // Spy on the same object method itself spyOn(dinoContainer, 'resolve') .and.callFake((middleware, dino) => { expect(middleware).toBe(String); expect(dino).toBe(res.locals.dino); return { invoke: (req, resp, next, result, endProps) => { expect(req).toBe(request); expect(resp).toBe(res); expect(next()).toBe('invoked'); expect(result).toBe(requestEndProps.result); expect(endProps).toBe(res.locals.dino); invoked = true; } }; }); dinoContainer.requestEndMiddleware(String); callback(request, res, () => 'invoked'); expect(DinoUtility.isSyncRequestEndMiddleware).toHaveBeenCalledTimes(1); expect(invoked).toBeTruthy(); }); it('requestEndMiddleWare.when_isAsyncRequestEndMiddleware', async () => { let invoked = false; let callback; let request = { path: 'test' }; let config: IDinoContainerConfig = { baseUri: 'testuri', app: { use: (uri, cb) => { expect(uri).toBe('testuri'); callback = cb; } } } as any; let requestEndProps = { result: 45 }; let res = { locals: { dino: requestEndProps } }; spyOn(DinoUtility, 'isSyncRequestEndMiddleware').and.callFake(() => false); spyOn(DinoUtility, 'isAsyncRequestEndMiddleware').and.callFake(() => true); spyOn(DIContainer, 'create').and.callFake(() => null); spyOn(RouteTable, 'create').and.callFake(() => null); let dinoContainer = new DinoContainer(config); // Spy on the same object method itself spyOn(dinoContainer, 'resolve') .and.callFake((middleware, dino) => { expect(middleware).toBe(String); expect(dino).toBe(res.locals.dino); return { invoke: (req, resp, next, result, endProps) => { expect(req).toBe(request); expect(resp).toBe(res); expect(next()).toBe('invoked'); expect(result).toBe(requestEndProps.result); expect(endProps).toBe(res.locals.dino); invoked = true; } }; }); dinoContainer.requestEndMiddleware(String); await callback(request, res, () => 'invoked'); expect(DinoUtility.isSyncRequestEndMiddleware).toHaveBeenCalledTimes(1); expect(DinoUtility.isAsyncRequestEndMiddleware).toHaveBeenCalledTimes(1); expect(invoked).toBeTruthy(); }); it('requestEndMiddleWare.throwsError_when_isAsyncRequestEndMiddleware', async () => { let err; let callback; let request = { path: 'test' }; let config: IDinoContainerConfig = { baseUri: 'testuri', app: { use: (uri, cb) => { expect(uri).toBe('testuri'); callback = cb; } } } as any; let res = { locals: { dino: 45 } }; spyOn(DinoUtility, 'isSyncRequestEndMiddleware').and.callFake(() => false); spyOn(DinoUtility, 'isAsyncRequestEndMiddleware').and.callFake(() => true); spyOn(DIContainer, 'create').and.callFake(() => null); spyOn(RouteTable, 'create').and.callFake(() => null); let dinoContainer = new DinoContainer(config); // Spy on the same object method itself spyOn(dinoContainer, 'resolve') .and.callFake((middleware, dino) => { expect(middleware).toBe(String); expect(dino).toBe(res.locals.dino); return { invoke: (req, resp, next) => { expect(req).toBe(request); expect(resp).toBe(res); throw new Error('TestError'); } }; }); dinoContainer.requestEndMiddleware(String); await callback(request, res, e => err = e); expect(DinoUtility.isSyncRequestEndMiddleware).toHaveBeenCalledTimes(1); expect(DinoUtility.isAsyncRequestEndMiddleware).toHaveBeenCalledTimes(1); expect(err).toEqual(new Error('TestError')); }); it('requestEndMiddleWare.when_not_a_RequestEndMiddleware', () => { let callback; let config: IDinoContainerConfig = { baseUri: 'testuri', app: { use: (uri, cb) => { expect(uri).toBe('testuri'); callback = cb; } } } as any; spyOn(DinoUtility, 'isSyncRequestEndMiddleware').and.callFake(() => false); spyOn(DinoUtility, 'isAsyncRequestEndMiddleware').and.callFake(() => false); spyOn(DIContainer, 'create').and.callFake(() => null); spyOn(RouteTable, 'create').and.callFake(() => null); let dinoContainer = new DinoContainer(config); dinoContainer.requestEndMiddleware(String); expect(callback).toBeUndefined(); expect(DinoUtility.isSyncRequestEndMiddleware).toHaveBeenCalledTimes(1); expect(DinoUtility.isAsyncRequestEndMiddleware).toHaveBeenCalledTimes(1); }); it('registerErrorMiddleWare.when_isSyncErrorMiddleware', () => { let invoked = false; let callback; let request = { path: 'test' }; let config: IDinoContainerConfig = { baseUri: 'testuri', app: { use: (uri, cb) => { expect(uri).toBe('testuri'); callback = cb; } } } as any; let res = { locals: { dino: 45 } }; spyOn(DinoUtility, 'isSyncErrorMiddleware').and.callFake(() => true); spyOn(DIContainer, 'create').and.callFake(() => null); spyOn(RouteTable, 'create').and.callFake(() => null); let dinoContainer = new DinoContainer(config); // Spy on the same object method itself spyOn(dinoContainer, 'resolve') .and.callFake((middleware, dino) => { expect(middleware).toBe(String); expect(dino).toBe(res.locals.dino); return { invoke: (err, req, resp, next) => { expect(err).toEqual(new Error('TestError')); expect(req).toBe(request); expect(resp).toBe(res); expect(next()).toBe('invoked'); invoked = true; } }; }); dinoContainer.registerErrorMiddleware(String); callback(new Error('TestError'), request, res, () => 'invoked'); expect(DinoUtility.isSyncErrorMiddleware).toHaveBeenCalledTimes(1); expect(invoked).toBeTruthy(); }); it('registerErrorMiddleWare.when_isAsyncErrorMiddleware', async () => { let invoked = false; let callback; let request = { path: 'test' }; let config: IDinoContainerConfig = { baseUri: 'testuri', app: { use: (uri, cb) => { expect(uri).toBe('testuri'); callback = cb; } } } as any; let res = { locals: { dino: 45 } }; spyOn(DinoUtility, 'isSyncErrorMiddleware').and.callFake(() => false); spyOn(DinoUtility, 'isAsyncErrorMiddleware').and.callFake(() => true); spyOn(DIContainer, 'create').and.callFake(() => null); spyOn(RouteTable, 'create').and.callFake(() => null); let dinoContainer = new DinoContainer(config); // Spy on the same object method itself spyOn(dinoContainer, 'resolve') .and.callFake((middleware, dino) => { expect(middleware).toBe(String); expect(dino).toBe(res.locals.dino); return { invoke: (err, req, resp, next) => { expect(err).toEqual(new Error('TestError')); expect(req).toBe(request); expect(resp).toBe(res); expect(next()).toBe('invoked'); invoked = true; } }; }); dinoContainer.registerErrorMiddleware(String); await callback(new Error('TestError'), request, res, () => 'invoked'); expect(DinoUtility.isAsyncErrorMiddleware).toHaveBeenCalledTimes(1); expect(DinoUtility.isSyncErrorMiddleware).toHaveBeenCalledTimes(1); expect(invoked).toBeTruthy(); }); it('registerErrorMiddleWare.throwsError_when_isAsyncErrorMiddleware', async () => { let err; let callback; let request = { path: 'test' }; let config: IDinoContainerConfig = { baseUri: 'testuri', app: { use: (uri, cb) => { expect(uri).toBe('testuri'); callback = cb; } } } as any; let res = { locals: { dino: 45 } }; spyOn(DinoUtility, 'isSyncErrorMiddleware').and.callFake(() => false); spyOn(DinoUtility, 'isAsyncErrorMiddleware').and.callFake(() => true); spyOn(DIContainer, 'create').and.callFake(() => null); spyOn(RouteTable, 'create').and.callFake(() => null); let dinoContainer = new DinoContainer(config); // Spy on the same object method itself spyOn(dinoContainer, 'resolve') .and.callFake((middleware, dino) => { expect(middleware).toBe(String); expect(dino).toBe(res.locals.dino); return { invoke: (err, req, resp, next) => { expect(err).toEqual(new Error('TestError')); expect(req).toBe(request); expect(resp).toBe(res); throw new Error('TestErrorThrown'); } }; }); dinoContainer.registerErrorMiddleware(String); await callback(new Error('TestError'), request, res, e => err = e); expect(DinoUtility.isAsyncErrorMiddleware).toHaveBeenCalledTimes(1); expect(DinoUtility.isSyncErrorMiddleware).toHaveBeenCalledTimes(1); expect(err).toEqual(new Error('TestErrorThrown')); }); it('registerErrorMiddleWare.when_not_a_ErrorMiddleware', () => { let callback; let config: IDinoContainerConfig = { baseUri: 'testuri', app: { use: (uri, cb) => { expect(uri).toBe('testuri'); callback = cb; } } } as any; spyOn(DinoUtility, 'isSyncErrorMiddleware').and.callFake(() => false); spyOn(DinoUtility, 'isAsyncErrorMiddleware').and.callFake(() => false); spyOn(DIContainer, 'create').and.callFake(() => null); spyOn(RouteTable, 'create').and.callFake(() => null); let dinoContainer = new DinoContainer(config); dinoContainer.registerErrorMiddleware(String); expect(callback).toBeUndefined(); expect(DinoUtility.isSyncErrorMiddleware).toHaveBeenCalledTimes(1); expect(DinoUtility.isAsyncErrorMiddleware).toHaveBeenCalledTimes(1); }); it('registerErrorController.when_isErrorController', () => { let patch; let invoked; let callback; let request = { path: 'test' }; let config: IDinoContainerConfig = { baseUri: 'testuri', app: { use: (uri, cb) => { expect(uri).toBe('testuri'); callback = cb; } } } as any; let res = { locals: { dino: 45 } }; spyOn(DIContainer, 'create').and.callFake(() => null); spyOn(RouteTable, 'create').and.callFake(() => null); spyOn(DinoUtility, 'isErrorController').and.callFake(() => true); spyOn(DinoErrorController, 'create').and.callFake(a => { expect(a).toEqual({ api: true }); return { patch: (err, req, resp, next) => { expect(err).toEqual(new Error('TestError')); expect(req).toBe(request); expect(resp).toBe(res); expect(next()).toBe('invoked'); patch = true; }, invoke: method => { expect(method).toBe(Constants.errControllerDefaultMethod); invoked = true; } }; }); let dinoContainer = new DinoContainer(config); // Spy on the same object method itself spyOn(dinoContainer, 'resolve') .and.callFake((middleware, dino) => { expect(middleware).toBe(String); expect(dino).toBe(res.locals.dino); return { api: true }; }); dinoContainer.registerErrorController(String); callback(new Error('TestError'), request, res, () => 'invoked'); expect(DinoUtility.isErrorController).toHaveBeenCalledTimes(1); expect(patch).toBeTruthy(); expect(invoked).toBeTruthy(); }); it('registerErrorController.when_not_anErrorController', () => { let callback; let config: IDinoContainerConfig = { baseUri: 'testuri', app: { use: (uri, cb) => { expect(uri).toBe('testuri'); callback = cb; } } } as any; spyOn(DinoUtility, 'isErrorController').and.callFake(() => false); spyOn(DIContainer, 'create').and.callFake(() => null); spyOn(RouteTable, 'create').and.callFake(() => null); let dinoContainer = new DinoContainer(config); dinoContainer.registerErrorController(String); expect(callback).toBeUndefined(); expect(DinoUtility.isErrorController).toHaveBeenCalledTimes(1); }); it('setUpDinoController.verify_values', () => { let config: IDinoContainerConfig = {} as any; let res: any = { locals: { dino: 45 } }; let dinoController: DinoController = { ctx: true } as any; let action: IActionMethodAttribute = { sendsResponse: false }; let _bindmodel = {}; spyOn(ControllerAction, 'create') .and.callFake((actionAttr: IActionMethodAttribute) => { expect(actionAttr.sendsResponse).toBe(action.sendsResponse); return 'testAction'; }); spyOn(DinoController, 'create').and.callFake( (api, action) => { expect(action).toBe('testAction'); expect(api).toBe('resolved'); return dinoController; }); spyOn(DIContainer, 'create').and.callFake((a, b) => null); spyOn(RouteTable, 'create').and.callFake(() => null); let dinoContainer = new DinoContainer(config); // Spy on the same object method itself spyOn(dinoContainer, 'resolve') .and.callFake((middleware, dino) => { expect(middleware).toBe(String); expect(dino).toBe(res.locals.dino); return 'resolved'; }); let obj = dinoContainer .setUpDinoController(String, action, res); expect(ControllerAction.create).toHaveBeenCalledTimes(1); expect(DinoController.create).toHaveBeenCalledTimes(1); expect(dinoContainer.resolve).toHaveBeenCalledTimes(1); expect(obj).toBe(dinoController); }); });
the_stack
import * as Fs from 'fs' import * as Path from 'path' import { Glob } from 'glob' import { dialog } from 'electron' import { v4 as uuid } from 'uuid' import { findIndex, omit } from 'lodash' import { ApplicationWindow } from '@main/application-window' import { Frameworks } from '@lib/frameworks' import { ProjectEventEmitter } from '@lib/frameworks/emitter' import { FrameworkStatus, parseFrameworkStatus } from '@lib/frameworks/status' import { ProgressLedger } from '@lib/frameworks/progress' import { FrameworkFactory } from '@lib/frameworks/factory' import { FrameworkOptions, IFramework } from '@lib/frameworks/framework' /** * Options to instantiate a Project with. */ export type RepositoryOptions = { id?: string, name?: string path: string expanded?: boolean frameworks?: Array<FrameworkOptions> status?: FrameworkStatus } /** * Standardised repository information (e.g. used for scanning * for test frameworks). */ export type ParsedRepository = { path: string files: Array<string> } export interface IRepository extends ProjectEventEmitter { frameworks: Array<IFramework> status: FrameworkStatus selected: boolean scanning: boolean getId (): string getDisplayName (): string start (): void refresh (): void stop (): Promise<any> reset (): Promise<any> save (): void scan (): Promise<Array<FrameworkOptions>> expand (): void collapse (): void isRunning (): boolean isRefreshing (): boolean isBusy (): boolean empty (): boolean count (): number isExpanded (): boolean render (): RepositoryOptions persist (): RepositoryOptions addFramework (options: FrameworkOptions): Promise<IFramework> removeFramework (id: string): void getFrameworkById (id: string): IFramework | undefined getPath (): string exists (): Promise<boolean> locate (window: Electron.BrowserWindow): Promise<void> getProgressLedger (): ProgressLedger resetProgressLedger (): void emitFrameworksToRenderer (): void } export class Repository extends ProjectEventEmitter implements IRepository { public frameworks: Array<IFramework> = [] public status: FrameworkStatus = 'loading' public selected = false public scanning = false protected id: string protected path: string protected name: string protected expanded: boolean protected parsed = false protected ready = false protected initialFrameworkCount = 0 protected initialFrameworkReady = 0 protected progressLedger: ProgressLedger = { run: 0, total: 0 } constructor (window: ApplicationWindow, options: RepositoryOptions) { super(window) this.id = options.id || uuid() this.path = options.path this.name = options.name || Path.basename(this.path) || 'untitled' this.expanded = typeof options.expanded === 'undefined' ? true : options.expanded this.initialFrameworkCount = (options.frameworks || []).length this.exists() // If options include frameworks already (i.e. persisted state), add them. this.loadFrameworks(options.frameworks || []) } /** * Run all of this repository's test frameworks. */ public start (): void { this.frameworks.forEach((framework: IFramework) => { framework.start() }) } /** * Refresh all of this repository's test frameworks. */ public refresh (): void { this.frameworks.forEach((framework: IFramework) => { framework.refresh() }) } /** * Stop any test framework in this repository that might be running. */ public stop (): Promise<any> { return Promise.all(this.frameworks.map((framework: IFramework): Promise<void> => { return new Promise(async (resolve, reject) => { await framework.stop() resolve() }) })) } /** * Reset this repository's state. */ public async reset (): Promise<any> { return Promise.all(this.frameworks.map((framework: IFramework) => { return framework.reset() })) } /** * Whether this repository is running. */ public isRunning (): boolean { return this.frameworks.some((framework: IFramework) => framework.isRunning()) } /** * Whether this repository is refreshing. */ public isRefreshing (): boolean { return this.frameworks.some((framework: IFramework) => framework.isRefreshing()) } /** * Whether this repository is busy. */ public isBusy (): boolean { return this.frameworks.some((framework: IFramework) => framework.isBusy()) } /** * How many frameworks the repository currently has. */ public count (): number { return this.frameworks.length } /** * Whether this repository has any frameworks. */ public empty (): boolean { return this.count() === 0 } /** * Whether this repository is expanded. */ public isExpanded (): boolean { return this.expanded } /** * Prepares the repository for sending out to renderer process. */ public render (): RepositoryOptions { return { id: this.id, name: this.name, path: this.path, status: this.status, expanded: this.expanded } } /** * Prepares the repository for persistence. */ public persist (): RepositoryOptions { return omit({ ...this.render(), frameworks: this.frameworks.map(framework => framework.persist()) }, 'status') } /** * Save this repository in the persistent store. */ public save (): void { this.emit('change') } /** * Scan the repository folder for testing frameworks. */ public async scan (): Promise<Array<FrameworkOptions>> { this.scanning = true const glob = new Glob('*', { cwd: this.path, dot: true, sync: true }) return new Promise(async (resolve, reject) => { const frameworks: Array<FrameworkOptions | false> = await Promise.all(Frameworks.map(framework => { return framework.spawnForDirectory({ path: this.path, files: glob.found }) })) resolve(frameworks.filter(options => !!options).map(options => { return <FrameworkOptions>{ ...options, scanStatus: 'pending' } })) this.scanning = false }) } /** * Get this repository's id. */ public getId (): string { return this.id } /** * Get this repository's display name. */ public getDisplayName (): string { return this.name } /** * Expand this repository. */ public expand (): void { this.expanded = true this.emit('change', this) } /** * Collapse this repository. */ public collapse (): void { this.expanded = false this.emit('change', this) } /** * A function to run when a child framework changes its status. */ protected statusListener (): void { this.updateStatus() } /** * A function to run when a child framework changes its state (i.e. runs, stops, etc). */ protected stateListener (): void { // Cascade the event up to the project. this.emit('state') } /** * A function to run when a child framework changes. */ protected changeListener (): void { this.save() } /** * A function to run when a child framework errors out. */ protected errorListener (): void { this.exists() } /** * A function to run when a child framework starts measuring progress. */ protected measuringListener (frameworkLedger: ProgressLedger): void { this.progressLedger.total += frameworkLedger.total } /** * A function to run when a child framework progresses. */ protected progressListener (): void { this.progress() } /** * Prepare the repository for parsed state. */ protected onParsed (): void { this.parsed = true if (!this.initialFrameworkCount) { this.onReady() } this.emit('parsed', this) } /** * Prepare the repository for ready state. */ protected onReady (): void { // Ready event will only trigger once. if (this.ready) { return } this.ready = true if (!this.initialFrameworkCount) { this.updateStatus() } this.emit('ready', this) } /** * Listener for when a child framework is ready. */ protected onFrameworkReady (): void { this.initialFrameworkReady++ if (this.initialFrameworkReady >= this.initialFrameworkCount) { this.onReady() } } /** * Update this repository's status. * * @param to The status we're updating to. */ protected updateStatus (to?: FrameworkStatus): void { // If repository is marked as missing, don't update status until // the `exists` method is called and filesystem is checked. if (this.status === 'missing') { return } if (typeof to === 'undefined') { to = parseFrameworkStatus(this.frameworks.map(framework => framework.status)) } const from = this.status if (to !== from) { this.status = to this.emit('status', to, from) this.emitToRenderer(`${this.id}:status:sidebar`, to, from) } } /** * Load a group of frameworks to this project on first instantiation. * * @param frameworks The frameworks to add to this project. */ protected async loadFrameworks (frameworks: Array<FrameworkOptions>): Promise<void> { return new Promise((resolve, reject) => { setTimeout(() => { Promise.all(frameworks.map((framework: FrameworkOptions) => { return this.addFramework(framework) })).then(() => { this.onParsed() resolve() }) }) }) } /** * Add a child framework to this repository. * * @param options The options of the framework we're adding. */ public async addFramework (options: FrameworkOptions): Promise<IFramework> { return new Promise((resolve, reject) => { const framework: IFramework = FrameworkFactory.make(this.window, { ...options, ...{ repositoryPath: this.path }}) framework .on('ready', this.onFrameworkReady.bind(this)) .on('status', this.statusListener.bind(this)) .on('state', this.stateListener.bind(this)) .on('change', this.changeListener.bind(this)) .on('error', this.errorListener.bind(this)) .on('measuring', this.measuringListener.bind(this)) .on('progress', this.progressListener.bind(this)) this.frameworks.push(framework) this.updateStatus() resolve(framework) }) } /** * Remove a child framework from this repository using its unique id. * * @param id The id of the framework to remove. */ public removeFramework (id: string): void { const index = findIndex(this.frameworks, framework => framework.getId() === id) if (index > -1) { this.frameworks[index].removeAllListeners() this.frameworks.splice(index, 1) this.updateStatus() this.save() } } /** * Retrieve a framework from this repository by its id. * * @param id The id of the framework to retrieve. */ public getFrameworkById (id: string): IFramework | undefined { const index = findIndex(this.frameworks, framework => framework.getId() === id) if (index > -1) { return this.frameworks[index] } return undefined } /** * Get this repository's path. */ public getPath (): string { return this.path } /** * Update the repository's path. */ protected async updatePath (path: string): Promise<void> { this.path = path await Promise.all(this.frameworks.map((framework: IFramework) => { return framework.updateOptions({ ...framework.persist(), ...{ repositoryPath: path } }) })) await this.exists() this.save() } /** * Whether the repository exists in the filesystem */ public async exists (): Promise<boolean> { return new Promise((resolve, reject) => { Fs.access(this.path, Fs.constants.R_OK, error => { this.status = 'loading' this.updateStatus(error ? 'missing' : undefined) resolve(!error) }) }) } /** * Locate this repository, if missing. */ public async locate (window: Electron.BrowserWindow): Promise<void> { const { filePaths } = await dialog.showOpenDialog(window, { properties: ['openDirectory', 'multiSelections'] }) if (!filePaths || !filePaths.length) { return } this.updatePath(filePaths[0]) } /** * Progress the ledger by one unit. */ protected progress (): void { this.progressLedger.run++ this.emit('progress') } /** * Return the framework's progress ledger. */ public getProgressLedger (): ProgressLedger { return this.progressLedger } /** * Reset the framework's progress ledger. */ public resetProgressLedger (): void { this.progressLedger = { run: 0, total: 0 } this.frameworks.forEach((framework: IFramework) => { framework.resetProgressLedger() }) } /** * Send repository's frameworks to the renderer process. */ public emitFrameworksToRenderer (): void { this.emitToRenderer(`${this.id}:frameworks`, this.frameworks.map(framework => framework.render())) } }
the_stack
import { text, integer, relationship } from '@keystone-next/keystone/fields'; import { list } from '@keystone-next/keystone'; import { setupTestRunner } from '@keystone-next/keystone/testing'; import { apiTestConfig, expectGraphQLValidationError, expectLimitsExceededError } from '../utils'; import { depthLimit, definitionLimit, fieldLimit } from './validation'; const runner = setupTestRunner({ config: apiTestConfig({ lists: { Post: list({ fields: { title: text(), author: relationship({ ref: 'User.posts', many: true }), }, }), User: list({ fields: { name: text(), favNumber: integer(), posts: relationship({ ref: 'Post.author', many: true }), }, graphql: { queryLimits: { maxResults: 2, }, }, }), }, graphql: { queryLimits: { maxTotalResults: 6 }, apolloConfig: { validationRules: [depthLimit(3), definitionLimit(3), fieldLimit(8)], }, }, }), }); describe('maxResults Limit', () => { describe('Basic querying', () => { test( 'users', runner(async ({ context }) => { const users = await context.query.User.createMany({ data: [ { name: 'Jess', favNumber: 1 }, { name: 'Johanna', favNumber: 8 }, { name: 'Sam', favNumber: 5 }, { name: 'Theo', favNumber: 2 }, ], }); // 2 results is okay let data = await context.graphql.run({ query: ` query { users( where: { name: { contains: "J" } }, orderBy: { name: asc }, ) { name } } `, }); expect(data).toHaveProperty('users'); expect(data.users).toEqual([{ name: 'Jess' }, { name: 'Johanna' }]); // No results is okay data = await context.graphql.run({ query: ` query { users( where: { name: { equals: "Nope" } } ) { name } } `, }); expect(data).toHaveProperty('users'); expect(data.users.length).toEqual(0); // Count is still correct data = await context.graphql.run({ query: `query { usersCount }`, }); expect(data).toHaveProperty('usersCount'); expect(data.usersCount).toBe(users.length); // This query is only okay because of the "take" parameter data = await context.graphql.run({ query: ` query { users(take: 1) { name } } `, }); expect(data).toHaveProperty('users'); expect(data.users.length).toEqual(1); // This query returns too many results let errors; ({ errors } = await context.graphql.raw({ query: ` query { users { name } } `, })); expectLimitsExceededError(errors, [{ path: ['users'] }]); // The query results don't break the limits, but the "take" parameter does ({ errors } = await context.graphql.raw({ query: ` query { users( where: { name: { equals: "Nope" } }, take: 100000 ) { name } } `, })); expectLimitsExceededError(errors, [{ path: ['users'] }]); }) ); test( 'negative take still causes the early error', runner(async ({ context }) => { // there are no users so this will never hit the late error so if it errors // it must be the early error let { errors } = await context.graphql.raw({ query: ` query { users(take: -10) { name } } `, }); expectLimitsExceededError(errors, [{ path: ['users'] }]); }) ); }); describe('Relationship querying', () => { test( 'posts by user', runner(async ({ context }) => { const users = await context.query.User.createMany({ data: [ { name: 'Jess', favNumber: 1 }, { name: 'Johanna', favNumber: 8 }, { name: 'Sam', favNumber: 5 }, ], }); await context.query.Post.createMany({ data: [ { author: { connect: [{ id: users[0].id }] }, title: 'One author' }, { author: { connect: [{ id: users[0].id }, { id: users[1].id }] }, title: 'Two authors', }, { author: { connect: [{ id: users[0].id }, { id: users[1].id }, { id: users[2].id }] }, title: 'Three authors', }, ], }); // Reset the count for each query context.totalResults = 0; // A basic query that should work let posts = await context.query.Post.findMany({ where: { title: { equals: 'One author' } }, query: 'title author { name }', }); expect(posts).toEqual([{ title: 'One author', author: [{ name: 'Jess' }] }]); // Reset the count for each query context.totalResults = 0; // Each subquery is within the limit (even though the total isn't) posts = await context.query.Post.findMany({ where: { OR: [{ title: { equals: 'One author' } }, { title: { equals: 'Two authors' } }], }, orderBy: { title: 'asc' }, query: 'title author(orderBy: { name: asc }) { name }', }); expect(posts).toEqual([ { title: 'One author', author: [{ name: 'Jess' }] }, { title: 'Two authors', author: [{ name: 'Jess' }, { name: 'Johanna' }] }, ]); // Reset the count for each query context.totalResults = 0; // This post has too many authors let errors; ({ errors } = await context.graphql.raw({ query: ` query { posts( where: { title: { equals: "Three authors" } }, ) { title author { name } } } `, })); expectLimitsExceededError(errors, [{ path: ['posts', expect.any(Number), 'author'] }]); // Requesting the too-many-authors post is okay as long as the authors aren't returned // Reset the count for each query context.totalResults = 0; posts = await context.query.Post.findMany({ where: { title: { equals: 'Three authors' } }, query: 'title', }); expect(posts).toEqual([{ title: 'Three authors' }]); // Some posts are okay, but one breaks the limit // Reset the count for each query context.totalResults = 0; ({ errors } = await context.graphql.raw({ query: ` query { posts { title author { name } } } `, })); expectLimitsExceededError(errors, [{ path: ['posts', expect.any(Number), 'author'] }]); // All subqueries are within limits, but the total isn't // Reset the count for each query context.totalResults = 0; ({ errors } = await context.graphql.raw({ query: ` query { posts(where: { title: { equals: "Two authors" } }) { title author { posts { title } } } } `, })); expectLimitsExceededError(errors, [{ path: ['posts', 0, 'author', 1, 'posts'] }]); }) ); }); }); // FIXME: we need upstream support in the graphql package to make KS validation rules work for internal requests // (Low priority, but makes the API less surprising if rules work everywhere by default.) describe('maxDepth Limit', () => { test( 'script kiddie', runner(async ({ graphQLRequest }) => { // Block a script-kiddie attempt to DoS the server with nested queries const { body } = await graphQLRequest({ query: ` query { posts { author { posts { author { name } } } } } `, }).expect(400); expectGraphQLValidationError(body.errors, [{ message: 'Operation has depth 5 (max: 3)' }]); }) ); test( 'mutation script kiddie', runner(async ({ graphQLRequest }) => { const { body } = await graphQLRequest({ query: ` mutation { updatePost(where: { id: "foo" }, data: { title: "bar" }) { author { posts { author { name } } } } } `, }).expect(400); expectGraphQLValidationError(body.errors, [{ message: 'Operation has depth 5 (max: 3)' }]); }) ); test( 'one fragment', runner(async ({ graphQLRequest }) => { // Slightly sneakier depth violation using a fragment const { body } = await graphQLRequest({ query: ` query nestingbomb { posts { ...f } } fragment f on Post { author { posts { title } } } `, }).expect(400); expectGraphQLValidationError(body.errors, [{ message: 'Operation has depth 4 (max: 3)' }]); }) ); test( 'multiple fragments', runner(async ({ graphQLRequest }) => { // Sneakier violation using multiple fragments const { body } = await graphQLRequest({ query: ` query nestingbomb { posts { ...f1 } } fragment f1 on Post { author { ...f2 } } fragment f2 on User { posts { title } } `, }).expect(400); expectGraphQLValidationError(body.errors, [{ message: 'Operation has depth 4 (max: 3)' }]); }) ); test( 'mutual fragment reference', runner(async ({ graphQLRequest }) => { // Infinite loop (illegal as GraphQL, but needs to be handled) const { body } = await graphQLRequest({ query: ` query nestingbomb { posts { ...f1 } } fragment f1 on Post { author { ...f2 } } fragment f2 on User { posts { ...f1 } } `, }).expect(400); expectGraphQLValidationError(body.errors, [ { message: 'Operation has depth Infinity (max: 3)' }, { message: 'Operation has depth Infinity (max: 3)' }, { message: 'Operation has depth Infinity (max: 3)' }, { message: 'Request contains Infinity fields (max: 8)' }, { message: 'Cannot spread fragment "f1" within itself via "f2".' }, ]); }) ); test( 'undefined fragment', runner(async ({ graphQLRequest }) => { // (also illegal as GraphQL, but needs to be handled) const { body } = await graphQLRequest({ query: ` query { posts { ...nosuchfragment } } `, }).expect(400); expectGraphQLValidationError(body.errors, [ { message: 'Undefined fragment "nosuchfragment"' }, { message: 'Undefined fragment "nosuchfragment"' }, { message: 'Unknown fragment "nosuchfragment".' }, ]); }) ); }); describe('maxDefinitions Limit', () => { test( 'queries', runner(async ({ graphQLRequest }) => { // Too many queries const { body } = await graphQLRequest({ operationName: 'a', query: ` query a { posts { title } } query b { posts { title } } query c { posts { title } } query d { posts { title } } `, }).expect(400); expectGraphQLValidationError(body.errors, [ { message: 'Request contains 4 definitions (max: 3)' }, ]); }) ); test( 'fragments', runner(async ({ graphQLRequest }) => { const { body } = await graphQLRequest({ operationName: 'q1', query: ` fragment f1 on Post { title } fragment f2 on Post { title } query q1 { posts { ...f1 } } query q2 { posts { ...f2 } } `, }).expect(400); expectGraphQLValidationError(body.errors, [ { message: 'Request contains 4 definitions (max: 3)' }, ]); }) ); test( 'mutations', runner(async ({ graphQLRequest }) => { const { body } = await graphQLRequest({ operationName: 'm1', query: ` mutation m1 { updatePost(where: { id: "foo" }, data: { title: "bar" }) { title } } mutation m2 { updatePost(where: { id: "foo" }, data: { title: "bar" }) { title } } mutation m3 { updatePost(where: { id: "foo" }, data: { title: "bar" }) { title } } mutation m4 { updatePost(where: { id: "foo" }, data: { title: "bar" }) { title } } `, }).expect(400); // This isn't the only error, but that's okay expectGraphQLValidationError(body.errors, [ { message: 'Request contains 4 definitions (max: 3)' }, ]); }) ); }); describe('maxFields Limit', () => { test( 'one operation', runner(async ({ graphQLRequest }) => { const { body } = await graphQLRequest({ query: ` query { posts { title author { name favNumber } } users { name favNumber posts { title } } } `, }).expect(400); expectGraphQLValidationError(body.errors, [ { message: 'Request contains 10 fields (max: 8)' }, ]); }) ); test( 'many operations', runner(async ({ graphQLRequest }) => { const { body } = await graphQLRequest({ operationName: 'a', query: ` query a { posts { title } users { name } } query b { posts { title } users { name } } query c { posts { title } } `, }).expect(400); expectGraphQLValidationError(body.errors, [ { message: 'Request contains 10 fields (max: 8)' }, ]); }) ); test( 'fragments', runner(async ({ graphQLRequest }) => { const { body } = await graphQLRequest({ operationName: 'a', query: ` fragment f on User { name favNumber } query a { posts { title author { ...f } } users1: users { ...f } users2: users { ...f } } `, }).expect(400); expectGraphQLValidationError(body.errors, [ { message: 'Request contains 11 fields (max: 8)' }, ]); }) ); test( 'unused fragment', runner(async ({ graphQLRequest }) => { const { body } = await graphQLRequest({ operationName: 'a', query: ` fragment unused on User { name favNumber } fragment f on User { name favNumber } query a { posts { title author { ...f } } users1: users { ...f } users2: users { ...f } } `, }).expect(400); expectGraphQLValidationError(body.errors, [ { message: 'Request contains 13 fields (max: 8)' }, { message: 'Fragment "unused" is never used.' }, ]); }) ); test( 'billion laughs', runner(async ({ graphQLRequest }) => { // https://en.wikipedia.org/wiki/Billion_laughs const { body } = await graphQLRequest({ operationName: 'a', query: ` query a { u1: users { ...lol1 } u2: users { ...lol1 } u3: users { ...lol1 } u4: users { ...lol1 } u5: users { ...lol1 } } fragment lol1 on User { p1: posts { ...lol2 } p2: posts { ...lol2 } p3: posts { ...lol2 } p4: posts { ...lol2 } p5: posts { ...lol2 } } fragment lol2 on Post { title author { id } } `, }).expect(400); expectGraphQLValidationError(body.errors, [ { message: 'Operation has depth 4 (max: 3)' }, { message: 'Request contains 105 fields (max: 8)' }, ]); }) ); });
the_stack
import forEach from "lodash/forEach"; import { displaySemicolon, getBlankLinesSeparator, getClassBodyDeclarationsSeparator, isStatementEmptyStatement, putIntoBraces, reject, rejectAndConcat, rejectAndJoin, rejectAndJoinSeps, sortClassTypeChildren, sortModifiers } from "./printer-utils"; import { concat, group, indent, join } from "./prettier-builder"; import { printTokenWithComments } from "./comments/format-comments"; import { hasLeadingComments, hasLeadingLineComments } from "./comments/comments-utils"; import { builders } from "prettier/doc"; import { BaseCstPrettierPrinter } from "../base-cst-printer"; import { ClassBodyCtx, ClassBodyDeclarationCtx, ClassDeclarationCtx, ClassMemberDeclarationCtx, ClassModifierCtx, ClassPermitsCtx, CompactConstructorDeclarationCtx, ConstructorBodyCtx, ConstructorDeclarationCtx, ConstructorDeclaratorCtx, ConstructorModifierCtx, EnumBodyCtx, EnumBodyDeclarationsCtx, EnumConstantCtx, EnumConstantListCtx, EnumConstantModifierCtx, EnumDeclarationCtx, ExceptionTypeCtx, ExceptionTypeListCtx, ExplicitConstructorInvocationCtx, FieldDeclarationCtx, FieldModifierCtx, FormalParameterCtx, FormalParameterListCtx, InstanceInitializerCtx, InterfaceTypeListCtx, IToken, MethodBodyCtx, MethodDeclarationCtx, MethodDeclaratorCtx, MethodHeaderCtx, MethodModifierCtx, NormalClassDeclarationCtx, QualifiedExplicitConstructorInvocationCtx, ReceiverParameterCtx, RecordBodyCtx, RecordBodyDeclarationCtx, RecordComponentCtx, RecordComponentListCtx, RecordComponentModifierCtx, RecordDeclarationCtx, RecordHeaderCtx, ResultCtx, SimpleTypeNameCtx, StaticInitializerCtx, SuperclassCtx, SuperinterfacesCtx, ThrowsCtx, TypeParameterListCtx, TypeParametersCtx, UnannClassOrInterfaceTypeCtx, UnannClassTypeCtx, UnannInterfaceTypeCtx, UnannPrimitiveTypeCtx, UnannPrimitiveTypeWithOptionalDimsSuffixCtx, UnannReferenceTypeCtx, UnannTypeCtx, UnannTypeVariableCtx, UnqualifiedExplicitConstructorInvocationCtx, VariableArityParameterCtx, VariableArityRecordComponentCtx, VariableDeclaratorCtx, VariableDeclaratorIdCtx, VariableDeclaratorListCtx, VariableInitializerCtx, VariableModifierCtx, VariableParaRegularParameterCtx } from "java-parser"; import { Doc } from "prettier"; import { isAnnotationCstNode, isTypeArgumentsCstNode } from "../types/utils"; import { printArgumentListWithBraces } from "../utils"; const { line, softline, hardline } = builders; export class ClassesPrettierVisitor extends BaseCstPrettierPrinter { classDeclaration(ctx: ClassDeclarationCtx) { const modifiers = sortModifiers(ctx.classModifier); const firstAnnotations = this.mapVisit(modifiers[0]); const otherModifiers = this.mapVisit(modifiers[1]); let classCST; if (ctx.normalClassDeclaration !== undefined) { classCST = ctx.normalClassDeclaration; } else if (ctx.enumDeclaration !== undefined) { classCST = ctx.enumDeclaration; } else { classCST = ctx.recordDeclaration; } const classDoc = this.visit(classCST); return rejectAndJoin(hardline, [ rejectAndJoin(hardline, firstAnnotations), rejectAndJoin(" ", [join(" ", otherModifiers), classDoc]) ]); } normalClassDeclaration(ctx: NormalClassDeclarationCtx) { const name = this.visit(ctx.typeIdentifier); const optionalTypeParams = this.visit(ctx.typeParameters); const optionalSuperClasses = this.visit(ctx.superclass); const optionalSuperInterfaces = this.visit(ctx.superinterfaces); const optionalClassPermits = this.visit(ctx.classPermits); const body = this.visit(ctx.classBody, { isNormalClassDeclaration: true }); let superClassesPart = ""; if (optionalSuperClasses) { superClassesPart = indent(rejectAndConcat([line, optionalSuperClasses])); } let superInterfacesPart = ""; if (optionalSuperInterfaces) { superInterfacesPart = indent( rejectAndConcat([line, optionalSuperInterfaces]) ); } let classPermits = ""; if (optionalClassPermits) { classPermits = indent(rejectAndConcat([line, optionalClassPermits])); } return rejectAndJoin(" ", [ group( rejectAndConcat([ rejectAndJoin(" ", [ctx.Class[0], name]), optionalTypeParams, superClassesPart, superInterfacesPart, classPermits ]) ), body ]); } classModifier(ctx: ClassModifierCtx) { if (ctx.annotation) { return this.visit(ctx.annotation); } // public | protected | private | ... return printTokenWithComments(this.getSingle(ctx) as IToken); } typeParameters(ctx: TypeParametersCtx) { const typeParameterList = this.visit(ctx.typeParameterList); return putIntoBraces( typeParameterList, softline, ctx.Less[0], ctx.Greater[0] ); } typeParameterList(ctx: TypeParameterListCtx) { const typeParameter = this.mapVisit(ctx.typeParameter); const commas = ctx.Comma ? ctx.Comma.map(elt => concat([elt, line])) : []; return group(rejectAndJoinSeps(commas, typeParameter)); } superclass(ctx: SuperclassCtx) { return join(" ", [ctx.Extends[0], this.visit(ctx.classType)]); } superinterfaces(ctx: SuperinterfacesCtx) { const interfaceTypeList = this.visit(ctx.interfaceTypeList); return group( rejectAndConcat([ ctx.Implements[0], indent(rejectAndConcat([line, interfaceTypeList])) ]) ); } classPermits(ctx: ClassPermitsCtx) { const typeNames = this.mapVisit(ctx.typeName); const commas = ctx.Comma ? ctx.Comma.map(elt => concat([elt, line])) : []; return group( rejectAndConcat([ ctx.Permits[0], indent( rejectAndConcat([line, group(rejectAndJoinSeps(commas, typeNames))]) ) ]) ); } interfaceTypeList(ctx: InterfaceTypeListCtx) { const interfaceType = this.mapVisit(ctx.interfaceType); const commas = ctx.Comma ? ctx.Comma.map(elt => concat([elt, line])) : []; return group(rejectAndJoinSeps(commas, interfaceType)); } classBody(ctx: ClassBodyCtx, param: any) { let content = ""; if (ctx.classBodyDeclaration !== undefined) { const classBodyDeclsVisited = reject( this.mapVisit(ctx.classBodyDeclaration) ); const separators = getClassBodyDeclarationsSeparator( ctx.classBodyDeclaration ); content = rejectAndJoinSeps(separators, classBodyDeclsVisited); // edge case when we have SemiColons let shouldHardline = false; ctx.classBodyDeclaration.forEach(elt => { if ( (elt.children.classMemberDeclaration && !elt.children.classMemberDeclaration[0].children.Semicolon) || elt.children.constructorDeclaration ) { shouldHardline = true; } }); if ( (ctx.classBodyDeclaration[0].children.classMemberDeclaration || ctx.classBodyDeclaration[0].children.constructorDeclaration) && shouldHardline && param && param.isNormalClassDeclaration ) { content = rejectAndConcat([hardline, content]); } } return putIntoBraces(content, hardline, ctx.LCurly[0], ctx.RCurly[0]); } classBodyDeclaration(ctx: ClassBodyDeclarationCtx) { return this.visitSingle(ctx); } classMemberDeclaration(ctx: ClassMemberDeclarationCtx) { if (ctx.Semicolon) { return displaySemicolon(ctx.Semicolon[0]); } return this.visitSingle(ctx); } fieldDeclaration(ctx: FieldDeclarationCtx) { const modifiers = sortModifiers(ctx.fieldModifier); const firstAnnotations = this.mapVisit(modifiers[0]); const otherModifiers = this.mapVisit(modifiers[1]); const unannType = this.visit(ctx.unannType); const variableDeclaratorList = this.visit(ctx.variableDeclaratorList); return rejectAndJoin(hardline, [ rejectAndJoin(hardline, firstAnnotations), rejectAndJoin(" ", [ rejectAndJoin(" ", otherModifiers), unannType, concat([variableDeclaratorList, ctx.Semicolon[0]]) ]) ]); } fieldModifier(ctx: FieldModifierCtx) { if (ctx.annotation) { return this.visit(ctx.annotation); } // public | protected | private | ... return printTokenWithComments(this.getSingle(ctx) as IToken); } variableDeclaratorList(ctx: VariableDeclaratorListCtx) { const variableDeclarators = this.mapVisit(ctx.variableDeclarator); const commas = ctx.Comma ? ctx.Comma.map(elt => concat([elt, " "])) : []; return rejectAndJoinSeps(commas, variableDeclarators); } variableDeclarator(ctx: VariableDeclaratorCtx) { const variableDeclaratorId = this.visit(ctx.variableDeclaratorId); if (ctx.Equals) { const variableInitializer = this.visit(ctx.variableInitializer); if (hasLeadingLineComments(ctx.variableInitializer![0])) { return group( indent( rejectAndJoin(hardline, [ rejectAndJoin(" ", [variableDeclaratorId, ctx.Equals[0]]), variableInitializer ]) ) ); } if ( // Array Initialisation ctx.variableInitializer![0].children.arrayInitializer !== undefined || // Lambda expression ctx.variableInitializer![0].children.expression![0].children .lambdaExpression !== undefined || // Ternary Expression (ctx.variableInitializer![0].children.expression![0].children .ternaryExpression !== undefined && ctx.variableInitializer![0].children.expression![0].children .ternaryExpression[0].children.QuestionMark !== undefined) ) { return rejectAndJoin(" ", [ variableDeclaratorId, ctx.Equals[0], variableInitializer ]); } if ( ctx.variableInitializer![0].children.expression![0].children .ternaryExpression !== undefined ) { const firstPrimary = ctx.variableInitializer![0].children.expression![0].children .ternaryExpression[0].children.binaryExpression[0].children .unaryExpression[0].children.primary[0]; // Cast Expression if ( firstPrimary.children.primaryPrefix[0].children.castExpression !== undefined ) { return rejectAndJoin(" ", [ variableDeclaratorId, ctx.Equals[0], variableInitializer ]); } // New Expression if ( firstPrimary.children.primaryPrefix[0].children.newExpression !== undefined ) { return rejectAndJoin(" ", [ variableDeclaratorId, ctx.Equals[0], variableInitializer ]); } // Method Invocation const isMethodInvocation = firstPrimary.children.primarySuffix !== undefined && firstPrimary.children.primarySuffix[0].children .methodInvocationSuffix !== undefined; const isUniqueUnaryExpression = ctx.variableInitializer![0].children.expression![0].children .ternaryExpression[0].children.binaryExpression[0].children .unaryExpression.length === 1; const isUniqueMethodInvocation = isMethodInvocation && isUniqueUnaryExpression; if (isUniqueMethodInvocation) { return rejectAndJoin(" ", [ variableDeclaratorId, ctx.Equals[0], variableInitializer ]); } } return group( indent( rejectAndJoin(line, [ rejectAndJoin(" ", [variableDeclaratorId, ctx.Equals[0]]), variableInitializer ]) ) ); } return variableDeclaratorId; } variableDeclaratorId(ctx: VariableDeclaratorIdCtx) { const identifier = ctx.Identifier[0]; const dims = this.visit(ctx.dims); return rejectAndConcat([identifier, dims]); } variableInitializer(ctx: VariableInitializerCtx) { return this.visitSingle(ctx); } unannType(ctx: UnannTypeCtx) { return this.visitSingle(ctx); } unannPrimitiveTypeWithOptionalDimsSuffix( ctx: UnannPrimitiveTypeWithOptionalDimsSuffixCtx ) { const unannPrimitiveType = this.visit(ctx.unannPrimitiveType); const dims = this.visit(ctx.dims); return rejectAndConcat([unannPrimitiveType, dims]); } unannPrimitiveType(ctx: UnannPrimitiveTypeCtx) { if (ctx.numericType) { return this.visitSingle(ctx); } return printTokenWithComments(this.getSingle(ctx) as IToken); } unannReferenceType(ctx: UnannReferenceTypeCtx) { const unannClassOrInterfaceType = this.visit(ctx.unannClassOrInterfaceType); const dims = this.visit(ctx.dims); return rejectAndConcat([unannClassOrInterfaceType, dims]); } unannClassOrInterfaceType(ctx: UnannClassOrInterfaceTypeCtx) { return this.visit(ctx.unannClassType); } unannClassType(ctx: UnannClassTypeCtx) { const tokens = sortClassTypeChildren( ctx.annotation, ctx.typeArguments, ctx.Identifier ); const segments: Doc[] = []; let currentSegment: (Doc | IToken)[] = []; forEach(tokens, (token, i) => { if (isTypeArgumentsCstNode(token)) { currentSegment.push(this.visit([token])); segments.push(rejectAndConcat(currentSegment)); currentSegment = []; } else if (isAnnotationCstNode(token)) { currentSegment.push(this.visit([token])); currentSegment.push(" "); } else { currentSegment.push(token as IToken); if ( (i + 1 < tokens.length && !isTypeArgumentsCstNode(tokens[i + 1])) || i + 1 === tokens.length ) { segments.push(rejectAndConcat(currentSegment)); currentSegment = []; } } }); return rejectAndJoinSeps(ctx.Dot, segments); } unannInterfaceType(ctx: UnannInterfaceTypeCtx) { return this.visit(ctx.unannClassType); } unannTypeVariable(ctx: UnannTypeVariableCtx) { return printTokenWithComments(this.getSingle(ctx) as IToken); } methodDeclaration(ctx: MethodDeclarationCtx) { const modifiers = sortModifiers(ctx.methodModifier); const firstAnnotations = this.mapVisit(modifiers[0]); const otherModifiers = this.mapVisit(modifiers[1]); const header = this.visit(ctx.methodHeader); const body = this.visit(ctx.methodBody); const headerBodySeparator = isStatementEmptyStatement(body) ? "" : " "; return rejectAndJoin(hardline, [ rejectAndJoin(hardline, firstAnnotations), rejectAndJoin(" ", [ rejectAndJoin(" ", otherModifiers), rejectAndJoin(headerBodySeparator, [header, body]) ]) ]); } methodModifier(ctx: MethodModifierCtx) { if (ctx.annotation) { return this.visit(ctx.annotation); } // public | protected | private | Synchronized | ... return printTokenWithComments(this.getSingle(ctx) as IToken); } methodHeader(ctx: MethodHeaderCtx) { const typeParameters = this.visit(ctx.typeParameters); const annotations = this.mapVisit(ctx.annotation); const result = this.visit(ctx.result); const declarator = this.visit(ctx.methodDeclarator); const throws = this.visit(ctx.throws); return group( concat([ rejectAndJoin(" ", [ typeParameters, rejectAndJoin(line, annotations), result, declarator, throws ]) ]) ); } result(ctx: ResultCtx) { if (ctx.unannType) { return this.visit(ctx.unannType); } // void return printTokenWithComments(this.getSingle(ctx) as IToken); } methodDeclarator(ctx: MethodDeclaratorCtx) { const identifier = printTokenWithComments(ctx.Identifier[0]); const formalParameterList = this.visit(ctx.formalParameterList); const dims = this.visit(ctx.dims); return rejectAndConcat([ identifier, putIntoBraces( formalParameterList, softline, ctx.LBrace[0], ctx.RBrace[0] ), dims ]); } receiverParameter(ctx: ReceiverParameterCtx) { const annotations = this.mapVisit(ctx.annotation); const unannType = this.visit(ctx.unannType); const identifier = ctx.Identifier ? concat([ctx.Identifier[0], ctx.Dot![0]]) : ""; return rejectAndJoin("", [ rejectAndJoin(" ", annotations), unannType, identifier, ctx.This[0] ]); } formalParameterList(ctx: FormalParameterListCtx) { const formalParameter = this.mapVisit(ctx.formalParameter); const commas = ctx.Comma ? ctx.Comma.map(elt => concat([elt, line])) : []; return rejectAndJoinSeps(commas, formalParameter); } formalParameter(ctx: FormalParameterCtx) { return this.visitSingle(ctx); } variableParaRegularParameter(ctx: VariableParaRegularParameterCtx) { const variableModifier = this.mapVisit(ctx.variableModifier); const unannType = this.visit(ctx.unannType); const variableDeclaratorId = this.visit(ctx.variableDeclaratorId); return rejectAndJoin(" ", [ rejectAndJoin(" ", variableModifier), unannType, variableDeclaratorId ]); } variableArityParameter(ctx: VariableArityParameterCtx) { const variableModifier = this.mapVisit(ctx.variableModifier); const unannType = this.visit(ctx.unannType); const annotations = this.mapVisit(ctx.annotation); const identifier = ctx.Identifier[0]; const unannTypePrinted = ctx.annotation === undefined ? concat([unannType, ctx.DotDotDot[0]]) : unannType; const annotationsPrinted = ctx.annotation === undefined ? annotations : concat([rejectAndJoin(" ", annotations), ctx.DotDotDot[0]]); return rejectAndJoin(" ", [ join(" ", variableModifier), unannTypePrinted, annotationsPrinted, identifier ]); } variableModifier(ctx: VariableModifierCtx) { if (ctx.annotation) { return this.visit(ctx.annotation); } return printTokenWithComments(this.getSingle(ctx) as IToken); } throws(ctx: ThrowsCtx) { const exceptionTypeList = this.visit(ctx.exceptionTypeList); const throwsDeclaration = join(" ", [ctx.Throws[0], exceptionTypeList]); return group(indent(rejectAndConcat([softline, throwsDeclaration]))); } exceptionTypeList(ctx: ExceptionTypeListCtx) { const exceptionTypes = this.mapVisit(ctx.exceptionType); const commas = ctx.Comma ? ctx.Comma.map(elt => concat([elt, " "])) : []; return rejectAndJoinSeps(commas, exceptionTypes); } exceptionType(ctx: ExceptionTypeCtx) { return this.visitSingle(ctx); } methodBody(ctx: MethodBodyCtx) { if (ctx.block) { return this.visit(ctx.block); } return printTokenWithComments(this.getSingle(ctx) as IToken); } instanceInitializer(ctx: InstanceInitializerCtx) { return this.visitSingle(ctx); } staticInitializer(ctx: StaticInitializerCtx) { const block = this.visit(ctx.block); return join(" ", [ctx.Static[0], block]); } constructorDeclaration(ctx: ConstructorDeclarationCtx) { const modifiers = sortModifiers(ctx.constructorModifier); const firstAnnotations = this.mapVisit(modifiers[0]); const otherModifiers = this.mapVisit(modifiers[1]); const constructorDeclarator = this.visit(ctx.constructorDeclarator); const throws = this.visit(ctx.throws); const constructorBody = this.visit(ctx.constructorBody); return rejectAndJoin(" ", [ group( rejectAndJoin(hardline, [ rejectAndJoin(hardline, firstAnnotations), rejectAndJoin(" ", [ join(" ", otherModifiers), constructorDeclarator, throws ]) ]) ), constructorBody ]); } constructorModifier(ctx: ConstructorModifierCtx) { if (ctx.annotation) { return this.visit(ctx.annotation); } // public | protected | private | Synchronized | ... return printTokenWithComments(this.getSingle(ctx) as IToken); } constructorDeclarator(ctx: ConstructorDeclaratorCtx) { const typeParameters = this.visit(ctx.typeParameters); const simpleTypeName = this.visit(ctx.simpleTypeName); const receiverParameter = this.visit(ctx.receiverParameter); const formalParameterList = this.visit(ctx.formalParameterList); const commas = ctx.Comma ? ctx.Comma.map(elt => concat([elt, " "])) : []; return rejectAndJoin(" ", [ typeParameters, concat([ simpleTypeName, putIntoBraces( rejectAndJoinSeps(commas, [receiverParameter, formalParameterList]), softline, ctx.LBrace[0], ctx.RBrace[0] ) ]) ]); } simpleTypeName(ctx: SimpleTypeNameCtx) { return printTokenWithComments(this.getSingle(ctx) as IToken); } constructorBody(ctx: ConstructorBodyCtx) { const explicitConstructorInvocation = this.visit( ctx.explicitConstructorInvocation ); const blockStatements = this.visit(ctx.blockStatements); return putIntoBraces( rejectAndJoin(hardline, [explicitConstructorInvocation, blockStatements]), hardline, ctx.LCurly[0], ctx.RCurly[0] ); } explicitConstructorInvocation(ctx: ExplicitConstructorInvocationCtx) { return this.visitSingle(ctx); } unqualifiedExplicitConstructorInvocation( ctx: UnqualifiedExplicitConstructorInvocationCtx ) { const typeArguments = this.visit(ctx.typeArguments); const keyWord = ctx.This ? ctx.This[0] : ctx.Super![0]; const argumentList = printArgumentListWithBraces.call( this, ctx.argumentList, ctx.RBrace![0], ctx.LBrace[0] ); return rejectAndConcat([ typeArguments, keyWord, group(rejectAndConcat([argumentList, ctx.Semicolon[0]])) ]); } qualifiedExplicitConstructorInvocation( ctx: QualifiedExplicitConstructorInvocationCtx ) { const expressionName = this.visit(ctx.expressionName); const typeArguments = this.visit(ctx.typeArguments); const argumentList = printArgumentListWithBraces.call( this, ctx.argumentList, ctx.RBrace![0], ctx.LBrace[0] ); return rejectAndConcat([ expressionName, ctx.Dot[0], typeArguments, ctx.Super[0], group(rejectAndConcat([argumentList, ctx.Semicolon[0]])) ]); } enumDeclaration(ctx: EnumDeclarationCtx) { const classModifier = this.mapVisit(ctx.classModifier); const typeIdentifier = this.visit(ctx.typeIdentifier); const superinterfaces = this.visit(ctx.superinterfaces); const enumBody = this.visit(ctx.enumBody); return rejectAndJoin(" ", [ join(" ", classModifier), ctx.Enum[0], typeIdentifier, superinterfaces, enumBody ]); } enumBody(ctx: EnumBodyCtx) { const enumConstantList = this.visit(ctx.enumConstantList); const enumBodyDeclarations = this.visit(ctx.enumBodyDeclarations); const hasEnumConstants = ctx.enumConstantList !== undefined; const hasNoClassBodyDeclarations = ctx.enumBodyDeclarations === undefined || ctx.enumBodyDeclarations[0].children.classBodyDeclaration === undefined; // edge case: https://github.com/jhipster/prettier-java/issues/383 const handleEnumBodyDeclarationsLeadingComments = !hasNoClassBodyDeclarations && hasLeadingComments(ctx.enumBodyDeclarations![0]) ? hardline : ""; let optionalComma; if ( hasEnumConstants && hasNoClassBodyDeclarations && this.prettierOptions.trailingComma !== "none" ) { optionalComma = ctx.Comma ? ctx.Comma[0] : ","; } else { optionalComma = ctx.Comma ? { ...ctx.Comma[0], image: "" } : ""; } return putIntoBraces( rejectAndConcat([ enumConstantList, optionalComma, handleEnumBodyDeclarationsLeadingComments, enumBodyDeclarations ]), hardline, ctx.LCurly[0], ctx.RCurly[0] ); } enumConstantList(ctx: EnumConstantListCtx) { const enumConstants = this.mapVisit(ctx.enumConstant); const blankLineSeparators = getBlankLinesSeparator(ctx.enumConstant); const commas = ctx.Comma ? ctx.Comma.map((elt, index) => concat([elt, blankLineSeparators![index]]) ) : []; return group(rejectAndJoinSeps(commas, enumConstants)); } enumConstant(ctx: EnumConstantCtx) { const modifiers = sortModifiers(ctx.enumConstantModifier); const firstAnnotations = this.mapVisit(modifiers[0]); const otherModifiers = this.mapVisit(modifiers[1]); const identifier = ctx.Identifier[0]; const classBody = this.visit(ctx.classBody); const optionalBracesAndArgumentList = ctx.LBrace ? printArgumentListWithBraces.call( this, ctx.argumentList, ctx.RBrace![0], ctx.LBrace[0] ) : ""; return rejectAndJoin(hardline, [ rejectAndJoin(hardline, firstAnnotations), rejectAndJoin(" ", [ rejectAndJoin(" ", otherModifiers), rejectAndConcat([identifier, optionalBracesAndArgumentList]), classBody ]) ]); } enumConstantModifier(ctx: EnumConstantModifierCtx) { return this.visitSingle(ctx); } enumBodyDeclarations(ctx: EnumBodyDeclarationsCtx) { if (ctx.classBodyDeclaration !== undefined) { const classBodyDeclaration = this.mapVisit(ctx.classBodyDeclaration); const separators = getClassBodyDeclarationsSeparator( ctx.classBodyDeclaration ); return rejectAndJoin(concat([hardline, hardline]), [ ctx.Semicolon[0], rejectAndJoinSeps(separators, classBodyDeclaration) ]); } return { ...ctx.Semicolon[0], image: "" }; } recordDeclaration(ctx: RecordDeclarationCtx) { const name = this.visit(ctx.typeIdentifier); const optionalTypeParams = this.visit(ctx.typeParameters); const recordHeader = this.visit(ctx.recordHeader); let superInterfacesPart = ""; const optionalSuperInterfaces = this.visit(ctx.superinterfaces); if (optionalSuperInterfaces) { superInterfacesPart = indent( rejectAndConcat([line, optionalSuperInterfaces]) ); } const body = this.visit(ctx.recordBody); return rejectAndJoin(" ", [ group( rejectAndConcat([ rejectAndJoin(" ", [ctx.Record[0], name]), optionalTypeParams, recordHeader, superInterfacesPart ]) ), body ]); } recordHeader(ctx: RecordHeaderCtx) { const recordComponentList = this.visit(ctx.recordComponentList); return putIntoBraces( recordComponentList, softline, ctx.LBrace[0], ctx.RBrace[0] ); } recordComponentList(ctx: RecordComponentListCtx) { const recordComponents = this.mapVisit(ctx.recordComponent); const commas = ctx.Comma ? ctx.Comma.map(elt => concat([elt, line])) : []; return rejectAndJoinSeps(commas, recordComponents); } recordComponent(ctx: RecordComponentCtx) { const modifiers = this.mapVisit(ctx.recordComponentModifier); const unannType = this.visit(ctx.unannType); if (ctx.Identifier !== undefined) { return rejectAndJoin(" ", [ join(" ", modifiers), unannType, ctx.Identifier[0] ]); } const variableArityRecordComponent = this.visit( ctx.variableArityRecordComponent ); if ( ctx.variableArityRecordComponent![0].children.annotation !== undefined ) { return rejectAndJoin(" ", [ join(" ", modifiers), join(" ", [unannType, variableArityRecordComponent]) ]); } return rejectAndJoin(" ", [ join(" ", modifiers), concat([unannType, variableArityRecordComponent]) ]); } variableArityRecordComponent(ctx: VariableArityRecordComponentCtx) { const annotations = this.mapVisit(ctx.annotation); const identifier = ctx.Identifier[0]; return rejectAndJoin(" ", [ rejectAndConcat([rejectAndJoin(" ", annotations), ctx.DotDotDot[0]]), identifier ]); } recordComponentModifier(ctx: RecordComponentModifierCtx) { return this.visitSingle(ctx); } recordBody(ctx: RecordBodyCtx) { return putIntoBraces( rejectAndJoinSeps( getBlankLinesSeparator(ctx.recordBodyDeclaration), this.mapVisit(ctx.recordBodyDeclaration) ), hardline, ctx.LCurly[0], ctx.RCurly[0] ); } recordBodyDeclaration(ctx: RecordBodyDeclarationCtx) { return this.visitSingle(ctx); } compactConstructorDeclaration(ctx: CompactConstructorDeclarationCtx) { const modifiers = sortModifiers(ctx.constructorModifier); const firstAnnotations = this.mapVisit(modifiers[0]); const otherModifiers = this.mapVisit(modifiers[1]); const name = this.visit(ctx.simpleTypeName); const constructorBody = this.visit(ctx.constructorBody); return rejectAndJoin(" ", [ group( rejectAndJoin(hardline, [ rejectAndJoin(hardline, firstAnnotations), rejectAndJoin(" ", [join(" ", otherModifiers), name]) ]) ), constructorBody ]); } isClassDeclaration() { return "isClassDeclaration"; } identifyClassBodyDeclarationType() { return "identifyClassBodyDeclarationType"; } isDims() { return "isDims"; } isCompactConstructorDeclaration() { return "isCompactConstructorDeclaration"; } }
the_stack
import React, { FunctionComponent, useCallback, useEffect, useRef, useState, } from "react"; import { Dimensions, Image, StatusBar, StyleSheet, View } from "react-native"; import Animated, { Easing } from "react-native-reanimated"; import { observer } from "mobx-react-lite"; import { useStyle } from "../../styles"; import * as SplashScreen from "expo-splash-screen"; import { TextInput } from "../../components/input"; import { Button } from "../../components/button"; import delay from "delay"; import { useStore } from "../../stores"; import { KeyboardAwareScrollView } from "react-native-keyboard-aware-scroll-view"; import { StackActions, useNavigation } from "@react-navigation/native"; import { KeyRingStatus } from "@keplr-wallet/background"; import { KeychainStore } from "../../stores/keychain"; import { IAccountStore } from "@keplr-wallet/stores"; import { autorun } from "mobx"; let splashScreenHided = false; async function hideSplashScreen() { if (!splashScreenHided) { console.log("Hide Splash screen"); if (await SplashScreen.hideAsync()) { splashScreenHided = true; } } } async function waitAccountLoad( accountStore: IAccountStore, chainId: string ): Promise<void> { if (accountStore.getAccount(chainId).bech32Address) { return; } return new Promise((resolve) => { const disposer = autorun(() => { if (accountStore.getAccount(chainId).bech32Address) { resolve(); if (disposer) { disposer(); } } }); }); } /* If the biomeric is on, just try to unlock by biometric automatically once. */ enum AutoBiomtricStatus { NO_NEED, NEED, FAILED, SUCCESS, } const useAutoBiomtric = (keychainStore: KeychainStore, tryEnabled: boolean) => { const [status, setStatus] = useState(AutoBiomtricStatus.NO_NEED); const tryBiometricAutoOnce = useRef(false); useEffect(() => { if (keychainStore.isBiometryOn && status === AutoBiomtricStatus.NO_NEED) { setStatus(AutoBiomtricStatus.NEED); } }, [keychainStore.isBiometryOn, status]); useEffect(() => { if ( !tryBiometricAutoOnce.current && status === AutoBiomtricStatus.NEED && tryEnabled ) { tryBiometricAutoOnce.current = true; (async () => { try { await keychainStore.tryUnlockWithBiometry(); setStatus(AutoBiomtricStatus.SUCCESS); } catch (e) { console.log(e); setStatus(AutoBiomtricStatus.FAILED); } })(); } }, [keychainStore, status, tryEnabled]); return status; }; /** * UnlockScreen is expected to be opened when the keyring store's state is "not loaded (yet)" or "locked" at launch. * And, this screen has continuity with the splash screen * @constructor */ export const UnlockScreen: FunctionComponent = observer(() => { const { keyRingStore, keychainStore, accountStore, chainStore } = useStore(); const style = useStyle(); const navigation = useNavigation(); const [isSplashEnd, setIsSplashEnd] = useState(false); const [animatedContinuityEffectOpacity] = useState( () => new Animated.Value(1) ); const navigateToHomeOnce = useRef(false); const navigateToHome = useCallback(async () => { if (!navigateToHomeOnce.current) { // Wait the account of selected chain is loaded. await waitAccountLoad(accountStore, chainStore.current.chainId); navigation.dispatch(StackActions.replace("MainTabDrawer")); } navigateToHomeOnce.current = true; }, [accountStore, chainStore, navigation]); const autoBiometryStatus = useAutoBiomtric( keychainStore, keyRingStore.status === KeyRingStatus.LOCKED && isSplashEnd ); useEffect(() => { if (isSplashEnd && autoBiometryStatus === AutoBiomtricStatus.SUCCESS) { (async () => { await hideSplashScreen(); })(); } }, [autoBiometryStatus, isSplashEnd, navigation]); useEffect(() => { if ( isSplashEnd && keyRingStore.status === KeyRingStatus.LOCKED && (autoBiometryStatus === AutoBiomtricStatus.NO_NEED || autoBiometryStatus === AutoBiomtricStatus.FAILED) ) { setTimeout(() => { Animated.timing(animatedContinuityEffectOpacity, { toValue: 0, duration: 600, easing: Easing.ease, }).start(); }, 700); } }, [ animatedContinuityEffectOpacity, autoBiometryStatus, isSplashEnd, keyRingStore.status, ]); const [password, setPassword] = useState(""); const [isLoading, setIsLoading] = useState(false); const [isBiometricLoading, setIsBiometricLoading] = useState(false); const [isFailed, setIsFailed] = useState(false); const tryBiometric = useCallback(async () => { try { setIsBiometricLoading(true); // Because javascript is synchronous language, the loadnig state change would not delivered to the UI thread // So to make sure that the loading state changes, just wait very short time. await delay(10); await keychainStore.tryUnlockWithBiometry(); await hideSplashScreen(); } catch (e) { console.log(e); setIsBiometricLoading(false); } }, [keychainStore]); const tryUnlock = async () => { try { setIsLoading(true); // Decryption needs slightly huge computation. // Because javascript is synchronous language, the loadnig state change would not delivered to the UI thread // before the actually decryption is complete. // So to make sure that the loading state changes, just wait very short time. await delay(10); await keyRingStore.unlock(password); await hideSplashScreen(); } catch (e) { console.log(e); setIsLoading(false); setIsFailed(true); } }; const routeToRegisterOnce = useRef(false); useEffect(() => { // If the keyring is empty, // route to the register screen. if ( !routeToRegisterOnce.current && isSplashEnd && keyRingStore.status === KeyRingStatus.EMPTY ) { (async () => { await hideSplashScreen(); routeToRegisterOnce.current = true; navigation.dispatch( StackActions.replace("Register", { screen: "Register.Intro", }) ); })(); } }, [isSplashEnd, keyRingStore.status, navigation]); useEffect(() => { if (keyRingStore.status === KeyRingStatus.UNLOCKED) { (async () => { await hideSplashScreen(); navigateToHome(); })(); } }, [keyRingStore.status, navigateToHome]); return ( <React.Fragment> <View style={style.flatten([ "absolute-fill", "background-color-splash-background", ])} /> <View style={style.flatten(["flex-1", "background-color-splash-background"])} > <KeyboardAwareScrollView contentContainerStyle={style.flatten(["flex-grow-1"])} > <View style={style.get("flex-5")} /> <Image style={StyleSheet.flatten([style.flatten(["width-full"])])} fadeDuration={0} resizeMode="contain" source={require("../../assets/logo/splash-image.png")} /> <View style={style.get("flex-3")} /> <View style={style.flatten(["padding-x-page"])}> <TextInput containerStyle={style.flatten(["padding-bottom-40"])} label="Password" returnKeyType="done" secureTextEntry={true} value={password} error={isFailed ? "Invalid password" : undefined} onChangeText={setPassword} onSubmitEditing={tryUnlock} /> <Button text="Sign in" size="large" loading={isLoading} onPress={tryUnlock} /> {keychainStore.isBiometryOn ? ( <Button containerStyle={style.flatten(["margin-top-40"])} text="Use Biometric Authentication" mode="text" loading={isBiometricLoading} onPress={tryBiometric} /> ) : null} </View> <View style={style.get("flex-7")} /> </KeyboardAwareScrollView> </View> <Animated.View style={StyleSheet.flatten([ style.flatten(["absolute-fill"]), { opacity: animatedContinuityEffectOpacity, }, ])} pointerEvents={isSplashEnd ? "none" : "auto"} > <SplashContinuityEffectView onAnimationEnd={() => { setIsSplashEnd(true); }} /> </Animated.View> </React.Fragment> ); }); const useAnimationState = () => { return useState(() => { return { finished: new Animated.Value<number>(0), position: new Animated.Value<number>(0), time: new Animated.Value<number>(0), frameTime: new Animated.Value<number>(0), }; })[0]; }; export const SplashContinuityEffectView: FunctionComponent<{ onAnimationEnd: () => void; }> = ({ onAnimationEnd }) => { const style = useStyle(); const onAnimationEndRef = useRef(onAnimationEnd); onAnimationEndRef.current = onAnimationEnd; const [isBackgroundLoaded, setIsBackgroundLoaded] = useState(false); const [logoSize, setLogoSize] = useState< | { width: number; height: number; } | undefined >(); const [animation] = useState(() => { return { isStarted: new Animated.Value<number>(0), backgroundClock: new Animated.Clock(), backgroundClippingClock: new Animated.Clock(), backgroundDone: new Animated.Value(0), backgroundClippingDone: new Animated.Value(0), }; }); const backgroundClippingWidth = useAnimationState(); const backgroundClippingHeight = useAnimationState(); const backgroundClippingRadius = useAnimationState(); const backgroundDelay = useAnimationState(); const backgroundWidth = useAnimationState(); const backgroundHeight = useAnimationState(); useEffect(() => { if (isBackgroundLoaded && logoSize) { (async () => { await hideSplashScreen(); animation.isStarted.setValue(1); })(); } }, [animation.isStarted, isBackgroundLoaded, logoSize]); const backgroundClippingAnimationDuration = 700; const backgroundAnimationDuration = 900; const backgroundAnimationDelay = 300; const expectedLogoSize = logoSize ? logoSize.height * (Dimensions.get("window").width / logoSize.width) : 0; const expectedBorderRadius = expectedLogoSize / 4.45; Animated.useCode(() => { return [ Animated.cond( Animated.and( Animated.greaterThan(animation.isStarted, 0), Animated.eq(animation.backgroundClippingDone, 0) ), [ Animated.cond( Animated.not( Animated.clockRunning(animation.backgroundClippingClock) ), [Animated.startClock(animation.backgroundClippingClock)], [ Animated.timing( animation.backgroundClippingClock, backgroundClippingWidth, { duration: backgroundClippingAnimationDuration, easing: Easing.out(Easing.cubic), toValue: 1, } ), Animated.timing( animation.backgroundClippingClock, backgroundClippingHeight, { duration: backgroundClippingAnimationDuration, easing: Easing.out(Easing.cubic), toValue: 1, } ), Animated.timing( animation.backgroundClippingClock, backgroundClippingRadius, { duration: backgroundClippingAnimationDuration, easing: Easing.out(Easing.cubic), toValue: 1, } ), Animated.cond( Animated.and( backgroundClippingWidth.finished, backgroundClippingHeight.finished, backgroundClippingRadius.finished ), [ Animated.set(animation.backgroundClippingDone, 1), Animated.debug( "Background clipping animation is done", Animated.stopClock(animation.backgroundClippingClock) ), ] ), ] ), ] ), ]; }, [ animation.backgroundClippingClock, animation.backgroundClippingDone, animation.isStarted, backgroundClippingHeight, backgroundClippingRadius, backgroundClippingWidth, ]); Animated.useCode(() => { return [ Animated.cond( Animated.and( Animated.greaterThan(animation.isStarted, 0), Animated.eq(animation.backgroundDone, 0) ), [ Animated.cond( Animated.not(Animated.clockRunning(animation.backgroundClock)), [Animated.startClock(animation.backgroundClock)], [ Animated.cond( backgroundDelay.finished, [ Animated.timing(animation.backgroundClock, backgroundWidth, { duration: backgroundAnimationDuration, easing: Easing.out(Easing.quad), toValue: 1, }), Animated.timing(animation.backgroundClock, backgroundHeight, { duration: backgroundAnimationDuration, easing: Easing.out(Easing.quad), toValue: 1, }), Animated.cond( Animated.and( backgroundWidth.finished, backgroundHeight.finished ), [ Animated.set(animation.backgroundDone, 1), Animated.debug( "Background animation is done", Animated.stopClock(animation.backgroundClock) ), Animated.call([], () => { onAnimationEndRef.current(); }), ] ), ], [ // `backgroundDelay` is actually not used for animation, // it is for the delay. Animated.timing(animation.backgroundClock, backgroundDelay, { duration: backgroundAnimationDelay, easing: Easing.ease, toValue: 1, }), Animated.cond(backgroundDelay.finished, [ Animated.debug( "Delay for background animation is reached", backgroundDelay.finished ), ]), ] ), ] ), ] ), ]; }, [ animation.isStarted, animation.backgroundDone, animation.backgroundClock, backgroundDelay, backgroundWidth, backgroundHeight, ]); return ( <React.Fragment> <View style={style.flatten([ "absolute-fill", "background-color-splash-background", ])} /> <View style={style.flatten([ "absolute-fill", "items-center", "justify-center", ])} > <Animated.View style={StyleSheet.flatten([ style.flatten([ "width-full", "height-full", "overflow-hidden", "items-center", "justify-center", ]), { width: backgroundClippingWidth.position.interpolate({ inputRange: [0, 1], outputRange: [Dimensions.get("window").width, expectedLogoSize], }), height: backgroundClippingHeight.position.interpolate({ inputRange: [0, 1], outputRange: [ Dimensions.get("window").height + (StatusBar.currentHeight ?? 0), expectedLogoSize, ], }), borderRadius: backgroundClippingRadius.position.interpolate({ inputRange: [0, 1], outputRange: [0, expectedBorderRadius], }), }, ])} > <Animated.Image style={StyleSheet.flatten([ style.flatten(["width-full", "height-full"]), { width: backgroundWidth.position.interpolate({ inputRange: [0, 1], outputRange: [ Dimensions.get("window").width, expectedLogoSize, ], }), height: backgroundHeight.position.interpolate({ inputRange: [0, 1], outputRange: [ Dimensions.get("window").height + (StatusBar.currentHeight ?? 0), expectedLogoSize, ], }), }, ])} source={require("../../assets/logo/splash-screen-only-background.png")} resizeMode="stretch" fadeDuration={0} onLoadEnd={() => { setIsBackgroundLoaded(true); }} /> </Animated.View> </View> <View style={style.flatten([ "absolute-fill", "items-center", "justify-center", ])} > <Image style={style.flatten(["width-full", "height-full"])} source={require("../../assets/logo/splash-screen-only-k.png")} resizeMode="contain" fadeDuration={0} onLoad={(e) => { setLogoSize(e.nativeEvent.source); }} /> </View> </React.Fragment> ); };
the_stack
import finale from '../utils/finale' import { removeDefaultImport, removeRequireAndImport } from '../utils/imports' import logger from '../utils/logger' const getAssertionExpression = (chaiAssertExpression, assertionName) => ({ type: 'CallExpression', callee: { type: 'MemberExpression', object: chaiAssertExpression, property: { type: 'Identifier', name: assertionName, }, }, }) const assertToExpectMapping = [ { assert: 'ok', expect: 'toBeTruthy', ignoreExpectedValue: true, }, { assert: 'notOk', expect: 'toBeFalsy', ignoreExpectedValue: true, }, { assert: 'isOk', expect: 'toBeTruthy', ignoreExpectedValue: true, }, { assert: 'isNotOk', expect: 'toBeFalsy', ignoreExpectedValue: true, }, { assert: 'equal', expect: 'toEqual', includeNegative: 'notEqual', }, { assert: 'strictEqual', expect: 'toBe', includeNegative: 'notStrictEqual', }, { assert: 'deepEqual', expect: 'toEqual', includeNegative: 'notDeepEqual', }, { assert: 'isAbove', expect: 'toBeGreaterThan', }, { assert: 'isAtLeast', expect: 'toBeGreaterThanOrEqual', }, { assert: 'isBelow', expect: 'toBeLessThan', }, { assert: 'isAtMost', expect: 'toBeLessThanOrEqual', }, { assert: 'isTrue', expect: 'toBe', expectedOverride: true, includeNegative: 'isNotTrue', }, { assert: 'isFalse', expect: 'toBe', expectedOverride: false, includeNegative: 'isNotFalse', }, { assert: 'isNull', expect: 'toBeNull', ignoreExpectedValue: true, includeNegative: 'isNotNull', }, { assert: 'isNaN', expect: 'toBe', ignoreExpectedValue: true, expectedOverride: 'NaN', includeNegative: 'isNotNaN', }, { assert: 'isDefined', expect: 'toBeDefined', ignoreExpectedValue: true, includeNegative: 'isUndefined', }, { assert: 'instanceOf', expect: 'toBeInstanceOf', includeNegative: 'notInstanceOf', }, { assert: 'include', expect: 'toContain', includeNegative: 'notInclude', }, { assert: 'match', expect: 'toMatch', includeNegative: 'notMatch', }, { assert: 'throws', expect: 'toThrow', ignoreExpectedValue: true, includeNegative: 'doesNotThrow', }, { assert: 'sameMembers', expect: 'toEqual', }, { assert: 'sameDeepMembers', expect: 'toEqual', }, { assert: 'nestedProperty', expect: 'toHaveProperty', includeNegative: 'notNestedProperty', }, ] const objectChecks = [ 'isExtensible', 'isNotExtensible', 'isSealed', 'isNotSealed', 'isFrozen', 'isNotFrozen', ] /** * Type checking */ const chaiAssertTypeofs = [ { assert: 'isFunction', type: 'function' }, { assert: 'isObject', type: 'object' }, { assert: 'isString', type: 'string' }, { assert: 'isNumber', type: 'number' }, { assert: 'isBoolean', type: 'boolean' }, ] const getArguments = (path, ignoreExpectedValue, expectedOverride) => { const [actual, originalExpectation] = path.value.arguments const expectation = !ignoreExpectedValue ? expectedOverride || originalExpectation : undefined return expectation ? { actual, expectation } : { actual } } const unsupportedAssertions = [ 'operator', 'changes', 'doesNotChange', 'increases', 'doesNotIncrease', 'decreases', 'doesNotDecrease', ] export default function transformer(fileInfo, api, options) { const j = api.jscodeshift const ast = j(fileInfo.source) let chaiAssertExpression let assertLocalName = removeRequireAndImport(j, ast, 'chai', 'assert') const defaultImportLocalName = removeDefaultImport(j, ast, 'chai') if (assertLocalName) { chaiAssertExpression = { type: 'Identifier', name: assertLocalName, } } else if (defaultImportLocalName) { chaiAssertExpression = { type: 'MemberExpression', object: { type: 'Identifier', name: defaultImportLocalName, }, property: { type: 'Identifier', name: 'assert', }, } } if (!chaiAssertExpression) { if (!options.skipImportDetection) { // No Chai require/import were found return fileInfo.source } assertLocalName = 'assert' chaiAssertExpression = { type: 'Identifier', name: 'assert', } } const logWarning = (msg: string, path) => logger(fileInfo, msg, path) const makeExpectation = (identifier: string, actual: any, expectation: any = []) => j.callExpression( j.memberExpression( j.callExpression(j.identifier('expect'), [actual]), j.identifier(identifier) ), Array.isArray(expectation) ? expectation : [expectation] ) const makeExpectationNamedArguments = ({ identifier, actual, expectation = [], }: { identifier: string actual: any expectation?: any }) => makeExpectation(identifier, actual, expectation) const makeNegativeExpectation = ( identifier: string, actual: any, expectation: any = [] ) => j.callExpression( j.memberExpression( j.memberExpression( j.callExpression(j.identifier('expect'), [actual]), j.identifier('not') ), j.identifier(identifier) ), Array.isArray(expectation) ? expectation : [expectation] ) const makeNegativeExpectationNamedArguments = ({ identifier, actual, expectation = [], }: { identifier: string actual: any expectation?: any }) => makeNegativeExpectation(identifier, actual, expectation) assertToExpectMapping.forEach( ({ assert, expect, ignoreExpectedValue, includeNegative, expectedOverride }) => { let override if (typeof expectedOverride !== 'undefined') { override = typeof expectedOverride === 'boolean' ? j.literal(expectedOverride) : j.identifier(expectedOverride) } ast .find(j.CallExpression, getAssertionExpression(chaiAssertExpression, assert)) .replaceWith((path) => makeExpectationNamedArguments({ identifier: expect, ...getArguments(path, ignoreExpectedValue, override), }) ) if (includeNegative) { ast .find( j.CallExpression, getAssertionExpression(chaiAssertExpression, includeNegative) ) .replaceWith((path) => makeNegativeExpectationNamedArguments({ identifier: expect, ...getArguments(path, ignoreExpectedValue, override), }) ) } } ) unsupportedAssertions.forEach((assertion) => { ast .find(j.CallExpression, getAssertionExpression(chaiAssertExpression, assertion)) .forEach((path) => { logWarning(`Unsupported Chai Assertion "${assertion}".`, path) }) }) ;['approximately', 'closeTo'].forEach((assertion) => { ast .find(j.CallExpression, getAssertionExpression(chaiAssertExpression, assertion)) .replaceWith((path) => makeExpectation( 'toBeLessThanOrEqual', j.callExpression( j.memberExpression(j.identifier('Math'), j.identifier('abs')), [ j.binaryExpression( '-', path.value.arguments[0] as any, path.value.arguments[1] ), ] ), [path.value.arguments[2]] ) ) }) // assert.nestedPropertyVal -> expect(obj).toHaveProperty() ast .find( j.CallExpression, getAssertionExpression(chaiAssertExpression, 'nestedPropertyVal') ) .replaceWith((path) => makeExpectation('toHaveProperty', path.value.arguments[0], [ path.value.arguments[1], path.value.arguments[2], ]) ) // assert.notNestedPropertyVal -> expect(obj).not.toHaveProperty() ast .find( j.CallExpression, getAssertionExpression(chaiAssertExpression, 'notNestedPropertyVal') ) .replaceWith((path) => makeNegativeExpectation('toHaveProperty', path.value.arguments[0], [ path.value.arguments[1], path.value.arguments[2], ]) ) // assert.fail -> expect(false).toBeTruthy() ast .find(j.CallExpression, getAssertionExpression(chaiAssertExpression, 'fail')) .replaceWith((path) => makeExpectation('toBe', j.literal(false), j.literal(true))) // assert.propertyVal -> expect(*.[prop]).toBe() ast .find(j.CallExpression, getAssertionExpression(chaiAssertExpression, 'propertyVal')) .replaceWith((path) => { const [obj, prop, value] = path.value.arguments return makeExpectation('toBe', j.memberExpression(obj, prop), value) }) // assert.propertyNotVal -> expect(*.[prop]).not.toBe() ast .find( j.CallExpression, getAssertionExpression(chaiAssertExpression, 'propertyNotVal') ) .replaceWith((path) => { const [obj, prop, value] = path.value.arguments return makeNegativeExpectation('toBe', j.memberExpression(obj, prop), value) }) // assert.notPropertyVal -> expect(*.[prop]).not.toBe() ast .find( j.CallExpression, getAssertionExpression(chaiAssertExpression, 'notPropertyVal') ) .replaceWith((path) => { const [obj, prop, value] = path.value.arguments return makeNegativeExpectation('toBe', j.memberExpression(obj, prop), value) }) // assert.deepPropertyVal -> expect(*).toHaveProperty(keyPath, ?value) ast .find( j.CallExpression, getAssertionExpression(chaiAssertExpression, 'deepPropertyVal') ) .replaceWith((path) => { const [obj, prop, value] = path.value.arguments return makeExpectation('toHaveProperty', obj, [prop, value]) }) // assert.deepPropertyNotVal -> expect(*).not.toHaveProperty(keyPath, ?value) ast .find( j.CallExpression, getAssertionExpression(chaiAssertExpression, 'deepPropertyNotVal') ) .replaceWith((path) => { const [obj, prop, value] = path.value.arguments return makeNegativeExpectation('toHaveProperty', obj, [prop, value]) }) // assert.notDeepPropertyVal -> expect(*).not.toHaveProperty(keyPath, ?value) ast .find( j.CallExpression, getAssertionExpression(chaiAssertExpression, 'notDeepPropertyVal') ) .replaceWith((path) => { const [obj, prop, value] = path.value.arguments return makeNegativeExpectation('toHaveProperty', obj, [prop, value]) }) // assert.deepProperty -> expect(*).toHaveProperty(keyPath) ast .find(j.CallExpression, getAssertionExpression(chaiAssertExpression, 'deepProperty')) .replaceWith((path) => { const [obj, prop] = path.value.arguments return makeExpectation('toHaveProperty', obj, prop) }) // assert.notDeepProperty -> expect(*).not.toHaveProperty(keyPath) ast .find( j.CallExpression, getAssertionExpression(chaiAssertExpression, 'notDeepProperty') ) .replaceWith((path) => { const [obj, prop] = path.value.arguments return makeNegativeExpectation('toHaveProperty', obj, prop) }) // assert.property -> expect(prop in obj).toBeTruthy() ast .find(j.CallExpression, getAssertionExpression(chaiAssertExpression, 'property')) .replaceWith((path) => makeExpectation( 'toBeTruthy', j.binaryExpression('in', path.value.arguments[1], path.value.arguments[0]) ) ) // assert.notProperty -> expect(prop in obj).toBeFalsy() ast .find(j.CallExpression, getAssertionExpression(chaiAssertExpression, 'notProperty')) .replaceWith((path) => makeExpectation( 'toBeFalsy', j.binaryExpression('in', path.value.arguments[1], path.value.arguments[0]) ) ) // assert.ifError -> expect(*).toBeFalsy() ast .find(j.CallExpression, getAssertionExpression(chaiAssertExpression, 'ifError')) .replaceWith((path) => makeExpectation('toBeFalsy', path.value.arguments[0])) // assert.includeMembers -> expect([]).toEqual(expect.arrayContaining([])) ast .find( j.CallExpression, getAssertionExpression(chaiAssertExpression, 'includeMembers') ) .replaceWith((path) => { return makeExpectation( 'toEqual', path.value.arguments[0], j.callExpression( j.memberExpression(j.identifier('expect'), j.identifier('arrayContaining')), [path.value.arguments[1]] ) ) }) // assert.notIncludeMembers -> expect([]).not.toEqual(expect.arrayContaining([])) ast .find( j.CallExpression, getAssertionExpression(chaiAssertExpression, 'notIncludeMembers') ) .replaceWith((path) => { return makeNegativeExpectation( 'toEqual', path.value.arguments[0], j.callExpression( j.memberExpression(j.identifier('expect'), j.identifier('arrayContaining')), [path.value.arguments[1]] ) ) }) // assert.includeDeepMembers -> expect([]).toEqual(expect.arrayContaining([])) ast .find( j.CallExpression, getAssertionExpression(chaiAssertExpression, 'includeDeepMembers') ) .replaceWith((path) => { return makeExpectation( 'toEqual', path.value.arguments[0], j.callExpression( j.memberExpression(j.identifier('expect'), j.identifier('arrayContaining')), [path.value.arguments[1]] ) ) }) // assert.notIncludeDeepMembers -> expect([]).not.toEqual(expect.arrayContaining([])) ast .find( j.CallExpression, getAssertionExpression(chaiAssertExpression, 'notIncludeDeepMembers') ) .replaceWith((path) => { return makeNegativeExpectation( 'toEqual', path.value.arguments[0], j.callExpression( j.memberExpression(j.identifier('expect'), j.identifier('arrayContaining')), [path.value.arguments[1]] ) ) }) // assert.isArray -> expect(Array.isArray).toBe(true) ast .find(j.CallExpression, getAssertionExpression(chaiAssertExpression, 'isArray')) .replaceWith((path) => makeExpectation( 'toBe', j.callExpression( j.memberExpression(j.identifier('Array'), j.identifier('isArray')), [path.value.arguments[0]] ), j.literal(true) ) ) // assert.isArray -> expect(Array.isArray).toBe(false) ast .find(j.CallExpression, getAssertionExpression(chaiAssertExpression, 'isNotArray')) .replaceWith((path) => makeNegativeExpectation( 'toBe', j.callExpression( j.memberExpression(j.identifier('Array'), j.identifier('isArray')), [path.value.arguments[0]] ), j.literal(true) ) ) // assert.typeOf(foo, Bar) -> expect(typeof foo).toBe(Bar) ast .find(j.CallExpression, getAssertionExpression(chaiAssertExpression, 'typeOf')) .replaceWith((path) => makeExpectation( 'toBe', j.unaryExpression('typeof', path.value.arguments[0]), path.value.arguments[1] ) ) // assert.notTypeOf(foo, Bar) -> expect(typeof foo).not.toBe(Bar) ast .find(j.CallExpression, getAssertionExpression(chaiAssertExpression, 'notTypeOf')) .replaceWith((path) => makeNegativeExpectation( 'toBe', j.unaryExpression('typeof', path.value.arguments[0]), path.value.arguments[1] ) ) chaiAssertTypeofs.forEach(({ assert, type }) => { ast .find(j.CallExpression, getAssertionExpression(chaiAssertExpression, assert)) .replaceWith((path) => makeExpectation( 'toBe', j.unaryExpression('typeof', path.value.arguments[0]), j.literal(type) ) ) ast .find( j.CallExpression, getAssertionExpression(chaiAssertExpression, assert.replace(/^is/, 'isNot')) ) .replaceWith((path) => makeNegativeExpectation( 'toBe', j.unaryExpression('typeof', path.value.arguments[0] as any), j.literal(type) ) ) }) // assert.lengthOf -> expect(*.length).toBe() ast .find(j.CallExpression, getAssertionExpression(chaiAssertExpression, 'lengthOf')) .replaceWith((path) => makeExpectation( 'toBe', j.memberExpression(path.value.arguments[0] as any, j.identifier('length')), path.value.arguments[1] ) ) // Object-specific boolean checks objectChecks.forEach((check) => { const isNegative = check.indexOf('isNot') === 0 const expectation = check.replace('isNot', 'is') ast .find(j.CallExpression, getAssertionExpression(chaiAssertExpression, check)) .replaceWith((path) => (isNegative ? makeNegativeExpectation : makeExpectation)( 'toBe', j.callExpression( j.memberExpression(j.identifier('Object'), j.identifier(expectation)), [path.value.arguments[0]] ), j.literal(true) ) ) }) // assert -> expect().toBeTruthy() ast .find(j.CallExpression, { callee: { type: 'Identifier', name: assertLocalName }, }) .replaceWith((path) => makeExpectation('toBeTruthy', path.value.arguments[0])) return finale(fileInfo, j, ast, options) }
the_stack
import * as React from 'react'; import { cc98Fetch, getToken } from '../../Utility'; import Button from 'antd/es/button'; import Table from 'antd/es/table'; import Checkbox from 'antd/es/checkbox'; import Input from 'antd/es/input'; import * as moment from 'moment'; const PostForumIndexColumnInfoType = [ '推荐阅读', '推荐功能', '校园新闻', '广告' ]; const urls = [ '/index/column/recommandationreading', '/index/column/recommandationfunction', '/index/column/schoolnews', '/config/global/advertisement' ]; class PostForumIndexColumnInfo { id: number; /** * 1=推荐阅读,2=推荐功能,3=校园新闻,4=广告 */ type: number; /** * 必须,广告表示对广告的简单描述 */ title: string; /** * 只有推荐阅读需要 */ content: string; /** * 校园新闻不需要 */ url: string; /** * 校园新闻不需要 */ imageUrl: string; /** * 排序权重,只有推荐阅读和推荐功能需要 */ orderWeight: number; /** * 是否显示 */ enable: boolean; /** * 只有广告需要,大于0的整数 */ days: number; /** * */ isNew: boolean; /** * */ expiredTime: string; } interface State { /** * 反馈信息 */ info: string; /** * 请求时返回的数据 */ data: PostForumIndexColumnInfo[]; /** * 1=推荐阅读,2=推荐功能,3=校园新闻,4=广告 */ type: number; /** * 当前页 */ current: number; } type props = {}; export default class extends React.Component<props, State> { constructor(props) { super(props); this.state = { info: '', data: [], type: 0, current: 1 }; this.getInfo = this.getInfo.bind(this); this.putCurData = this.putCurData.bind(this); this.handleTdChange = this.handleTdChange.bind(this); this.add = this.add.bind(this); } async getInfo(url) { this.setState({ type: urls.indexOf(url) + 1, data: [] }); try { const token: string = await getToken(); let headers = new Headers(); headers.append('Authorization', token); let res = await cc98Fetch(url + '/all', { headers }); let data = await res.json(); this.setState({ data }); } catch (e) { this.setState({ info: e.message }); } } handleTdChange(key, value, index: number) { this.setState(prevState => { let { data } = prevState as State; data[index] = { ...data[index], [key]: value }; //console.log(data); this.setState({ data }); }); } async putCurData(index: number) { let url: string, method: string; if (this.state.data[index].isNew) { url = '/index/column/'; method = 'POST'; } else { url = '/index/column/' + this.state.data[index].id; method = 'PUT'; } try { const token: string = await getToken(); let headers = new Headers(); headers.append('Authorization', token); headers.append('Content-Type', 'application/json'); let res = await cc98Fetch(url, { method: method, headers, body: JSON.stringify(this.state.data[index]) }); if (res.status === 200) { this.setState({ info: '修改成功' }); } else { throw new Error(res.status.toString()); } } catch (e) { this.setState({ info: e.message }); } } add() { this.setState(prevState => { let newData = new PostForumIndexColumnInfo(); newData.enable = true; newData.isNew = true; newData.type = prevState.type; newData.id = prevState.data[0].id + 1; return { data: [newData, ...prevState.data] }; }); } onPageChange = v => { this.setState({ current: v.current }); }; render() { const { current } = this.state; const Columns = [ { title: 'id', dataIndex: 'id', key: 'id', width: 60 }, { title: 'type', dataIndex: 'type', key: 'type', width: 100, render: text => PostForumIndexColumnInfoType[text - 1] }, { title: 'title', dataIndex: 'title', key: 'title', width: 200, render: (text, record, index) => ( <Input type="text" onChange={e => this.handleTdChange( 'title', e.target.value, (current - 1) * 10 + index ) } value={text} /> ) }, this.state.type === 1 ? { title: 'content', dataIndex: 'content', key: 'content', width: 200, render: (text, record, index) => ( <Input type="text" onChange={e => this.handleTdChange( 'content', e.target.value, (current - 1) * 10 + index ) } value={text} /> ) } : null, { title: 'url', dataIndex: 'url', key: 'url', width: 140, render: (text, record, index) => ( <Input type="text" onChange={e => this.handleTdChange( 'url', e.target.value, (current - 1) * 10 + index ) } value={text} /> ) }, this.state.type !== 3 ? { title: 'imageUrl', dataIndex: 'imageUrl', key: 'imageUrl', width: 200, render: (text, record, index) => ( <Input type="text" onChange={e => this.handleTdChange( 'imageUrl', e.target.value, (current - 1) * 10 + index ) } value={text} /> ) } : null, this.state.type === 1 || this.state.type === 2 ? { title: 'orderWeight', dataIndex: 'orderWeight', key: 'orderWeight', width: 150, render: (text, record, index) => ( <Input type="text" onChange={e => this.handleTdChange( 'orderWeight', e.target.value, (current - 1) * 10 + index ) } value={text} /> ) } : null, { title: 'enable', dataIndex: 'enable', key: 'enable', width: 80, render: (text, record, index) => ( <Checkbox checked={text} onChange={e => this.handleTdChange( 'enable', (e.target as HTMLInputElement).checked, (current - 1) * 10 + index ) } /> ) }, this.state.type === 4 ? { title: 'days', dataIndex: 'days', key: 'days', render: (text, record, index) => ( <Input type="text" onChange={e => this.handleTdChange( 'days', e.target.value, (current - 1) * 10 + index ) } value={text} /> ) } : null, this.state.type === 4 ? { title: 'expiredTime', dataIndex: 'expiredTime', key: 'expiredTime', render: text => moment(text).format('YYYY-MM-DD HH:mm:ss') } : null, { title: 'save', dataIndex: 'save', key: 'save', width: 100, render: (text, record, index) => ( <Button type="primary" onClick={e => this.putCurData((current - 1) * 10 + index)} > 保存 </Button> ) } ].filter(v => { if (v) return v; }); return ( <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', marginTop: '1rem', borderTop: '#eaeaea solid thin', paddingTop: '1rem' }} > <div style={{ display: 'flex', justifyContent: 'space-around', alignItems: 'center', width: '100%', marginBottom: '1rem' }} > <div style={{ marginTop: '10px' }}>自定义栏目</div> <div> <Button type="primary" disabled={this.state.type === 1} onClick={() => this.getInfo(urls[0])} > 推荐阅读 </Button> </div> <div> <Button type="primary" disabled={this.state.type === 2} onClick={() => this.getInfo(urls[1])} > 推荐功能 </Button> </div> <div> <Button type="primary" disabled={this.state.type === 3} onClick={() => this.getInfo(urls[2])} > 校园新闻 </Button> </div> <div> <Button type="primary" disabled={this.state.type === 4} onClick={() => this.getInfo(urls[3])} > 广告 </Button> </div> {this.state.type > 0 ? ( <div> <Button type="primary" onClick={() => this.add()}> 添加 </Button> </div> ) : null} </div> <div> <Table bordered onChange={this.onPageChange} columns={Columns} dataSource={this.state.data} /> <p>{this.state.info}</p> </div> </div> ); } } // {this.state.data.length > 0 ? // <table> // <tbody> // <tr> // <th>id</th> // <th>type</th> // <th>title</th> // {this.state.type === 1 ? <th>content</th> : null} // <th>url</th> // {this.state.type !== 3 ? <th>imageUrl</th> : null} // {this.state.type === 1 || this.state.type === 2 ? <th>orderWeight</th> : null} // <th>enable</th> // {this.state.type === 4 ? <th>days</th> : null} // {this.state.type === 4 ? <th>expiredTime</th> : null} // <th>save</th></tr> // {this.state.data.map((item, index) => ( // <tr key={item.id}> // <td>{item.id}</td> // <td>{PostForumIndexColumnInfoType[item.type - 1]}</td> // <td><input type="text" onChange={e => this.handleTdChange('title', e.target.value, index)} value={item.title} /></td> // {this.state.type === 1 ? <td><input type="text" onChange={e => this.handleTdChange('content', e.target.value, index)} value={item.content} /></td> : null} // <td><input type="text" onChange={e => this.handleTdChange('url', e.target.value, index)} value={item.url} /></td> // {this.state.type !== 3 ? <td><input type="text" onChange={e => this.handleTdChange('imageUrl', e.target.value, index)} value={item.imageUrl} /></td> : null} // {this.state.type === 1 || this.state.type === 2 ? <td><input type="number" onChange={e => this.handleTdChange('orderWeight', Number.parseInt(e.target.value), index)} value={item.orderWeight} /></td> : null} // <td><input onChange={e => this.handleTdChange('enable', (e.target as HTMLInputElement).checked, index)} type="checkbox" checked={item.enable} /></td> // {this.state.type === 4 ? <td><input type="number" onChange={e => this.handleTdChange('days', Number.parseInt(e.target.value), index)} value={item.days} /></td> : null} // {this.state.type === 4 && item.expiredTime ? <td>{item.expiredTime.slice(0, 19).replace('T', ' ')}</td> : null} // <td><button type="button" onClick={e => this.putCurData(index)}>保存</button></td> // </tr> // ))} // </tbody> // </table> : null}
the_stack
export const weekday = [ { Day: 'Friday', 'SUM(AIR_TIME)': 1943661 }, { Day: 'Saturday', 'SUM(AIR_TIME)': 1798845 }, { Day: 'Thursday', 'SUM(AIR_TIME)': 1626157 }, { Day: 'Sunday', 'SUM(AIR_TIME)': 1048653 }, ]; export const population = [ { Country: 'China', Population: 58345455000 }, { Country: 'India', Population: 46023037597 }, { Country: 'United States', Population: 13604468357 }, { Country: 'Indonesia', Population: 9357861231 }, { Country: 'Brazil', Population: 7752058955 }, { Country: 'Russian Federation', Population: 7667188460 }, { Country: 'Japan', Population: 6454620759 }, { Country: 'Pakistan', Population: 5696041480 }, { Country: 'Bangladesh', Population: 5549261462 }, { Country: 'Nigeria', Population: 5259800493 }, { Country: 'Mexico', Population: 4444653964 }, { Country: 'Germany', Population: 4361793335 }, { Country: 'Vietnam', Population: 3420037000 }, { Country: 'Philippines', Population: 3272015554 }, { Country: 'United Kingdom', Population: 3169118137 }, { Country: 'France', Population: 3151638853 }, { Country: 'Italy', Population: 3082869665 }, { Country: 'Egypt, Arab Rep.', Population: 2967887581 }, { Country: 'Thailand', Population: 2827157965 }, { Country: 'Turkey', Population: 2805220683 }, { Country: 'Ethiopia', Population: 2750952916 }, { Country: 'Iran, Islamic Rep.', Population: 2717528355 }, { Country: 'Ukraine', Population: 2657782543 }, { Country: 'Korea, Rep.', Population: 2216456927 }, { Country: 'Myanmar', Population: 2126848982 }, { Country: 'Spain', Population: 2115316751 }, { Country: 'Congo, Dem. Rep.', Population: 2015439254 }, { Country: 'Poland', Population: 1976772515 }, { Country: 'South Africa', Population: 1871083248 }, { Country: 'Colombia', Population: 1776189608 }, { Country: 'Argentina', Population: 1728332290 }, { Country: 'Canada', Population: 1470276931 }, { Country: 'Tanzania', Population: 1413734053 }, { Country: 'Algeria', Population: 1317290647 }, { Country: 'Morocco', Population: 1277441301 }, { Country: 'Kenya', Population: 1253201109 }, { Country: 'Romania', Population: 1171333228 }, { Country: 'Peru', Population: 1121937313 }, { Country: 'Sudan', Population: 1118903636 }, { Country: 'Uzbekistan', Population: 1053380227 }, { Country: 'Korea, Dem. Rep.', Population: 1047335229 }, { Country: 'Venezuela, RB', Population: 1036057583 }, { Country: 'Nepal', Population: 1007162709 }, { Country: 'Uganda', Population: 987376102 }, { Country: 'Iraq', Population: 983604177 }, { Country: 'Malaysia', Population: 978122682 }, { Country: 'Australia', Population: 903260509 }, { Country: 'Afghanistan', Population: 887557752 }, { Country: 'Sri Lanka', Population: 881137000 }, { Country: 'Saudi Arabia', Population: 828451525 }, { Country: 'Mozambique', Population: 807229371 }, { Country: 'Netherlands', Population: 803013980 }, { Country: 'Ghana', Population: 801844889 }, { Country: 'Kazakhstan', Population: 797168043 }, { Country: 'Chile', Population: 696739897 }, { Country: 'Yemen, Rep.', Population: 695646128 }, { Country: 'Cameroon', Population: 664127790 }, { Country: 'Syrian Arab Republic', Population: 663924524 }, { Country: 'Madagascar', Population: 656478313 }, { Country: 'Angola', Population: 641906296 }, { Country: "Cote d'Ivoire", Population: 634194484 }, { Country: 'Hungary', Population: 566995908 }, { Country: 'Czech Republic', Population: 559416359 }, { Country: 'Belgium', Population: 551921585 }, { Country: 'Cuba', Population: 550461345 }, { Country: 'Greece', Population: 547065293 }, { Country: 'Ecuador', Population: 537148542 }, { Country: 'Portugal', Population: 536945679 }, { Country: 'Belarus', Population: 524490000 }, { Country: 'Cambodia', Population: 523555378 }, { Country: 'Zimbabwe', Population: 509866860 }, { Country: 'Burkina Faso', Population: 505122912 }, { Country: 'Mali', Population: 500758830 }, { Country: 'Guatemala', Population: 498361800 }, { Country: 'Niger', Population: 471910464 }, { Country: 'Malawi', Population: 470725354 }, { Country: 'Sweden', Population: 468210684 }, { Country: 'Bulgaria', Population: 456247765 }, { Country: 'Zambia', Population: 438847085 }, { Country: 'Austria', Population: 426785647 }, { Country: 'Tunisia', Population: 415992799 }, { Country: 'Senegal', Population: 414475224 }, { Country: 'Haiti', Population: 377521290 }, { Country: 'Azerbaijan', Population: 374210660 }, { Country: 'Dominican Republic', Population: 373939753 }, { Country: 'Switzerland', Population: 369360744 }, { Country: 'Bolivia', Population: 368308373 }, { Country: 'Guinea', Population: 362469063 }, { Country: 'Chad', Population: 355875809 }, { Country: 'Rwanda', Population: 347121852 }, { Country: 'Somalia', Population: 332677926 }, { Country: 'South Sudan', Population: 319024522 }, { Country: 'Burundi', Population: 305731834 }, { Country: 'Hong Kong SAR, China', Population: 298353905 }, { Country: 'Benin', Population: 290736360 }, { Country: 'Denmark', Population: 283435789 }, { Country: 'Slovak Republic', Population: 276228375 }, { Country: 'Finland', Population: 271585488 }, { Country: 'Tajikistan', Population: 267603756 }, { Country: 'El Salvador', Population: 266413287 }, { Country: 'Israel', Population: 263866720 }, { Country: 'Honduras', Population: 257791863 }, { Country: 'Croatia', Population: 246197511 }, { Country: 'Georgia', Population: 241070850 }, { Country: 'Norway', Population: 233337059 }, { Country: 'Papua New Guinea', Population: 228299012 }, { Country: 'Lao PDR', Population: 227340983 }, { Country: 'Kyrgyz Republic', Population: 222809200 }, { Country: 'Paraguay', Population: 221768661 }, { Country: 'Libya', Population: 217716251 }, { Country: 'Bosnia and Herzegovina', Population: 215521543 }, { Country: 'Nicaragua', Population: 213048662 }, { Country: 'Togo', Population: 204624027 }, { Country: 'Sierra Leone', Population: 203443826 }, { Country: 'Ireland', Population: 196019322 }, { Country: 'Turkmenistan', Population: 189687365 }, { Country: 'New Zealand', Population: 187593600 }, { Country: 'Serbia', Population: 186596480 }, { Country: 'Moldova', Population: 186156257 }, { Country: 'Lithuania', Population: 182416949 }, { Country: 'Puerto Rico', Population: 181515497 }, { Country: 'Jordan', Population: 180850641 }, { Country: 'Singapore', Population: 173168000 }, { Country: 'Uruguay', Population: 167612670 }, { Country: 'Costa Rica', Population: 163515714 }, { Country: 'Lebanon', Population: 162031498 }, { Country: 'Eritrea', Population: 161125877 }, { Country: 'Armenia', Population: 160782905 }, { Country: 'Central African Republic', Population: 158650217 }, { Country: 'Albania', Population: 148154320 }, { Country: 'United Arab Emirates', Population: 134952923 }, { Country: 'Panama', Population: 130974461 }, { Country: 'Congo, Rep.', Population: 130701144 }, { Country: 'Latvia', Population: 130544986 }, { Country: 'Liberia', Population: 125666085 }, { Country: 'Jamaica', Population: 124779119 }, { Country: 'Mauritania', Population: 113489314 }, { Country: 'Mongolia', Population: 106717826 }, { Country: 'Slovenia', Population: 104119695 }, { Country: 'Macedonia, FYR', Population: 104100695 }, { Country: 'Oman', Population: 93132249 }, { Country: 'Kosovo', Population: 86627232 }, { Country: 'Kuwait', Population: 84737006 }, { Country: 'Lesotho', Population: 81971241 }, { Country: 'West Bank and Gaza', Population: 77390117 }, { Country: 'Estonia', Population: 77119567 }, { Country: 'Namibia', Population: 75238033 }, { Country: 'Botswana', Population: 70510085 }, { Country: 'Trinidad and Tobago', Population: 62771502 }, { Country: 'Guinea-Bissau', Population: 58400669 }, { Country: 'Mauritius', Population: 56066051 }, { Country: 'Gabon', Population: 52489952 }, { Country: 'Gambia, The', Population: 50232086 }, { Country: 'Cyprus', Population: 43711039 }, { Country: 'Swaziland', Population: 42858935 }, { Country: 'Timor-Leste', Population: 41694123 }, { Country: 'Guyana', Population: 39868752 }, { Country: 'Fiji', Population: 37505227 }, { Country: 'Montenegro', Population: 31652512 }, { Country: 'Qatar', Population: 30075210 }, { Country: 'Bahrain', Population: 29724096 }, { Country: 'Djibouti', Population: 26324244 }, { Country: 'Bhutan', Population: 25987074 }, { Country: 'Comoros', Population: 22692936 }, { Country: 'Suriname', Population: 22687861 }, { Country: 'Equatorial Guinea', Population: 22627794 }, { Country: 'Luxembourg', Population: 21852156 }, { Country: 'Malta', Population: 19363458 }, { Country: 'Cabo Verde', Population: 19178461 }, { Country: 'Macao SAR, China', Population: 18882494 }, { Country: 'Solomon Islands', Population: 16859526 }, { Country: 'Barbados', Population: 14146501 }, { Country: 'Iceland', Population: 13716537 }, { Country: 'Bahamas, The', Population: 13446111 }, { Country: 'Brunei Darussalam', Population: 13322318 }, { Country: 'Maldives', Population: 11478624 }, { Country: 'Belize', Population: 10571460 }, { Country: 'French Polynesia', Population: 9974982 }, { Country: 'New Caledonia', Population: 9225822 }, { Country: 'Samoa', Population: 8770470 }, { Country: 'Vanuatu', Population: 7966814 }, { Country: 'Curacao', Population: 7898637 }, { Country: 'Channel Islands', Population: 7515697 }, { Country: 'St. Lucia', Population: 7336842 }, { Country: 'Guam', Population: 6647797 }, { Country: 'Sao Tome and Principe', Population: 6169644 }, { Country: 'St. Vincent and the Grenadines', Population: 5557117 }, { Country: 'Grenada', Population: 5366107 }, { Country: 'Tonga', Population: 5038574 }, { Country: 'Virgin Islands (U.S.)', Population: 5006756 }, { Country: 'Micronesia, Fed. Sts.', Population: 4627492 }, { Country: 'Aruba', Population: 4048374 }, { Country: 'Antigua and Barbuda', Population: 3887170 }, { Country: 'Dominica', Population: 3881071 }, { Country: 'Kiribati', Population: 3874990 }, { Country: 'Seychelles', Population: 3761184 }, { Country: 'Isle of Man', Population: 3728525 }, { Country: 'Bermuda', Population: 3159267 }, { Country: 'Greenland', Population: 2807533 }, { Country: 'Andorra', Population: 2704725 }, { Country: 'St. Kitts and Nevis', Population: 2535482 }, { Country: 'Faeroe Islands', Population: 2399439 }, { Country: 'American Samoa', Population: 2294886 }, { Country: 'Marshall Islands', Population: 2086174 }, { Country: 'Northern Mariana Islands', Population: 2015842 }, { Country: 'Monaco', Population: 1595554 }, { Country: 'Liechtenstein', Population: 1527171 }, { Country: 'Cayman Islands', Population: 1480956 }, { Country: 'San Marino', Population: 1298411 }, { Country: 'St. Martin (French part)', Population: 1020457 }, { Country: 'Palau', Population: 833299 }, { Country: 'Turks and Caicos Islands', Population: 775185 }, { Country: 'Sint Maarten (Dutch part)', Population: 597781 }, { Country: 'Tuvalu', Population: 466709 }, ];
the_stack
import React from 'react'; export function getDesignerIcon(icon: string) { if (icon === 'routes') return ( <svg className="top-icon" width="32px" height="32px" viewBox="0 0 32 32" id="icon"> <defs> <style>{".cls-1{fill:none;}"}</style> </defs> <path d="M29,10H24v2h5v6H22v2h3v2.142a4,4,0,1,0,2,0V20h2a2.0027,2.0027,0,0,0,2-2V12A2.0023,2.0023,0,0,0,29,10ZM28,26a2,2,0,1,1-2-2A2.0027,2.0027,0,0,1,28,26Z"/> <path d="M19,6H14V8h5v6H12v2h3v6.142a4,4,0,1,0,2,0V16h2a2.0023,2.0023,0,0,0,2-2V8A2.0023,2.0023,0,0,0,19,6ZM18,26a2,2,0,1,1-2-2A2.0027,2.0027,0,0,1,18,26Z"/> <path d="M9,2H3A2.002,2.002,0,0,0,1,4v6a2.002,2.002,0,0,0,2,2H5V22.142a4,4,0,1,0,2,0V12H9a2.002,2.002,0,0,0,2-2V4A2.002,2.002,0,0,0,9,2ZM8,26a2,2,0,1,1-2-2A2.0023,2.0023,0,0,1,8,26ZM3,10V4H9l.0015,6Z"/> <rect id="_Transparent_Rectangle_" data-name="&lt;Transparent Rectangle&gt;" className="cls-1" width="32" height="32"/> </svg>) if (icon === 'rest') return ( <svg className="top-icon" viewBox="0 0 32 32"> <g className="layer"> <title>Layer 1</title> <path d="m23.50007,22l-0.5,0l0,-2l0.5,0a4.4975,4.4975 0 0 0 0.3564,-8.981l-0.8154,-0.0639l-0.0986,-0.812a6.9938,6.9938 0 0 0 -13.8838,0l-0.0991,0.812l-0.8155,0.0639a4.4975,4.4975 0 0 0 0.356,8.981l0.5,0l0,2l-0.5,0a6.4973,6.4973 0 0 1 -1.3,-12.8638a8.9943,8.9943 0 0 1 17.6006,0a6.4974,6.4974 0 0 1 -1.3006,12.8638z" id="svg_1"/> <path d="m22.9724,22.26637l0,-2l-2.1011,0a4.9678,4.9678 0 0 0 -0.7319,-1.7529l1.49,-1.49l-1.414,-1.414l-1.49,1.49a4.9678,4.9678 0 0 0 -1.753,-0.732l0,-2.1011l-2,0l0,2.1011a4.9678,4.9678 0 0 0 -1.7529,0.7319l-1.49,-1.49l-1.414,1.414l1.49,1.49a4.9678,4.9678 0 0 0 -0.732,1.753l-2.1011,0l0,2l2.1011,0a4.9678,4.9678 0 0 0 0.7319,1.7529l-1.49,1.49l1.414,1.414l1.49,-1.49a4.9678,4.9678 0 0 0 1.753,0.732l0,2.1011l2,0l0,-2.1011a4.9678,4.9678 0 0 0 1.7529,-0.7319l1.49,1.49l1.414,-1.414l-1.49,-1.49a4.9678,4.9678 0 0 0 0.732,-1.753l2.1011,0zm-7,2a3,3 0 1 1 3,-3a3.0033,3.0033 0 0 1 -3,3z" id="svg_2" transform="rotate(25 15.9724 21.2664)" xmlns="http://www.w3.org/2000/svg"/> </g> </svg> ) if (icon === 'beans') return ( <svg className="top-icon" width="32px" height="32px" viewBox="0 0 32 32" id="icon"> <defs> <style>{".cls-1 {fill: none;}"}</style> </defs> <title>data--1</title> <rect x="15" y="6" width="13" height="2"/> <rect x="15" y="24" width="13" height="2"/> <rect x="4" y="15" width="13" height="2"/> <path d="M7,11a4,4,0,1,1,4-4A4,4,0,0,1,7,11ZM7,5A2,2,0,1,0,9,7,2,2,0,0,0,7,5Z" transform="translate(0 0)"/> <path d="M7,29a4,4,0,1,1,4-4A4,4,0,0,1,7,29Zm0-6a2,2,0,1,0,2,2A2,2,0,0,0,7,23Z" transform="translate(0 0)"/> <path d="M25,20a4,4,0,1,1,4-4A4,4,0,0,1,25,20Zm0-6a2,2,0,1,0,2,2A2,2,0,0,0,25,14Z" transform="translate(0 0)"/> <g id="_Transparent_Rectangle_" data-name="&lt;Transparent Rectangle&gt;"> <rect className="cls-1" width="32" height="32"/> </g> </svg> ) if (icon === 'dependencies') return ( <svg className="top-icon" width="32px" height="32px" viewBox="0 0 32 32" id="icon"> <defs> <style>{".cls-1 {fill: none;}"}</style> </defs> <title>application</title> <path d="M16,18H6a2,2,0,0,1-2-2V6A2,2,0,0,1,6,4H16a2,2,0,0,1,2,2V16A2,2,0,0,1,16,18ZM6,6V16H16V6Z" transform="translate(0 0)"/> <path d="M26,12v4H22V12h4m0-2H22a2,2,0,0,0-2,2v4a2,2,0,0,0,2,2h4a2,2,0,0,0,2-2V12a2,2,0,0,0-2-2Z" transform="translate(0 0)"/> <path d="M26,22v4H22V22h4m0-2H22a2,2,0,0,0-2,2v4a2,2,0,0,0,2,2h4a2,2,0,0,0,2-2V22a2,2,0,0,0-2-2Z" transform="translate(0 0)"/> <path d="M16,22v4H12V22h4m0-2H12a2,2,0,0,0-2,2v4a2,2,0,0,0,2,2h4a2,2,0,0,0,2-2V22a2,2,0,0,0-2-2Z" transform="translate(0 0)"/> <g id="_Transparent_Rectangle_" data-name="&lt;Transparent Rectangle&gt;"> <rect className="cls-1" width="32" height="32"/> </g> </svg> ) if (icon === 'error') return ( <svg className="top-icon" width="36px" height="36px" viewBox="0 0 36 36" version="1.1" preserveAspectRatio="xMidYMid meet"> <circle className="clr-i-outline clr-i-outline-path-1" cx="18" cy="26.06" r="1.33"/> <path className="clr-i-outline clr-i-outline-path-2" d="M18,22.61a1,1,0,0,1-1-1v-12a1,1,0,1,1,2,0v12A1,1,0,0,1,18,22.61Z"/> <path className="clr-i-outline clr-i-outline-path-3" d="M18,34A16,16,0,1,1,34,18,16,16,0,0,1,18,34ZM18,4A14,14,0,1,0,32,18,14,14,0,0,0,18,4Z"/> <rect x="0" y="0" width="36" height="36" fillOpacity="0"/> </svg>) if (icon === 'exception') return ( <svg className="top-icon" width="32px" height="32px" viewBox="0 0 32 32" id="icon"> <defs> <style>{".cls-1{fill:none;}"}</style> </defs> <title>misuse--alt</title> <polygon points="21.41 23 16 17.591 10.59 23 9 21.41 14.409 16 9 10.591 10.591 9 16 14.409 21.409 9 23 10.591 17.591 16 23 21.41 21.41 23"/> <path d="M16,4A12,12,0,1,1,4,16,12.0136,12.0136,0,0,1,16,4m0-2A14,14,0,1,0,30,16,14,14,0,0,0,16,2Z" transform="translate(0)"/> <rect id="_Transparent_Rectangle_" data-name="&lt;Transparent Rectangle&gt;" className="cls-1" width="32" height="32"/> </svg>) if (icon === 'template') return ( <svg className="top-icon" width="32px" height="32px" viewBox="0 0 32 32" id="icon" xmlns="http://www.w3.org/2000/svg"> <defs> <style>{".cls-1{fill:none;}"}</style> </defs> <title>code</title> <polygon points="31 16 24 23 22.59 21.59 28.17 16 22.59 10.41 24 9 31 16"/> <polygon points="1 16 8 9 9.41 10.41 3.83 16 9.41 21.59 8 23 1 16"/> <rect x="5.91" y="15" width="20.17" height="2" transform="translate(-3.6 27.31) rotate(-75)"/> <rect id="_Transparent_Rectangle_" data-name="&lt;Transparent Rectangle&gt;" className="cls-1" width="32" height="32" transform="translate(0 32) rotate(-90)"/> </svg>) if (icon === 'traits') return ( <svg className="top-icon" width="32px" height="32px" viewBox="0 0 32 32" id="icon"> <defs> <style>{".cls-1{fill:none;}"}</style> </defs> <title>settings</title> <path d="M27,16.76c0-.25,0-.5,0-.76s0-.51,0-.77l1.92-1.68A2,2,0,0,0,29.3,11L26.94,7a2,2,0,0,0-1.73-1,2,2,0,0,0-.64.1l-2.43.82a11.35,11.35,0,0,0-1.31-.75l-.51-2.52a2,2,0,0,0-2-1.61H13.64a2,2,0,0,0-2,1.61l-.51,2.52a11.48,11.48,0,0,0-1.32.75L7.43,6.06A2,2,0,0,0,6.79,6,2,2,0,0,0,5.06,7L2.7,11a2,2,0,0,0,.41,2.51L5,15.24c0,.25,0,.5,0,.76s0,.51,0,.77L3.11,18.45A2,2,0,0,0,2.7,21L5.06,25a2,2,0,0,0,1.73,1,2,2,0,0,0,.64-.1l2.43-.82a11.35,11.35,0,0,0,1.31.75l.51,2.52a2,2,0,0,0,2,1.61h4.72a2,2,0,0,0,2-1.61l.51-2.52a11.48,11.48,0,0,0,1.32-.75l2.42.82a2,2,0,0,0,.64.1,2,2,0,0,0,1.73-1L29.3,21a2,2,0,0,0-.41-2.51ZM25.21,24l-3.43-1.16a8.86,8.86,0,0,1-2.71,1.57L18.36,28H13.64l-.71-3.55a9.36,9.36,0,0,1-2.7-1.57L6.79,24,4.43,20l2.72-2.4a8.9,8.9,0,0,1,0-3.13L4.43,12,6.79,8l3.43,1.16a8.86,8.86,0,0,1,2.71-1.57L13.64,4h4.72l.71,3.55a9.36,9.36,0,0,1,2.7,1.57L25.21,8,27.57,12l-2.72,2.4a8.9,8.9,0,0,1,0,3.13L27.57,20Z" transform="translate(0 0)"/> <path d="M16,22a6,6,0,1,1,6-6A5.94,5.94,0,0,1,16,22Zm0-10a3.91,3.91,0,0,0-4,4,3.91,3.91,0,0,0,4,4,3.91,3.91,0,0,0,4-4A3.91,3.91,0,0,0,16,12Z" transform="translate(0 0)"/> <rect id="_Transparent_Rectangle_" data-name="&lt;Transparent Rectangle&gt;" className="cls-1" width="32" height="32"/> </svg>) if (icon === 'yaml') return ( <svg className="top-icon" x="0px" y="0px" width="32px" height="32px" viewBox="0 0 32 32"> <style type="text/css">{".st0{fill:none;}"}</style> <title>document</title> <path d="M25.7,9.3l-7-7C18.5,2.1,18.3,2,18,2H8C6.9,2,6,2.9,6,4v24c0,1.1,0.9,2,2,2h16c1.1,0,2-0.9,2-2V10C26,9.7,25.9,9.5,25.7,9.3 z M18,4.4l5.6,5.6H18V4.4z M24,28H8V4h8v6c0,1.1,0.9,2,2,2h6V28z"/> <rect x="10" y="22" width="12" height="2"/> <rect x="10" y="16" width="12" height="2"/> <rect className="st0" width="32" height="32"/> </svg>) if (icon === 'code') return ( <svg className="top-icon" width="32px" height="32px" viewBox="0 0 32 32" id="icon"> <defs> <style>{".cls-1{fill:none;}"}</style> </defs> <title>code</title> <polygon points="31 16 24 23 22.59 21.59 28.17 16 22.59 10.41 24 9 31 16"/> <polygon points="1 16 8 9 9.41 10.41 3.83 16 9.41 21.59 8 23 1 16"/> <rect x="5.91" y="15" width="20.17" height="2" transform="translate(-3.6 27.31) rotate(-75)"/> <rect id="_Transparent_Rectangle_" data-name="&lt;Transparent Rectangle&gt;" className="cls-1" width="32" height="32" transform="translate(0 32) rotate(-90)"/> </svg>) } export class BeanIcon extends React.Component<any> { render() { return ( <svg className="icon" width="32px" height="32px" viewBox="0 0 32 32" id="icon"> <defs> <style>{".cls-1 {fill: none;}"}</style> </defs> <title>data--1</title> <rect x="15" y="6" width="13" height="2"/> <rect x="15" y="24" width="13" height="2"/> <rect x="4" y="15" width="13" height="2"/> <path d="M7,11a4,4,0,1,1,4-4A4,4,0,0,1,7,11ZM7,5A2,2,0,1,0,9,7,2,2,0,0,0,7,5Z" transform="translate(0 0)"/> <path d="M7,29a4,4,0,1,1,4-4A4,4,0,0,1,7,29Zm0-6a2,2,0,1,0,2,2A2,2,0,0,0,7,23Z" transform="translate(0 0)"/> <path d="M25,20a4,4,0,1,1,4-4A4,4,0,0,1,25,20Zm0-6a2,2,0,1,0,2,2A2,2,0,0,0,25,14Z" transform="translate(0 0)"/> <g id="_Transparent_Rectangle_" data-name="&lt;Transparent Rectangle&gt;"> <rect className="cls-1" width="32" height="32"/> </g> </svg> ) } } export class DependencyIcon extends React.Component<any> { render() { return ( <svg className="icon" width="32px" height="32px" viewBox="0 0 32 32" id="icon"> <defs> <style>{".cls-1 {fill: none;}"}</style> </defs> <title>application</title> <path d="M16,18H6a2,2,0,0,1-2-2V6A2,2,0,0,1,6,4H16a2,2,0,0,1,2,2V16A2,2,0,0,1,16,18ZM6,6V16H16V6Z" transform="translate(0 0)"/> <path d="M26,12v4H22V12h4m0-2H22a2,2,0,0,0-2,2v4a2,2,0,0,0,2,2h4a2,2,0,0,0,2-2V12a2,2,0,0,0-2-2Z" transform="translate(0 0)"/> <path d="M26,22v4H22V22h4m0-2H22a2,2,0,0,0-2,2v4a2,2,0,0,0,2,2h4a2,2,0,0,0,2-2V22a2,2,0,0,0-2-2Z" transform="translate(0 0)"/> <path d="M16,22v4H12V22h4m0-2H12a2,2,0,0,0-2,2v4a2,2,0,0,0,2,2h4a2,2,0,0,0,2-2V22a2,2,0,0,0-2-2Z" transform="translate(0 0)"/> <g id="_Transparent_Rectangle_" data-name="&lt;Transparent Rectangle&gt;"> <rect className="cls-1" width="32" height="32"/> </g> </svg> ) } } export class RestIcon extends React.Component<any> { render() { return ( <svg className="icon" viewBox="0 0 32 32"> <g className="layer"> <title>Layer 1</title> <path d="m23.50007,22l-0.5,0l0,-2l0.5,0a4.4975,4.4975 0 0 0 0.3564,-8.981l-0.8154,-0.0639l-0.0986,-0.812a6.9938,6.9938 0 0 0 -13.8838,0l-0.0991,0.812l-0.8155,0.0639a4.4975,4.4975 0 0 0 0.356,8.981l0.5,0l0,2l-0.5,0a6.4973,6.4973 0 0 1 -1.3,-12.8638a8.9943,8.9943 0 0 1 17.6006,0a6.4974,6.4974 0 0 1 -1.3006,12.8638z" id="svg_1"/> <path d="m22.9724,22.26637l0,-2l-2.1011,0a4.9678,4.9678 0 0 0 -0.7319,-1.7529l1.49,-1.49l-1.414,-1.414l-1.49,1.49a4.9678,4.9678 0 0 0 -1.753,-0.732l0,-2.1011l-2,0l0,2.1011a4.9678,4.9678 0 0 0 -1.7529,0.7319l-1.49,-1.49l-1.414,1.414l1.49,1.49a4.9678,4.9678 0 0 0 -0.732,1.753l-2.1011,0l0,2l2.1011,0a4.9678,4.9678 0 0 0 0.7319,1.7529l-1.49,1.49l1.414,1.414l1.49,-1.49a4.9678,4.9678 0 0 0 1.753,0.732l0,2.1011l2,0l0,-2.1011a4.9678,4.9678 0 0 0 1.7529,-0.7319l1.49,1.49l1.414,-1.414l-1.49,-1.49a4.9678,4.9678 0 0 0 0.732,-1.753l2.1011,0zm-7,2a3,3 0 1 1 3,-3a3.0033,3.0033 0 0 1 -3,3z" id="svg_2" transform="rotate(25 15.9724 21.2664)" xmlns="http://www.w3.org/2000/svg"/> </g> </svg> ) } } export class ConceptIcon extends React.Component<any> { render() { return ( <svg className="icon" width="32px" height="32px" viewBox="0 0 32 32"> <defs> <style>{".cls-1 {fill: none;}"}</style> </defs> <title>concept</title> <path d="M20.8851,19.4711a5.9609,5.9609,0,0,0,0-6.9422L23,10.4141l1.293,1.2929a.9995.9995,0,0,0,1.414,0l4-4a.9994.9994,0,0,0,0-1.414l-4-4a.9994.9994,0,0,0-1.414,0l-4,4a.9994.9994,0,0,0,0,1.414L21.5859,9l-2.1148,2.1149a5.9609,5.9609,0,0,0-6.9422,0L10,8.5859V2H2v8H8.5859l2.529,2.5289a5.9609,5.9609,0,0,0,0,6.9422L9,21.5859,7.707,20.293a.9994.9994,0,0,0-1.414,0l-4,4a.9994.9994,0,0,0,0,1.414l4,4a.9995.9995,0,0,0,1.414,0l4-4a.9994.9994,0,0,0,0-1.414L10.4141,23l2.1148-2.1149a5.9609,5.9609,0,0,0,6.9422,0L22,23.4141V30h8V22H23.4141ZM25,4.4141,27.5859,7,25,9.5859,22.4141,7ZM7,27.5859,4.4141,25,7,22.4141,9.5859,25ZM8,8H4V4H8Zm4,8a4,4,0,1,1,4,4A4.0045,4.0045,0,0,1,12,16Zm12,8h4v4H24Z"/> <rect id="_Transparent_Rectangle_" data-name="&lt;Transparent Rectangle&gt;" className="cls-1" width="32" height="32"/> </svg> ) } }
the_stack
import { Constants, PersistentCacheKeys, TemporaryCacheKeys, ErrorCacheKeys, ServerHashParamKeys, SESSION_STORAGE} from "../utils/Constants"; import { AccessTokenCacheItem } from "./AccessTokenCacheItem"; import { CacheLocation } from "../Configuration"; import { BrowserStorage } from "./BrowserStorage"; import { RequestUtils } from "../utils/RequestUtils"; import { AccessTokenKey } from "./AccessTokenKey"; import { StringUtils } from "../utils/StringUtils"; import { IdToken } from "../IdToken"; /** * @hidden */ export class AuthCache extends BrowserStorage {// Singleton private clientId: string; private rollbackEnabled: boolean; private temporaryCache: BrowserStorage; constructor(clientId: string, cacheLocation: CacheLocation, storeAuthStateInCookie: boolean) { super(cacheLocation); this.temporaryCache = new BrowserStorage(SESSION_STORAGE); this.clientId = clientId; // This is hardcoded to true for now. We may make this configurable in the future this.rollbackEnabled = true; this.migrateCacheEntries(storeAuthStateInCookie); } /** * Support roll back to old cache schema until the next major release: true by default now * @param storeAuthStateInCookie */ private migrateCacheEntries(storeAuthStateInCookie: boolean) { const idTokenKey = `${Constants.cachePrefix}.${PersistentCacheKeys.IDTOKEN}`; const clientInfoKey = `${Constants.cachePrefix}.${PersistentCacheKeys.CLIENT_INFO}`; const errorKey = `${Constants.cachePrefix}.${ErrorCacheKeys.ERROR}`; const errorDescKey = `${Constants.cachePrefix}.${ErrorCacheKeys.ERROR_DESC}`; const idTokenValue = super.getItem(idTokenKey); let idToken; if (idTokenValue) { try { idToken = new IdToken(idTokenValue); } catch (e) { return; } } if (idToken && idToken.claims && idToken.claims.aud === this.clientId) { const clientInfoValue = super.getItem(clientInfoKey); const errorValue = super.getItem(errorKey); const errorDescValue = super.getItem(errorDescKey); const values = [idTokenValue, clientInfoValue, errorValue, errorDescValue]; const keysToMigrate = [PersistentCacheKeys.IDTOKEN, PersistentCacheKeys.CLIENT_INFO,ErrorCacheKeys.ERROR, ErrorCacheKeys.ERROR_DESC]; keysToMigrate.forEach((cacheKey, index) => this.duplicateCacheEntry(cacheKey, values[index], storeAuthStateInCookie)); } } /** * Utility function to help with roll back keys * @param newKey * @param value * @param storeAuthStateInCookie */ private duplicateCacheEntry(newKey: string, value: string, storeAuthStateInCookie?: boolean) { if (value) { this.setItem(newKey, value, storeAuthStateInCookie); } } /** * Prepend msal.<client-id> to each key; Skip for any JSON object as Key (defined schemas do not need the key appended: AccessToken Keys or the upcoming schema) * @param key * @param addInstanceId */ private generateCacheKey(key: string, addInstanceId: boolean): string { try { // Defined schemas do not need the key appended JSON.parse(key); return key; } catch (e) { if (key.indexOf(`${Constants.cachePrefix}`) === 0 || key.indexOf(Constants.adalIdToken) === 0){ return key; } return addInstanceId ? `${Constants.cachePrefix}.${this.clientId}.${key}` : `${Constants.cachePrefix}.${key}`; } } /** * Validates that the input cache key contains the account search terms (clientId and homeAccountIdentifier) and * then whether or not it contains the "scopes", depending on the token type being searched for. With matching account * search terms, Access Token search tries to match the "scopes" keyword, while Id Token search expects "scopes" to not be included. * @param key * @param clientId * @param homeAccountIdentifier * @param tokenType */ private matchKeyForType(key:string, clientId: string, homeAccountIdentifier: string, tokenType: string): AccessTokenKey { // All valid token cache item keys are valid JSON objects, ignore keys that aren't const parsedKey = StringUtils.validateAndParseJsonCacheKey(key); if (!parsedKey) { return null; } // Does the cache item match the request account const accountMatches = key.match(clientId) && key.match(homeAccountIdentifier); // Does the cache item match the requested token type let tokenTypeMatches = false; switch (tokenType) { case ServerHashParamKeys.ACCESS_TOKEN: // Cache item is an access token if scopes are included in the cache item key tokenTypeMatches = !!key.match(Constants.scopes); break; case ServerHashParamKeys.ID_TOKEN: // Cache may be an ID token if scopes are NOT included in the cache item key tokenTypeMatches = !key.match(Constants.scopes); break; } return (accountMatches && tokenTypeMatches) ? parsedKey : null; } /** * add value to storage * @param key * @param value * @param enableCookieStorage */ setItem(key: string, value: string, enableCookieStorage?: boolean): void { super.setItem(this.generateCacheKey(key, true), value, enableCookieStorage); // Values stored in cookies will have rollback disabled to minimize cookie length if (this.rollbackEnabled && !enableCookieStorage) { super.setItem(this.generateCacheKey(key, false), value, enableCookieStorage); } } /** * get one item by key from storage * @param key * @param enableCookieStorage */ getItem(key: string, enableCookieStorage?: boolean): string { return super.getItem(this.generateCacheKey(key, true), enableCookieStorage); } /** * remove value from storage * @param key */ removeItem(key: string): void { this.temporaryCache.removeItem(this.generateCacheKey(key, true)); super.removeItem(this.generateCacheKey(key, true)); if (this.rollbackEnabled) { super.removeItem(this.generateCacheKey(key, false)); } } /** * Sets temporary cache value * @param key * @param value * @param enableCookieStorage */ setTemporaryItem(key: string, value: string, enableCookieStorage?: boolean): void { this.temporaryCache.setItem(this.generateCacheKey(key, true), value, enableCookieStorage); } /** * Gets temporary cache value * @param key * @param enableCookieStorage */ getTemporaryItem(key: string, enableCookieStorage?: boolean): string { return this.temporaryCache.getItem(this.generateCacheKey(key, true), enableCookieStorage); } /** * Reset the cache items */ resetCacheItems(): void { const storage = window[this.cacheLocation]; let key: string; for (key in storage) { // Check if key contains msal prefix; For now, we are clearing all cache items created by MSAL.js if (storage.hasOwnProperty(key) && (key.indexOf(Constants.cachePrefix) !== -1)) { super.removeItem(key); // TODO: Clear cache based on client id (clarify use cases where this is needed) } } } /** * Reset all temporary cache items */ resetTempCacheItems(state?: string): void { const stateId = state && RequestUtils.parseLibraryState(state).id; const isTokenRenewalInProgress = this.tokenRenewalInProgress(state); const storage = window[this.cacheLocation]; // check state and remove associated cache if (stateId && !isTokenRenewalInProgress) { Object.keys(storage).forEach(key => { if (key.indexOf(stateId) !== -1) { this.removeItem(key); super.clearItemCookie(key); } }); } // delete the interaction status cache this.setInteractionInProgress(false); this.removeItem(TemporaryCacheKeys.REDIRECT_REQUEST); } /** * Set cookies for IE * @param cName * @param cValue * @param expires */ setItemCookie(cName: string, cValue: string, expires?: number): void { super.setItemCookie(this.generateCacheKey(cName, true), cValue, expires); if (this.rollbackEnabled) { super.setItemCookie(this.generateCacheKey(cName, false), cValue, expires); } } clearItemCookie(cName: string): void { super.clearItemCookie(this.generateCacheKey(cName, true)); if (this.rollbackEnabled) { super.clearItemCookie(this.generateCacheKey(cName, false)); } } /** * get one item by key from cookies * @param cName */ getItemCookie(cName: string): string { return super.getItemCookie(this.generateCacheKey(cName, true)); } /** * Get all tokens of a certain type from the cache * @param clientId * @param homeAccountIdentifier * @param tokenType */ getAllTokensByType(clientId: string, homeAccountIdentifier: string, tokenType: string): Array<AccessTokenCacheItem> { const results = Object.keys(window[this.cacheLocation]).reduce((tokens, key) => { const matchedTokenKey: AccessTokenKey = this.matchKeyForType(key, clientId, homeAccountIdentifier, tokenType); if (matchedTokenKey) { const value = this.getItem(key); if (value) { try { const newAccessTokenCacheItem = new AccessTokenCacheItem(matchedTokenKey, JSON.parse(value)); return tokens.concat([ newAccessTokenCacheItem ]); } catch (err) { // Skip cache items with non-valid JSON values return tokens; } } } return tokens; }, []); return results; } /** * Get all access tokens in the cache * @param clientId * @param homeAccountIdentifier */ getAllAccessTokens(clientId: string, homeAccountIdentifier: string): Array<AccessTokenCacheItem> { return this.getAllTokensByType(clientId, homeAccountIdentifier, ServerHashParamKeys.ACCESS_TOKEN); } /** * Get all id tokens in the cache in the form of AccessTokenCacheItem objects so they are * in a normalized format and can make use of the existing cached access token validation logic */ getAllIdTokens(clientId: string, homeAccountIdentifier: string): Array<AccessTokenCacheItem> { return this.getAllTokensByType(clientId, homeAccountIdentifier, ServerHashParamKeys.ID_TOKEN); } /** * Get all access and ID tokens in the cache * @param clientId * @param homeAccountIdentifier */ getAllTokens(clientId: string, homeAccountIdentifier: string): Array<AccessTokenCacheItem> { const accessTokens = this.getAllAccessTokens(clientId, homeAccountIdentifier); const idTokens = this.getAllIdTokens(clientId, homeAccountIdentifier); return [...accessTokens, ...idTokens]; } /** * Returns whether or not interaction is currently in progress. Optionally scope it to just this clientId * @param forThisClient */ isInteractionInProgress(matchClientId: boolean): boolean { const clientId = this.getInteractionInProgress(); if (matchClientId) { return clientId === this.clientId; } else { return !!clientId; } } /** * Returns the clientId of the interaction currently in progress */ getInteractionInProgress(): string { return this.getTemporaryItem(this.generateCacheKey(TemporaryCacheKeys.INTERACTION_STATUS, false)); } /** * Sets interaction in progress state * @param isInProgress */ setInteractionInProgress(newInProgressValue: boolean): void { if (newInProgressValue && !this.isInteractionInProgress(false)) { // Ensure we don't overwrite interaction in progress for a different clientId this.setTemporaryItem(this.generateCacheKey(TemporaryCacheKeys.INTERACTION_STATUS, false), this.clientId); } else if (!newInProgressValue && this.isInteractionInProgress(true)) { // Only remove if the current in progress interaction is for this clientId this.removeItem(this.generateCacheKey(TemporaryCacheKeys.INTERACTION_STATUS, false)); } } /** * Return if the token renewal is still in progress * * @param stateValue */ private tokenRenewalInProgress(stateValue: string): boolean { const renewStatus = this.getItem(AuthCache.generateTemporaryCacheKey(TemporaryCacheKeys.RENEW_STATUS, stateValue)); return !!(renewStatus && renewStatus === Constants.inProgress); } /** * Clear all cookies */ public clearMsalCookie(state?: string): void { /* * If state is truthy, remove values associated with that request. * Otherwise, remove all MSAL cookies. */ if (state) { this.clearItemCookie(AuthCache.generateTemporaryCacheKey(TemporaryCacheKeys.NONCE_IDTOKEN, state)); this.clearItemCookie(AuthCache.generateTemporaryCacheKey(TemporaryCacheKeys.STATE_LOGIN, state)); this.clearItemCookie(AuthCache.generateTemporaryCacheKey(TemporaryCacheKeys.LOGIN_REQUEST, state)); this.clearItemCookie(AuthCache.generateTemporaryCacheKey(TemporaryCacheKeys.STATE_ACQ_TOKEN, state)); } else { const cookies = document.cookie.split(";"); cookies.forEach(cookieString => { const [ cookieName ] = cookieString.trim().split("="); if (cookieName.indexOf(Constants.cachePrefix) > -1) { super.clearItemCookie(cookieName); } }); } } /** * Create acquireTokenAccountKey to cache account object * @param accountId * @param state */ public static generateAcquireTokenAccountKey(accountId: string, state: string): string { const stateId = RequestUtils.parseLibraryState(state).id; return `${TemporaryCacheKeys.ACQUIRE_TOKEN_ACCOUNT}${Constants.resourceDelimiter}${accountId}${Constants.resourceDelimiter}${stateId}`; } /** * Create authorityKey to cache authority * @param state */ public static generateAuthorityKey(state: string): string { return AuthCache.generateTemporaryCacheKey(TemporaryCacheKeys.AUTHORITY, state); } /** * Generates the cache key for temporary cache items, using request state * @param tempCacheKey Cache key prefix * @param state Request state value */ public static generateTemporaryCacheKey(tempCacheKey: TemporaryCacheKeys, state: string): string { // Use the state id (a guid), in the interest of shorter key names, which is important for cookies. const stateId = RequestUtils.parseLibraryState(state).id; return `${tempCacheKey}${Constants.resourceDelimiter}${stateId}`; } }
the_stack
declare const enum FBSDKDefaultAudience { Friends = 0, OnlyMe = 1, Everyone = 2 } declare class FBSDKDeviceLoginCodeInfo extends NSObject { static alloc(): FBSDKDeviceLoginCodeInfo; // inherited from NSObject static new(): FBSDKDeviceLoginCodeInfo; // inherited from NSObject readonly expirationDate: Date; readonly identifier: string; readonly loginCode: string; readonly pollingInterval: number; readonly verificationURL: NSURL; } declare const enum FBSDKDeviceLoginError { ExcessivePolling = 1349172, AuthorizationDeclined = 1349173, AuthorizationPending = 1349174, CodeExpired = 1349152 } declare class FBSDKDeviceLoginManager extends NSObject implements NSNetServiceDelegate { static alloc(): FBSDKDeviceLoginManager; // inherited from NSObject static new(): FBSDKDeviceLoginManager; // inherited from NSObject delegate: FBSDKDeviceLoginManagerDelegate; readonly permissions: NSArray<string>; redirectURL: NSURL; readonly debugDescription: string; // inherited from NSObjectProtocol readonly description: string; // inherited from NSObjectProtocol readonly hash: number; // inherited from NSObjectProtocol readonly isProxy: boolean; // inherited from NSObjectProtocol readonly superclass: typeof NSObject; // inherited from NSObjectProtocol readonly // inherited from NSObjectProtocol constructor(o: { permissions: NSArray<string> | string[]; enableSmartLogin: boolean; }); cancel(): void; class(): typeof NSObject; conformsToProtocol(aProtocol: any /* Protocol */): boolean; initWithPermissionsEnableSmartLogin(permissions: NSArray<string> | string[], enableSmartLogin: boolean): this; isEqual(object: any): boolean; isKindOfClass(aClass: typeof NSObject): boolean; isMemberOfClass(aClass: typeof NSObject): boolean; netServiceDidAcceptConnectionWithInputStreamOutputStream(sender: NSNetService, inputStream: NSInputStream, outputStream: NSOutputStream): void; netServiceDidNotPublish(sender: NSNetService, errorDict: NSDictionary<string, number>): void; netServiceDidNotResolve(sender: NSNetService, errorDict: NSDictionary<string, number>): void; netServiceDidPublish(sender: NSNetService): void; netServiceDidResolveAddress(sender: NSNetService): void; netServiceDidStop(sender: NSNetService): void; netServiceDidUpdateTXTRecordData(sender: NSNetService, data: NSData): void; netServiceWillPublish(sender: NSNetService): void; netServiceWillResolve(sender: NSNetService): void; performSelector(aSelector: string): any; performSelectorWithObject(aSelector: string, object: any): any; performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any; respondsToSelector(aSelector: string): boolean; retainCount(): number; self(): this; start(): void; } interface FBSDKDeviceLoginManagerDelegate extends NSObjectProtocol { deviceLoginManagerCompletedWithResultError(loginManager: FBSDKDeviceLoginManager, result: FBSDKDeviceLoginManagerResult, error: NSError): void; deviceLoginManagerStartedWithCodeInfo(loginManager: FBSDKDeviceLoginManager, codeInfo: FBSDKDeviceLoginCodeInfo): void; } declare var FBSDKDeviceLoginManagerDelegate: { prototype: FBSDKDeviceLoginManagerDelegate; }; declare class FBSDKDeviceLoginManagerResult extends NSObject { static alloc(): FBSDKDeviceLoginManagerResult; // inherited from NSObject static new(): FBSDKDeviceLoginManagerResult; // inherited from NSObject readonly accessToken: FBSDKAccessToken; readonly cancelled: boolean; } declare var FBSDKLoginAuthTypeReauthorize: string; declare var FBSDKLoginAuthTypeRerequest: string; declare class FBSDKLoginButton extends FBSDKButton { static alloc(): FBSDKLoginButton; // inherited from NSObject static appearance(): FBSDKLoginButton; // inherited from UIAppearance static appearanceForTraitCollection(trait: UITraitCollection): FBSDKLoginButton; // inherited from UIAppearance static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): FBSDKLoginButton; // inherited from UIAppearance static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): FBSDKLoginButton; // inherited from UIAppearance static appearanceWhenContainedIn(ContainerClass: typeof NSObject): FBSDKLoginButton; // inherited from UIAppearance static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): FBSDKLoginButton; // inherited from UIAppearance static buttonWithConfigurationPrimaryAction(configuration: UIButtonConfiguration, primaryAction: UIAction): FBSDKLoginButton; // inherited from UIButton static buttonWithType(buttonType: UIButtonType): FBSDKLoginButton; // inherited from UIButton static buttonWithTypePrimaryAction(buttonType: UIButtonType, primaryAction: UIAction): FBSDKLoginButton; // inherited from UIButton static new(): FBSDKLoginButton; // inherited from NSObject static systemButtonWithImageTargetAction(image: UIImage, target: any, action: string): FBSDKLoginButton; // inherited from UIButton static systemButtonWithPrimaryAction(primaryAction: UIAction): FBSDKLoginButton; // inherited from UIButton authType: string; defaultAudience: FBSDKDefaultAudience; delegate: FBSDKLoginButtonDelegate; loginTracking: FBSDKLoginTracking; messengerPageId: string; nonce: string; permissions: NSArray<string>; tooltipBehavior: FBSDKLoginButtonTooltipBehavior; tooltipColorStyle: FBSDKTooltipColorStyle; } interface FBSDKLoginButtonDelegate extends NSObjectProtocol { loginButtonDidCompleteWithResultError(loginButton: FBSDKLoginButton, result: FBSDKLoginManagerLoginResult, error: NSError): void; loginButtonDidLogOut(loginButton: FBSDKLoginButton): void; loginButtonWillLogin?(loginButton: FBSDKLoginButton): boolean; } declare var FBSDKLoginButtonDelegate: { prototype: FBSDKLoginButtonDelegate; }; declare const enum FBSDKLoginButtonTooltipBehavior { Automatic = 0, ForceDisplay = 1, Disable = 2 } declare class FBSDKLoginConfiguration extends NSObject { static alloc(): FBSDKLoginConfiguration; // inherited from NSObject static authTypeForString(rawValue: string): string; static new(): FBSDKLoginConfiguration; // inherited from NSObject readonly authType: string; readonly messengerPageId: string; readonly nonce: string; readonly tracking: FBSDKLoginTracking; constructor(o: { permissions: NSArray<string> | string[]; tracking: FBSDKLoginTracking; }); constructor(o: { permissions: NSArray<string> | string[]; tracking: FBSDKLoginTracking; messengerPageId: string; }); constructor(o: { permissions: NSArray<string> | string[]; tracking: FBSDKLoginTracking; messengerPageId: string; authType: string; }); constructor(o: { permissions: NSArray<string> | string[]; tracking: FBSDKLoginTracking; nonce: string; }); constructor(o: { permissions: NSArray<string> | string[]; tracking: FBSDKLoginTracking; nonce: string; messengerPageId: string; }); constructor(o: { permissions: NSArray<string> | string[]; tracking: FBSDKLoginTracking; nonce: string; messengerPageId: string; authType: string; }); constructor(o: { tracking: FBSDKLoginTracking; }); initWithPermissionsTracking(permissions: NSArray<string> | string[], tracking: FBSDKLoginTracking): this; initWithPermissionsTrackingMessengerPageId(permissions: NSArray<string> | string[], tracking: FBSDKLoginTracking, messengerPageId: string): this; initWithPermissionsTrackingMessengerPageIdAuthType(permissions: NSArray<string> | string[], tracking: FBSDKLoginTracking, messengerPageId: string, authType: string): this; initWithPermissionsTrackingNonce(permissions: NSArray<string> | string[], tracking: FBSDKLoginTracking, nonce: string): this; initWithPermissionsTrackingNonceMessengerPageId(permissions: NSArray<string> | string[], tracking: FBSDKLoginTracking, nonce: string, messengerPageId: string): this; initWithPermissionsTrackingNonceMessengerPageIdAuthType(permissions: NSArray<string> | string[], tracking: FBSDKLoginTracking, nonce: string, messengerPageId: string, authType: string): this; initWithTracking(tracking: FBSDKLoginTracking): this; } declare const enum FBSDKLoginError { Reserved = 300, Unknown = 301, PasswordChanged = 302, UserCheckpointed = 303, UserMismatch = 304, UnconfirmedUser = 305, SystemAccountAppDisabled = 306, SystemAccountUnavailable = 307, BadChallengeString = 308, InvalidIDToken = 309, MissingAccessToken = 310 } declare var FBSDKLoginErrorDomain: string; declare class FBSDKLoginManager extends NSObject { static alloc(): FBSDKLoginManager; // inherited from NSObject static new(): FBSDKLoginManager; // inherited from NSObject defaultAudience: FBSDKDefaultAudience; logInFromViewControllerConfigurationCompletion(viewController: UIViewController, configuration: FBSDKLoginConfiguration, completion: (p1: FBSDKLoginManagerLoginResult, p2: NSError) => void): void; logInWithPermissionsFromViewControllerHandler(permissions: NSArray<string> | string[], fromViewController: UIViewController, handler: (p1: FBSDKLoginManagerLoginResult, p2: NSError) => void): void; logInWithURLHandler(url: NSURL, handler: (p1: FBSDKLoginManagerLoginResult, p2: NSError) => void): void; logOut(): void; reauthorizeDataAccessHandler(fromViewController: UIViewController, handler: (p1: FBSDKLoginManagerLoginResult, p2: NSError) => void): void; } declare class FBSDKLoginManagerLoginResult extends NSObject { static alloc(): FBSDKLoginManagerLoginResult; // inherited from NSObject static new(): FBSDKLoginManagerLoginResult; // inherited from NSObject authenticationToken: FBSDKAuthenticationToken; declinedPermissions: NSSet<string>; grantedPermissions: NSSet<string>; readonly isCancelled: boolean; token: FBSDKAccessToken; constructor(o: { token: FBSDKAccessToken; authenticationToken: FBSDKAuthenticationToken; isCancelled: boolean; grantedPermissions: NSSet<string>; declinedPermissions: NSSet<string>; }); initWithTokenAuthenticationTokenIsCancelledGrantedPermissionsDeclinedPermissions(token: FBSDKAccessToken, authenticationToken: FBSDKAuthenticationToken, isCancelled: boolean, grantedPermissions: NSSet<string>, declinedPermissions: NSSet<string>): this; } declare class FBSDKLoginTooltipView extends FBSDKTooltipView { static alloc(): FBSDKLoginTooltipView; // inherited from NSObject static appearance(): FBSDKLoginTooltipView; // inherited from UIAppearance static appearanceForTraitCollection(trait: UITraitCollection): FBSDKLoginTooltipView; // inherited from UIAppearance static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): FBSDKLoginTooltipView; // inherited from UIAppearance static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): FBSDKLoginTooltipView; // inherited from UIAppearance static appearanceWhenContainedIn(ContainerClass: typeof NSObject): FBSDKLoginTooltipView; // inherited from UIAppearance static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): FBSDKLoginTooltipView; // inherited from UIAppearance static new(): FBSDKLoginTooltipView; // inherited from NSObject delegate: FBSDKLoginTooltipViewDelegate; forceDisplay: boolean; } interface FBSDKLoginTooltipViewDelegate extends NSObjectProtocol { loginTooltipViewShouldAppear?(view: FBSDKLoginTooltipView, appIsEligible: boolean): boolean; loginTooltipViewWillAppear?(view: FBSDKLoginTooltipView): void; loginTooltipViewWillNotAppear?(view: FBSDKLoginTooltipView): void; } declare var FBSDKLoginTooltipViewDelegate: { prototype: FBSDKLoginTooltipViewDelegate; }; declare const enum FBSDKLoginTracking { Enabled = 0, Limited = 1 } declare class FBSDKReferralCode extends NSObject { static alloc(): FBSDKReferralCode; // inherited from NSObject static initWithString(string: string): FBSDKReferralCode; static new(): FBSDKReferralCode; // inherited from NSObject value: string; } declare class FBSDKReferralManager extends NSObject { static alloc(): FBSDKReferralManager; // inherited from NSObject static new(): FBSDKReferralManager; // inherited from NSObject constructor(o: { viewController: UIViewController; }); initWithViewController(viewController: UIViewController): this; startReferralWithCompletionHandler(handler: (p1: FBSDKReferralManagerResult, p2: NSError) => void): void; } declare class FBSDKReferralManagerResult extends NSObject { static alloc(): FBSDKReferralManagerResult; // inherited from NSObject static new(): FBSDKReferralManagerResult; // inherited from NSObject readonly isCancelled: boolean; referralCodes: NSArray<FBSDKReferralCode>; constructor(o: { referralCodes: NSArray<FBSDKReferralCode> | FBSDKReferralCode[]; isCancelled: boolean; }); initWithReferralCodesIsCancelled(referralCodes: NSArray<FBSDKReferralCode> | FBSDKReferralCode[], isCancelled: boolean): this; } declare const enum FBSDKTooltipColorStyle { FriendlyBlue = 0, NeutralGray = 1 } declare class FBSDKTooltipView extends UIView { static alloc(): FBSDKTooltipView; // inherited from NSObject static appearance(): FBSDKTooltipView; // inherited from UIAppearance static appearanceForTraitCollection(trait: UITraitCollection): FBSDKTooltipView; // inherited from UIAppearance static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): FBSDKTooltipView; // inherited from UIAppearance static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): FBSDKTooltipView; // inherited from UIAppearance static appearanceWhenContainedIn(ContainerClass: typeof NSObject): FBSDKTooltipView; // inherited from UIAppearance static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): FBSDKTooltipView; // inherited from UIAppearance static new(): FBSDKTooltipView; // inherited from NSObject colorStyle: FBSDKTooltipColorStyle; displayDuration: number; message: string; tagline: string; constructor(o: { tagline: string; message: string; colorStyle: FBSDKTooltipColorStyle; }); dismiss(): void; initWithTaglineMessageColorStyle(tagline: string, message: string, colorStyle: FBSDKTooltipColorStyle): this; presentFromView(anchorView: UIView): void; presentInViewWithArrowPositionDirection(view: UIView, arrowPosition: CGPoint, arrowDirection: FBSDKTooltipViewArrowDirection): void; } declare const enum FBSDKTooltipViewArrowDirection { Down = 0, Up = 1 }
the_stack
import { Base } from "../class/Base.js" import { CI } from "../collection/Iterator.js" import { DEBUG, warn } from "../environment/Debug.js" import { cycleInfo, OnCycleAction, WalkStep } from "../graph/WalkDepth.js" import { CalculationContext, runGeneratorAsyncWithEffect, SynchronousCalculationStarted } from "../primitives/Calculation.js" import { delay, MAX_SMI } from "../util/Helpers.js" import { LeveledQueue } from "../util/LeveledQueue.js" import { BreakCurrentStackExecution, Effect, RejectEffect } from "./Effect.js" import { ChronoGraph, CommitArguments } from "./Graph.js" import { Identifier, Levels, throwUnknownIdentifier } from "./Identifier.js" import { EdgeType, Quark, TombStone } from "./Quark.js" import { Revision, Scope } from "./Revision.js" import { ComputationCycle, TransactionCycleDetectionWalkContext } from "./TransactionCycleDetectionWalkContext.js" import { TransactionWalkDepth } from "./TransactionWalkDepth.js" //--------------------------------------------------------------------------------------------------------------------- export type NotPromise<T> = T extends Promise<any> ? never : T /** * A type for the value, that can be yielded as an effect. */ export type YieldableValue = Effect | Identifier | Promise<any> /** * A type for the synchronous effect handler function */ export type SyncEffectHandler = <T extends any>(effect : YieldableValue) => T & NotPromise<T> export type AsyncEffectHandler = <T extends any>(effect : YieldableValue) => Promise<T> //--------------------------------------------------------------------------------------------------------------------- // weird stack overflow on 1300 deep benchmark, when using `EdgeType.Normal` w/o aliasing it to constant first export const EdgeTypeNormal = EdgeType.Normal export const EdgeTypePast = EdgeType.Past //--------------------------------------------------------------------------------------------------------------------- export type TransactionCommitResult = { revision : Revision, entries : Scope, transaction : Transaction } //--------------------------------------------------------------------------------------------------------------------- export class Transaction extends Base { baseRevision : Revision = undefined candidateClass : typeof Revision = Revision candidate : Revision = undefined graph : ChronoGraph = undefined isClosed : boolean = false walkContext : TransactionWalkDepth = undefined entries : Map<Identifier, Quark> = new Map() // // we use 2 different stacks, because they support various effects // stackSync : LeveledQueue<Quark> = new LeveledQueue() // the `stackGen` supports async effects notably stackGen : LeveledQueue<Quark> = new LeveledQueue() // is used for tracking the active quark entry (quark entry being computed) activeStack : Quark[] = [] onEffectSync : SyncEffectHandler = undefined onEffectAsync : AsyncEffectHandler = undefined //--------------------- propagationStartDate : number = 0 lastProgressNotificationDate : number = 0 startProgressNotificationsAfterMs : number = 500 emitProgressNotificationsEveryMs : number = 200 // TODO auto-adjust this parameter to match the emitProgressNotificationsEveryMs (to avoid calls to time functions) emitProgressNotificationsEveryCalculations : number = 100 plannedTotalIdentifiersToCalculate : number = 0 // writes : WriteInfo[] = [] ongoing : Promise<any> = Promise.resolve() selfDependedMarked : boolean = false rejectedWith : RejectEffect<unknown> = undefined initialize (...args) { super.initialize(...args) this.walkContext = TransactionWalkDepth.new({ visited : this.entries, transaction : this, baseRevision : this.baseRevision, pushTo : this.stackGen }) if (!this.candidate) this.candidate = this.candidateClass.new({ previous : this.baseRevision }) // the `onEffectSync` should be bound to the `yieldSync` of course, and `yieldSync` should look like: // yieldSync (effect : YieldableValue) : any { // if (effect instanceof Identifier) return this.read(effect) // } // however, the latter consumes more stack frames - every read goes through `yieldSync` // since `read` is the most used effect anyway, we bind `onEffectSync` to `read` and // instead inside of `read` delegate to `yieldSync` for non-identifiers this.onEffectSync = /*this.onEffectAsync =*/ this.read.bind(this) this.onEffectAsync = this.readAsync.bind(this) } get dirty () : boolean { return this.entries.size > 0 } get dirtyProposed () : boolean { return CI(this.entries.values()).some(quark => quark.hasProposedValue()) } markSelfDependent () { if (this.selfDependedMarked) return this.selfDependedMarked = true for (const selfDependentIden of this.baseRevision.selfDependent) { const existing = this.entries.get(selfDependentIden) if (existing && existing.getValue() === TombStone) continue this.touch(selfDependentIden) } } // onNewWrite () { // this.writes.forEach(writeInfo => { // const identifier = writeInfo.identifier // // identifier.write.call(identifier.context || identifier, identifier, this, null, ...writeInfo.proposedArgs) // }) // // this.writes.length = 0 // } getActiveEntry () : Quark { return this.activeStack[ this.activeStack.length - 1 ] // // `stackSync` is always empty, except when the synchronous "batch" is being processed // const activeStack = this.stackSync.length > 0 ? this.stackSync : this.stackGen // // return activeStack.last() } yieldAsync (effect : Effect) : Promise<any> { if (effect instanceof Promise) return effect return this.graph[ effect.handler ](effect, this) } // see the comment for the `onEffectSync` yieldSync (effect : Effect) : any { if (effect instanceof Promise) { throw new Error("Can not yield a promise in the synchronous context") } return this.graph[ effect.handler ](effect, this) } // this seems to be an optimistic version readAsync<T> (identifier : Identifier<T>) : Promise<T> { // see the comment for the `onEffectSync` if (!(identifier instanceof Identifier)) return this.yieldAsync(identifier as Effect) let entry : Quark const activeEntry = this.getActiveEntry() if (activeEntry) { entry = this.addEdge(identifier, activeEntry, EdgeTypeNormal) } else { entry = this.entries.get(identifier) if (!entry) { const previousEntry = this.baseRevision.getLatestEntryFor(identifier) if (!previousEntry) throwUnknownIdentifier(identifier) entry = previousEntry.hasValue() ? previousEntry : this.touch(identifier) } } if (entry.hasValue()) return entry.getValue() if (entry.promise) return entry.promise //---------------------- // TODO should use `onReadIdentifier` somehow? to have the same control flow for reading sync/gen identifiers? // now need to repeat the logic if (!entry.previous || !entry.previous.hasValue()) entry.forceCalculation() return this.ongoing = entry.promise = this.ongoing.then(() => { return (async () => { //---------------------- while (this.stackGen.lowestLevel < identifier.level) { await runGeneratorAsyncWithEffect(this.onEffectAsync, this.calculateTransitionsStackGen, [ this.onEffectAsync, this.stackGen.takeLowestLevel() ], this) } this.markSelfDependent() // entry might be already calculated (in the `ongoing` promise), so no need to calculate it if (entry.getValue() === undefined) return runGeneratorAsyncWithEffect(this.onEffectAsync, this.calculateTransitionsStackGen, [ this.onEffectAsync, [ entry ] ], this) })() }).then(() => { if (this.rejectedWith) throw new Error(`Transaction rejected: ${String(this.rejectedWith.reason)}`) // we clear the promise in the `resetToEpoch` should be enough? // entry.promise = undefined // TODO review this exception if (!entry.hasValue()) throw new Error('Computation cycle. Sync') return entry.getValue() }) } get<T> (identifier : Identifier<T>) : T | Promise<T> { // see the comment for the `onEffectSync` if (!(identifier instanceof Identifier)) return this.yieldSync(identifier as Effect) let entry : Quark const activeEntry = this.getActiveEntry() if (activeEntry) { entry = this.addEdge(identifier, activeEntry, EdgeTypeNormal) } else { entry = this.entries.get(identifier) if (!entry) { const previousEntry = this.baseRevision.getLatestEntryFor(identifier) if (!previousEntry) throwUnknownIdentifier(identifier) entry = previousEntry.hasValue() ? previousEntry : this.touch(identifier) } } const value1 = entry.getValue() if (value1 === TombStone) throwUnknownIdentifier(identifier) // the `&& entry.hasValue()` part was added to allow KEEP_TRYING_TO_RESOLVE feature for references if (value1 !== undefined && entry.hasValue()) return value1 if (entry.promise) return entry.promise //---------------------- // TODO should use `onReadIdentifier` somehow? to have the same control flow for reading sync/gen identifiers? // now need to repeat the logic if (!entry.previous || !entry.previous.hasValue()) entry.forceCalculation() //---------------------- while (this.stackGen.getLowestLevel() < identifier.level) { // here we force the computations for lower level identifiers should be sync this.calculateTransitionsStackSync(this.onEffectSync, this.stackGen.takeLowestLevel()) } this.markSelfDependent() if (identifier.sync) { this.calculateTransitionsStackSync(this.onEffectSync, [ entry ]) const value = entry.getValue() // TODO review this exception if (value === undefined) throw new Error('Cycle during synchronous computation') if (value === TombStone) throwUnknownIdentifier(identifier) return value } else { const promise = this.ongoing = entry.promise = this.ongoing.then(() => { // entry might be already calculated (in the `ongoing` promise), so no need to calculate it if (entry.getValue() === undefined) return runGeneratorAsyncWithEffect(this.onEffectAsync, this.calculateTransitionsStackGen, [ this.onEffectAsync, [ entry ] ], this) }).then(() => { if (this.rejectedWith) throw new Error(`Transaction rejected: ${String(this.rejectedWith.reason)}`) // we clear the promise in the `resetToEpoch` should be enough? // entry.promise = undefined const value = entry.getValue() // TODO review this exception if (value === undefined) throw new Error('Computation cycle. Async get') if (value === TombStone) throwUnknownIdentifier(identifier) return value // // TODO review this exception // if (!entry.hasValue()) throw new Error('Computation cycle. Async get') // // return entry.getValue() }) if (DEBUG) { // @ts-ignore promise.quark = entry } return promise // return runGeneratorAsyncWithEffect(this.onEffectAsync, this.calculateTransitionsStackGen, [ this.onEffectAsync, [ entry ] ], this).then(() => { // const value = entry.getValue() // // // TODO review this exception // if (value === undefined) throw new Error('Cycle during synchronous computation') // if (value === TombStone) throwUnknownIdentifier(identifier) // // return value // }) } } // this seems to be an optimistic version read<T> (identifier : Identifier<T>) : T { // see the comment for the `onEffectSync` if (!(identifier instanceof Identifier)) return this.yieldSync(identifier as Effect) let entry : Quark const activeEntry = this.getActiveEntry() if (activeEntry) { entry = this.addEdge(identifier, activeEntry, EdgeTypeNormal) } else { entry = this.entries.get(identifier) if (!entry) { const previousEntry = this.baseRevision.getLatestEntryFor(identifier) if (!previousEntry) throwUnknownIdentifier(identifier) entry = previousEntry.hasValue() ? previousEntry : this.touch(identifier) } } const value1 = entry.getValue() if (value1 === TombStone) throwUnknownIdentifier(identifier) if (value1 !== undefined) return value1 // if (!identifier.sync) throw new Error("Can not calculate asynchronous identifier synchronously") // TODO should use `onReadIdentifier` somehow? to have the same control flow for reading sync/gen identifiers? // now need to repeat the logic if (!entry.previous || !entry.previous.hasValue()) entry.forceCalculation() //---------------------- while (this.stackGen.getLowestLevel() < identifier.level) { this.calculateTransitionsStackSync(this.onEffectSync, this.stackGen.takeLowestLevel()) } //---------------------- this.markSelfDependent() this.calculateTransitionsStackSync(this.onEffectSync, [ entry ]) const value = entry.getValue() // TODO review this exception if (value === undefined) throw new Error('Cycle during synchronous computation') if (value === TombStone) throwUnknownIdentifier(identifier) return value } // semantic is actually - read the most-fresh value readCurrentOrProposedOrPrevious<T> (identifier : Identifier<T>) : T { const dirtyQuark = this.entries.get(identifier) if (dirtyQuark) { const value = dirtyQuark.getValue() if (value !== undefined) return value if (dirtyQuark.proposedValue !== undefined) return dirtyQuark.proposedValue } return this.readPrevious(identifier) } readCurrentOrProposedOrPreviousAsync<T> (identifier : Identifier<T>) : Promise<T> { const dirtyQuark = this.entries.get(identifier) if (dirtyQuark) { const value = dirtyQuark.getValue() if (value !== undefined) return value if (dirtyQuark.proposedValue !== undefined) return dirtyQuark.proposedValue } return this.readPreviousAsync(identifier) } readPrevious<T> (identifier : Identifier<T>) : T { const previousEntry = this.baseRevision.getLatestEntryFor(identifier) if (!previousEntry) return undefined const value = previousEntry.getValue() return value !== TombStone ? (value === undefined && identifier.lazy ? this.read(identifier) : value) : undefined } readPreviousAsync<T> (identifier : Identifier<T>) : Promise<T> { const previousEntry = this.baseRevision.getLatestEntryFor(identifier) if (!previousEntry) return undefined const value = previousEntry.getValue() return value !== TombStone ? (value !== undefined ? value : this.readAsync(identifier)) : undefined } readProposedOrPrevious<T> (identifier : Identifier<T>) : T { const dirtyQuark = this.entries.get(identifier) if (dirtyQuark && dirtyQuark.proposedValue !== undefined) { return dirtyQuark.proposedValue } else { return this.readPrevious(identifier) } } readProposedOrPreviousAsync<T> (identifier : Identifier<T>) : Promise<T> { const dirtyQuark = this.entries.get(identifier) if (dirtyQuark && dirtyQuark.proposedValue !== undefined) { return dirtyQuark.proposedValue } else { return this.readPreviousAsync(identifier) } } write (identifier : Identifier, proposedValue : any, ...args : any[]) { if (proposedValue === undefined) proposedValue = null // this.writes.push(WriteEffect.new({ // identifier : identifier, // proposedArgs : [ proposedValue, ...args ] // })) // // this.onNewWrite() identifier.write.call(identifier.context || identifier, identifier, this, null, /*this.getWriteTarget(identifier),*/ proposedValue, ...args) } // acquireQuark<T extends Identifier> (identifier : T) : InstanceType<T[ 'quarkClass' ]> { // return this.touch(identifier).startOrigin() as InstanceType<T[ 'quarkClass' ]> // } getWriteTarget<T extends Identifier> (identifier : T) : InstanceType<T[ 'quarkClass' ]> { return this.touch(identifier).startOrigin() as InstanceType<T[ 'quarkClass' ]> } // return quark if it exists and is non-shadowing, otherwise undefined acquireQuarkIfExists<T extends Identifier> (identifier : T) : InstanceType<T[ 'quarkClass' ]> | undefined { const entry = this.entries.get(identifier) return entry && entry.origin === entry ? entry.origin as InstanceType<T[ 'quarkClass' ]> : undefined } touch (identifier : Identifier) : Quark { const existingEntry = this.entries.get(identifier) if (!existingEntry || existingEntry.visitEpoch < this.walkContext.currentEpoch) this.walkContext.continueFrom([ identifier ]) const entry = existingEntry || this.entries.get(identifier) entry.forceCalculation() return entry } // touchInvalidate (identifier : Identifier) : Quark { // const existingEntry = this.entries.get(identifier) // // if (existingEntry && existingEntry.hasValue()) { // this.walkContext.startNewEpoch() // } // // if (!existingEntry || existingEntry.visitEpoch < this.walkContext.currentEpoch) this.walkContext.continueFrom([ identifier ]) // // const entry = existingEntry || this.entries.get(identifier) // // entry.forceCalculation() // // return entry // } hasIdentifier (identifier : Identifier) : boolean { const activeEntry = this.entries.get(identifier) if (activeEntry && activeEntry.getValue() === TombStone) return false return Boolean(activeEntry || this.baseRevision.getLatestEntryFor(identifier)) } // this is actually an optimized version of `write`, which skips the graph walk phase // (since the identifier is assumed to be new, there should be no dependent quarks) addIdentifier (identifier : Identifier, proposedValue? : any, ...args : any[]) : Quark { // however, the identifier may be already in the transaction, for example if the `write` method // of some other identifier writes to this identifier let entry : Quark = this.entries.get(identifier) const isVariable = identifier.level === Levels.UserInput if (!entry) { entry = identifier.newQuark(this.baseRevision) entry.previous = this.baseRevision.getLatestEntryFor(identifier) entry.forceCalculation() this.entries.set(identifier, entry) if (!identifier.lazy && !isVariable) this.stackGen.push(entry) } if (proposedValue !== undefined || isVariable) { // TODO change to `this.write()` entry.startOrigin() identifier.write.call(identifier.context || identifier, identifier, this, entry, proposedValue === undefined && isVariable ? null : proposedValue, ...args) } // if we are re-adding the same identifier in the same transaction, clear the TombStone flag if (entry.getValue() === TombStone) entry.value = undefined identifier.enterGraph(this.graph) return entry } removeIdentifier (identifier : Identifier) { identifier.leaveGraph(this.graph) const entry = this.touch(identifier).startOrigin() entry.setValue(TombStone) } populateCandidateScopeFromTransitions (candidate : Revision, scope : Map<Identifier, Quark>) { if (candidate.scope.size === 0) { // in this branch we can overwrite the whole map candidate.scope = scope } else { // in this branch candidate's scope already has some content - this is the case for calculating lazy values // // TODO benchmark what is faster (for small maps) - `map.forEach(entry => {})` or `for (const entry of map) {}` // entries.forEach((entry : QuarkEntry, identifier : Identifier) => { // candidate.scope.set(identifier, entry) // }) for (const [ identifier, quark ] of scope) { if (quark.isShadow()) { const latestEntry = candidate.getLatestEntryFor(identifier) // TODO remove the origin/shadowing concepts? this line won't be needed then // and we iterate over the edges from "origin" anyway quark.getOutgoing().forEach((toQuark, toIdentifier) => latestEntry.getOutgoing().set(toIdentifier, toQuark)) } else { candidate.scope.set(identifier, quark) } } } } preCommit (args? : CommitArguments) { if (this.isClosed) throw new Error('Can not propagate closed revision') this.markSelfDependent() this.isClosed = true this.propagationStartDate = Date.now() this.plannedTotalIdentifiersToCalculate = this.stackGen.length } postCommit () : TransactionCommitResult { this.populateCandidateScopeFromTransitions(this.candidate, this.entries) // won't be available after next line const entries = this.entries // for some reason need to cleanup the `walkContext` manually, otherwise the extra revisions hangs in memory this.walkContext = undefined return { revision : this.candidate, entries, transaction : this } } commit (args? : CommitArguments) : TransactionCommitResult { this.preCommit(args) this.calculateTransitionsSync(this.onEffectSync) // runGeneratorSyncWithEffect(this.onEffectSync, this.calculateTransitionsStackGen, [ this.onEffectSync, stack ], this) return this.postCommit() } reject (rejection : RejectEffect<unknown> = RejectEffect.new()) { this.rejectedWith = rejection this.walkContext = undefined } clearRejected () { for (const quark of this.entries.values()) { quark.cleanup() // quark.clearOutgoing() } this.entries.clear() } // // propagation that does not use generators at all // propagateSync (args? : PropagateArguments) : TransactionPropagateResult { // const stack = this.prePropagate(args) // // this.calculateTransitionsStackSync(this.onEffectSync, stack) // // runGeneratorSyncWithEffect(this.onEffectSync, this.calculateTransitionsStackGen, [ this.onEffectSync, stack ], this) // // return this.postPropagate() // } async commitAsync (args? : CommitArguments) : Promise<TransactionCommitResult> { this.preCommit(args) return this.ongoing = this.ongoing.then(() => { return runGeneratorAsyncWithEffect(this.onEffectAsync, this.calculateTransitions, [ this.onEffectAsync ], this) }).then(() => { return this.postCommit() }) // await runGeneratorAsyncWithEffect(this.onEffectAsync, this.calculateTransitions, [ this.onEffectAsync ], this) // // return this.postCommit() } getLatestEntryFor (identifier : Identifier) : Quark { let entry : Quark = this.entries.get(identifier) || this.baseRevision.getLatestEntryFor(identifier) if (entry.getValue() === TombStone) return undefined return entry } // check the transaction "entries" first, but only return an entry // from that, if it is already calculated, otherwise - take it // from the base revision getLatestStableEntryFor (identifier : Identifier) : Quark { let entry : Quark = this.entries.get(identifier) if (entry) { const value = entry.getValue() if (value === TombStone) return undefined return value === undefined ? this.baseRevision.getLatestEntryFor(identifier) : entry } else { return this.baseRevision.getLatestEntryFor(identifier) } } addEdge (identifierRead : Identifier, activeEntry : Quark, type : EdgeType) : Quark { const identifier = activeEntry.identifier if (identifier.level < identifierRead.level) throw new Error('Identifier can not read from higher level identifier') let entry : Quark = this.entries.get(identifierRead) // creating "shadowing" entry, to store the new edges if (!entry) { const previousEntry = this.baseRevision.getLatestEntryFor(identifierRead) if (!previousEntry) throwUnknownIdentifier(identifierRead) entry = identifierRead.newQuark(this.baseRevision) previousEntry.origin && entry.setOrigin(previousEntry.origin) entry.previous = previousEntry this.entries.set(identifierRead, entry) } entry.addOutgoingTo(activeEntry, type) return entry } onQuarkCalculationCompleted (entry : Quark, value : any) { // cleanup the iterator entry.cleanup() const identifier = entry.identifier const previousEntry = entry.previous //-------------------- const sameAsPrevious = Boolean(previousEntry && previousEntry.hasValue() && identifier.equality(value, previousEntry.getValue())) if (sameAsPrevious) { previousEntry.outgoingInTheFutureAndPastTransactionCb(this, previousOutgoingEntry => { const outgoingEntry = this.entries.get(previousOutgoingEntry.identifier) if (outgoingEntry) outgoingEntry.edgesFlow-- }) // this is a "workaround" for the following problem: // there might be several copies of the same quark in the calculation stack, this is normal // because if quark is requested by some other quark it is just pushed to the stack, // which may already contain this quark // then when the quark is calculated (this code) it propagates the `edgesFlow` decrease // but next time it will be encountered in the stack, its `edgesFlow` might be decreased by other // identifiers, which will trigger another round of `edgesFlow` decrease propagation // so we set the `edgesFlow` to MAX_SMI after decrease been propagated to prevent repeated such propagation entry.edgesFlow = MAX_SMI entry.setOrigin(previousEntry.origin) // seems not needed anymore? // this is to indicate that this entry should be recalculated (origin removed) // see `resetToEpoch` entry.value = value } else { entry.startOrigin() entry.setValue(value) } //-------------------- let ignoreSelfDependency : boolean = false if (entry.usedProposedOrPrevious) { if (entry.proposedValue !== undefined) { if (identifier.equality(value, entry.proposedValue)) ignoreSelfDependency = true } else { // ignore the uninitialized atoms (`proposedValue` === undefined && !previousEntry) // which has been calculated to `null` - we don't consider this as a change if (sameAsPrevious || (!previousEntry && value === null)) ignoreSelfDependency = true } if (!ignoreSelfDependency) this.candidate.selfDependent.add(identifier) } } onReadIdentifier (identifierRead : Identifier, activeEntry : Quark, stack : Quark[]) : IteratorResult<any> | undefined | ComputationCycle { const requestedEntry = this.addEdge(identifierRead, activeEntry, EdgeTypeNormal) // this is a workaround for references with failed resolution problem in gantt // those references return `hasValue() === false` even that they actually have value // (which is `null` and needed to be recalculated) if (requestedEntry.hasValue() || requestedEntry.value !== undefined) { const value = requestedEntry.getValue() if (value === TombStone) throwUnknownIdentifier(identifierRead) return activeEntry.continueCalculation(value) } else if (requestedEntry.isShadow()) { // shadow entry is shadowing a quark w/o value - it is still transitioning or lazy // in both cases start new calculation requestedEntry.startOrigin() requestedEntry.forceCalculation() stack.push(requestedEntry) return undefined } else { if (!requestedEntry.isCalculationStarted()) { stack.push(requestedEntry) if (!requestedEntry.previous || !requestedEntry.previous.hasValue()) requestedEntry.forceCalculation() return undefined } else { // cycle - the requested quark has started calculation (means it was encountered in the calculation loop before) // but the calculation did not complete yet (even that requested quark is calculated before the current) let cycle : ComputationCycle const walkContext = TransactionCycleDetectionWalkContext.new({ transaction : this, onCycle (node : Identifier, stack : WalkStep<Identifier>[]) : OnCycleAction { cycle = ComputationCycle.new({ cycle : cycleInfo(stack), requestedEntry, activeEntry, }) return OnCycleAction.Cancel } }) walkContext.startFrom([ requestedEntry.identifier ]) return cycle } } } * calculateTransitions (context : CalculationContext<any>) : Generator<any, void, unknown> { const queue = this.stackGen while (queue.length) { // TODO if stack calculation is interrupted with BreakCurrentStackExecution we might be loosing // some identifiers from the queue?? yield* this.calculateTransitionsStackGen(context, queue.takeLowestLevel()) } } calculateTransitionsSync (context : CalculationContext<any>) { const queue = this.stackGen while (queue.length) { this.calculateTransitionsStackSync(context, queue.takeLowestLevel()) } } // this method is not decomposed into smaller ones intentionally, as that makes benchmarks worse // it seems that overhead of calling few more functions in such tight loop as this outweighs the optimization * calculateTransitionsStackGen (context : CalculationContext<any>, stack : Quark[]) : Generator<any, void, unknown> { if (this.rejectedWith) return this.walkContext.startNewEpoch() const entries = this.entries const propagationStartDate = this.propagationStartDate const enableProgressNotifications = this.graph ? this.graph.enableProgressNotifications : false let counter : number = 0 const prevActiveStack = this.activeStack this.activeStack = stack while (stack.length && !this.rejectedWith) { if (enableProgressNotifications && !(counter++ % this.emitProgressNotificationsEveryCalculations)) { const now = Date.now() const elapsed = now - propagationStartDate if (elapsed > this.startProgressNotificationsAfterMs) { const lastProgressNotificationDate = this.lastProgressNotificationDate if (!lastProgressNotificationDate || (now - lastProgressNotificationDate) > this.emitProgressNotificationsEveryMs) { this.lastProgressNotificationDate = now this.graph.onPropagationProgressNotification({ total : this.plannedTotalIdentifiersToCalculate, remaining : stack.length, phase : 'propagating' }) yield delay(0) } } } const entry = stack[ stack.length - 1 ] const identifier = entry.identifier // TODO can avoid `.get()` call by comparing some another "epoch" counter on the entry const ownEntry = entries.get(identifier) if (ownEntry !== entry) { entry.cleanup() stack.pop() continue } if (entry.edgesFlow == 0) { // even if we delete the entry there might be other copies in stack, so reduce the `edgesFlow` to -1 // to indicate that those are already processed entry.edgesFlow-- const previousEntry = entry.previous previousEntry && previousEntry.outgoingInTheFutureAndPastTransactionCb(this, outgoing => { const outgoingEntry = entries.get(outgoing.identifier) if (outgoingEntry) outgoingEntry.edgesFlow-- }) } // the "edgesFlow < 0" indicates that none of the incoming deps of this quark has changed // thus we don't need to calculate it, moreover, we can remove the quark from the `entries` // to expose the value from the previous revision // however, we only do it, when there is a quark from previous revision and it has "origin" (some value) if (entry.edgesFlow < 0 && entry.previous && entry.previous.origin) { // even if the entry will be deleted from the transaction, we set the correct origin for it // this is because there might be other references to this entry in the stack // and also the entry may be referenced as dependency of some other quark // in such case the correct `originId` will preserve dependency during revisions compactification entry.setOrigin(entry.previous.origin) // if there's no outgoing edges we remove the quark if (entry.size === 0) { entries.delete(identifier) } // reduce garbage collection workload entry.cleanup() stack.pop() continue } if (/*entry.isShadow() ||*/ entry.hasValue() || entry.proposedValue === TombStone) { entry.cleanup() stack.pop() continue } const startedAtEpoch = entry.visitEpoch let iterationResult : IteratorResult<any> = entry.isCalculationStarted() ? entry.iterationResult : entry.startCalculation(this.onEffectSync) while (iterationResult) { const value = iterationResult.value === undefined ? null : iterationResult.value if (entry.isCalculationCompleted()) { if (entry.visitEpoch == startedAtEpoch) { this.onQuarkCalculationCompleted(entry, value) } stack.pop() break } else if (value instanceof Identifier) { const onReadIdentifierResult = this.onReadIdentifier(value, entry, stack) // handle the cycle if (onReadIdentifierResult instanceof ComputationCycle) { this.walkContext.startNewEpoch() yield* this.graph.onComputationCycleHandler(onReadIdentifierResult) entry.cleanupCalculation() iterationResult = undefined } else { iterationResult = onReadIdentifierResult } } else if (value === SynchronousCalculationStarted) { // the fact, that we've encountered `SynchronousCalculationStarted` constant can mean 2 things: // 1) there's a cycle during synchronous computation (we throw exception in `read` method) // 2) some other computation is reading synchronous computation, that has already started // in such case its safe to just unwind the stack stack.pop() break } else { // bypass the unrecognized effect to the outer context const effectResult = yield value // the calculation can be interrupted (`cleanupCalculation`) as a result of the effect (WriteEffect) // in such case we can not continue calculation and jare ust exit the inner loop if (effectResult === BreakCurrentStackExecution) break // // the calculation can be interrupted (`cleanupCalculation`) as a result of the effect (WriteEffect) // // in such case we can not continue calculation and just exit the inner loop // if (entry.iterationResult) if (entry.visitEpoch === startedAtEpoch) { iterationResult = entry.continueCalculation(effectResult) } else { stack.pop() break } // else // iterationResult = null } } } this.activeStack = prevActiveStack } // THIS METHOD HAS TO BE KEPT SYNCED WITH THE `calculateTransitionsStackGen` !!! calculateTransitionsStackSync (context : CalculationContext<any>, stack : Quark[]) { if (this.rejectedWith) return this.walkContext.startNewEpoch() const entries = this.entries const prevActiveStack = this.activeStack this.activeStack = stack while (stack.length && !this.rejectedWith) { const entry = stack[ stack.length - 1 ] const identifier = entry.identifier // TODO can avoid `.get()` call by comparing some another "epoch" counter on the entry const ownEntry = entries.get(identifier) if (ownEntry !== entry) { entry.cleanup() stack.pop() continue } if (entry.edgesFlow == 0) { // even if we delete the entry there might be other copies in stack, so reduce the `edgesFlow` to -1 // to indicate that those are already processed entry.edgesFlow-- const previousEntry = entry.previous previousEntry && previousEntry.outgoingInTheFutureAndPastTransactionCb(this, outgoing => { const outgoingEntry = entries.get(outgoing.identifier) if (outgoingEntry) outgoingEntry.edgesFlow-- }) } // the "edgesFlow < 0" indicates that none of the incoming deps of this quark has changed // thus we don't need to calculate it, moreover, we can remove the quark from the `entries` // to expose the value from the previous revision // however, we only do it, when there is a quark from previous revision and it has "origin" (some value) if (entry.edgesFlow < 0 && entry.previous && entry.previous.origin) { // even if the entry will be deleted from the transaction, we set the correct origin for it // this is because there might be other references to this entry in the stack // and also the entry may be referenced as dependency of some other quark // in such case the correct `originId` will preserve dependency during revisions compactification entry.setOrigin(entry.previous.origin) // if there's no outgoing edges we remove the quark if (entry.size === 0) { entries.delete(identifier) } // reduce garbage collection workload entry.cleanup() stack.pop() continue } if (/*entry.isShadow() ||*/ entry.hasValue() || entry.proposedValue === TombStone) { entry.cleanup() stack.pop() continue } const startedAtEpoch = entry.visitEpoch let iterationResult : IteratorResult<any> = entry.isCalculationStarted() ? entry.iterationResult : entry.startCalculation(this.onEffectSync) while (iterationResult) { const value = iterationResult.value === undefined ? null : iterationResult.value if (entry.isCalculationCompleted()) { if (entry.visitEpoch == startedAtEpoch) { this.onQuarkCalculationCompleted(entry, value) } stack.pop() break } else if (value instanceof Identifier) { const onReadIdentifierResult = this.onReadIdentifier(value, entry, stack) // handle the cycle if (onReadIdentifierResult instanceof ComputationCycle) { this.walkContext.startNewEpoch() this.graph.onComputationCycleHandlerSync(onReadIdentifierResult) entry.cleanupCalculation() iterationResult = undefined } else { iterationResult = onReadIdentifierResult } } else if (value === SynchronousCalculationStarted) { // the fact, that we've encountered `SynchronousCalculationStarted` constant can mean 2 things: // 1) there's a cycle during synchronous computation (we throw exception in `read` method) // 2) some other computation is reading synchronous computation, that has already started // in such case its safe to just unwind the stack stack.pop() break } else { // bypass the unrecognized effect to the outer context const effectResult = context(value) if (effectResult instanceof Promise) throw new Error("Effect resolved to promise in the synchronous context, check that you marked the asynchronous calculations accordingly") // the calculation can be interrupted (`cleanupCalculation`) as a result of the effect (WriteEffect) // in such case we can not continue calculation and just exit the inner loop if (effectResult === BreakCurrentStackExecution) break // // the calculation can be interrupted (`cleanupCalculation`) as a result of the effect (WriteEffect) // // in such case we can not continue calculation and just exit the inner loop // if (entry.iterationResult) if (entry.visitEpoch === startedAtEpoch) { iterationResult = entry.continueCalculation(effectResult) } else { stack.pop() break } // else // iterationResult = null } } } this.activeStack = prevActiveStack } }
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs, enums } from "../types"; import * as utilities from "../utilities"; /** * Manages an AWS Storage Gateway file, tape, or volume gateway in the provider region. * * > **NOTE:** The Storage Gateway API requires the gateway to be connected to properly return information after activation. If you are receiving `The specified gateway is not connected` errors during resource creation (gateway activation), ensure your gateway instance meets the [Storage Gateway requirements](https://docs.aws.amazon.com/storagegateway/latest/userguide/Requirements.html). * * ## Example Usage * ### Local Cache * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const testVolumeAttachment = new aws.ec2.VolumeAttachment("testVolumeAttachment", { * deviceName: "/dev/xvdb", * volumeId: aws_ebs_volume.test.id, * instanceId: aws_instance.test.id, * }); * const testLocalDisk = testVolumeAttachment.deviceName.apply(deviceName => aws.storagegateway.getLocalDisk({ * diskNode: deviceName, * gatewayArn: aws_storagegateway_gateway.test.arn, * })); * const testCache = new aws.storagegateway.Cache("testCache", { * diskId: testLocalDisk.apply(testLocalDisk => testLocalDisk.diskId), * gatewayArn: aws_storagegateway_gateway.test.arn, * }); * ``` * ### FSx File Gateway * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const example = new aws.storagegateway.Gateway("example", { * gatewayIpAddress: "1.2.3.4", * gatewayName: "example", * gatewayTimezone: "GMT", * gatewayType: "FILE_FSX_SMB", * smbActiveDirectorySettings: { * domainName: "corp.example.com", * password: "avoid-plaintext-passwords", * username: "Admin", * }, * }); * ``` * ### S3 File Gateway * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const example = new aws.storagegateway.Gateway("example", { * gatewayIpAddress: "1.2.3.4", * gatewayName: "example", * gatewayTimezone: "GMT", * gatewayType: "FILE_S3", * }); * ``` * ### Tape Gateway * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const example = new aws.storagegateway.Gateway("example", { * gatewayIpAddress: "1.2.3.4", * gatewayName: "example", * gatewayTimezone: "GMT", * gatewayType: "VTL", * mediumChangerType: "AWS-Gateway-VTL", * tapeDriveType: "IBM-ULT3580-TD5", * }); * ``` * ### Volume Gateway (Cached) * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const example = new aws.storagegateway.Gateway("example", { * gatewayIpAddress: "1.2.3.4", * gatewayName: "example", * gatewayTimezone: "GMT", * gatewayType: "CACHED", * }); * ``` * ### Volume Gateway (Stored) * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const example = new aws.storagegateway.Gateway("example", { * gatewayIpAddress: "1.2.3.4", * gatewayName: "example", * gatewayTimezone: "GMT", * gatewayType: "STORED", * }); * ``` * * ## Import * * `aws_storagegateway_gateway` can be imported by using the gateway Amazon Resource Name (ARN), e.g. * * ```sh * $ pulumi import aws:storagegateway/gateway:Gateway example arn:aws:storagegateway:us-east-1:123456789012:gateway/sgw-12345678 * ``` * * Certain resource arguments, like `gateway_ip_address` do not have a Storage Gateway API method for reading the information after creation, either omit the argument from the provider configuration or use `ignoreChanges` to hide the difference. */ export class Gateway extends pulumi.CustomResource { /** * Get an existing Gateway resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: GatewayState, opts?: pulumi.CustomResourceOptions): Gateway { return new Gateway(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'aws:storagegateway/gateway:Gateway'; /** * Returns true if the given object is an instance of Gateway. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is Gateway { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === Gateway.__pulumiType; } /** * Gateway activation key during resource creation. Conflicts with `gatewayIpAddress`. Additional information is available in the [Storage Gateway User Guide](https://docs.aws.amazon.com/storagegateway/latest/userguide/get-activation-key.html). */ public readonly activationKey!: pulumi.Output<string>; /** * Amazon Resource Name (ARN) of the gateway. */ public /*out*/ readonly arn!: pulumi.Output<string>; /** * The average download bandwidth rate limit in bits per second. This is supported for the `CACHED`, `STORED`, and `VTL` gateway types. */ public readonly averageDownloadRateLimitInBitsPerSec!: pulumi.Output<number | undefined>; /** * The average upload bandwidth rate limit in bits per second. This is supported for the `CACHED`, `STORED`, and `VTL` gateway types. */ public readonly averageUploadRateLimitInBitsPerSec!: pulumi.Output<number | undefined>; /** * The Amazon Resource Name (ARN) of the Amazon CloudWatch log group to use to monitor and log events in the gateway. */ public readonly cloudwatchLogGroupArn!: pulumi.Output<string | undefined>; /** * The ID of the Amazon EC2 instance that was used to launch the gateway. */ public /*out*/ readonly ec2InstanceId!: pulumi.Output<string>; /** * The type of endpoint for your gateway. */ public /*out*/ readonly endpointType!: pulumi.Output<string>; /** * Identifier of the gateway. */ public /*out*/ readonly gatewayId!: pulumi.Output<string>; /** * Gateway IP address to retrieve activation key during resource creation. Conflicts with `activationKey`. Gateway must be accessible on port 80 from where this provider is running. Additional information is available in the [Storage Gateway User Guide](https://docs.aws.amazon.com/storagegateway/latest/userguide/get-activation-key.html). */ public readonly gatewayIpAddress!: pulumi.Output<string>; /** * Name of the gateway. */ public readonly gatewayName!: pulumi.Output<string>; /** * An array that contains descriptions of the gateway network interfaces. See Gateway Network Interface. */ public /*out*/ readonly gatewayNetworkInterfaces!: pulumi.Output<outputs.storagegateway.GatewayGatewayNetworkInterface[]>; /** * Time zone for the gateway. The time zone is of the format "GMT", "GMT-hr:mm", or "GMT+hr:mm". For example, `GMT-4:00` indicates the time is 4 hours behind GMT. The time zone is used, for example, for scheduling snapshots and your gateway's maintenance schedule. */ public readonly gatewayTimezone!: pulumi.Output<string>; /** * Type of the gateway. The default value is `STORED`. Valid values: `CACHED`, `FILE_FSX_SMB`, `FILE_S3`, `STORED`, `VTL`. */ public readonly gatewayType!: pulumi.Output<string | undefined>; /** * VPC endpoint address to be used when activating your gateway. This should be used when your instance is in a private subnet. Requires HTTP access from client computer running this provider. More info on what ports are required by your VPC Endpoint Security group in [Activating a Gateway in a Virtual Private Cloud](https://docs.aws.amazon.com/storagegateway/latest/userguide/gateway-private-link.html). */ public readonly gatewayVpcEndpoint!: pulumi.Output<string | undefined>; /** * The type of hypervisor environment used by the host. */ public /*out*/ readonly hostEnvironment!: pulumi.Output<string>; /** * Type of medium changer to use for tape gateway. This provider cannot detect drift of this argument. Valid values: `STK-L700`, `AWS-Gateway-VTL`, `IBM-03584L32-0402`. */ public readonly mediumChangerType!: pulumi.Output<string | undefined>; /** * Nested argument with Active Directory domain join information for Server Message Block (SMB) file shares. Only valid for `FILE_S3` and `FILE_FSX_SMB` gateway types. Must be set before creating `ActiveDirectory` authentication SMB file shares. More details below. */ public readonly smbActiveDirectorySettings!: pulumi.Output<outputs.storagegateway.GatewaySmbActiveDirectorySettings | undefined>; /** * Specifies whether the shares on this gateway appear when listing shares. */ public readonly smbFileShareVisibility!: pulumi.Output<boolean | undefined>; /** * Guest password for Server Message Block (SMB) file shares. Only valid for `FILE_S3` and `FILE_FSX_SMB` gateway types. Must be set before creating `GuestAccess` authentication SMB file shares. This provider can only detect drift of the existence of a guest password, not its actual value from the gateway. This provider can however update the password with changing the argument. */ public readonly smbGuestPassword!: pulumi.Output<string | undefined>; /** * Specifies the type of security strategy. Valid values are: `ClientSpecified`, `MandatorySigning`, and `MandatoryEncryption`. See [Setting a Security Level for Your Gateway](https://docs.aws.amazon.com/storagegateway/latest/userguide/managing-gateway-file.html#security-strategy) for more information. */ public readonly smbSecurityStrategy!: pulumi.Output<string>; /** * Key-value map of resource tags */ public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>; /** * A map of tags assigned to the resource, including those inherited from the provider . */ public /*out*/ readonly tagsAll!: pulumi.Output<{[key: string]: string}>; /** * Type of tape drive to use for tape gateway. This provider cannot detect drift of this argument. Valid values: `IBM-ULT3580-TD5`. */ public readonly tapeDriveType!: pulumi.Output<string | undefined>; /** * Create a Gateway resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: GatewayArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: GatewayArgs | GatewayState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as GatewayState | undefined; inputs["activationKey"] = state ? state.activationKey : undefined; inputs["arn"] = state ? state.arn : undefined; inputs["averageDownloadRateLimitInBitsPerSec"] = state ? state.averageDownloadRateLimitInBitsPerSec : undefined; inputs["averageUploadRateLimitInBitsPerSec"] = state ? state.averageUploadRateLimitInBitsPerSec : undefined; inputs["cloudwatchLogGroupArn"] = state ? state.cloudwatchLogGroupArn : undefined; inputs["ec2InstanceId"] = state ? state.ec2InstanceId : undefined; inputs["endpointType"] = state ? state.endpointType : undefined; inputs["gatewayId"] = state ? state.gatewayId : undefined; inputs["gatewayIpAddress"] = state ? state.gatewayIpAddress : undefined; inputs["gatewayName"] = state ? state.gatewayName : undefined; inputs["gatewayNetworkInterfaces"] = state ? state.gatewayNetworkInterfaces : undefined; inputs["gatewayTimezone"] = state ? state.gatewayTimezone : undefined; inputs["gatewayType"] = state ? state.gatewayType : undefined; inputs["gatewayVpcEndpoint"] = state ? state.gatewayVpcEndpoint : undefined; inputs["hostEnvironment"] = state ? state.hostEnvironment : undefined; inputs["mediumChangerType"] = state ? state.mediumChangerType : undefined; inputs["smbActiveDirectorySettings"] = state ? state.smbActiveDirectorySettings : undefined; inputs["smbFileShareVisibility"] = state ? state.smbFileShareVisibility : undefined; inputs["smbGuestPassword"] = state ? state.smbGuestPassword : undefined; inputs["smbSecurityStrategy"] = state ? state.smbSecurityStrategy : undefined; inputs["tags"] = state ? state.tags : undefined; inputs["tagsAll"] = state ? state.tagsAll : undefined; inputs["tapeDriveType"] = state ? state.tapeDriveType : undefined; } else { const args = argsOrState as GatewayArgs | undefined; if ((!args || args.gatewayName === undefined) && !opts.urn) { throw new Error("Missing required property 'gatewayName'"); } if ((!args || args.gatewayTimezone === undefined) && !opts.urn) { throw new Error("Missing required property 'gatewayTimezone'"); } inputs["activationKey"] = args ? args.activationKey : undefined; inputs["averageDownloadRateLimitInBitsPerSec"] = args ? args.averageDownloadRateLimitInBitsPerSec : undefined; inputs["averageUploadRateLimitInBitsPerSec"] = args ? args.averageUploadRateLimitInBitsPerSec : undefined; inputs["cloudwatchLogGroupArn"] = args ? args.cloudwatchLogGroupArn : undefined; inputs["gatewayIpAddress"] = args ? args.gatewayIpAddress : undefined; inputs["gatewayName"] = args ? args.gatewayName : undefined; inputs["gatewayTimezone"] = args ? args.gatewayTimezone : undefined; inputs["gatewayType"] = args ? args.gatewayType : undefined; inputs["gatewayVpcEndpoint"] = args ? args.gatewayVpcEndpoint : undefined; inputs["mediumChangerType"] = args ? args.mediumChangerType : undefined; inputs["smbActiveDirectorySettings"] = args ? args.smbActiveDirectorySettings : undefined; inputs["smbFileShareVisibility"] = args ? args.smbFileShareVisibility : undefined; inputs["smbGuestPassword"] = args ? args.smbGuestPassword : undefined; inputs["smbSecurityStrategy"] = args ? args.smbSecurityStrategy : undefined; inputs["tags"] = args ? args.tags : undefined; inputs["tapeDriveType"] = args ? args.tapeDriveType : undefined; inputs["arn"] = undefined /*out*/; inputs["ec2InstanceId"] = undefined /*out*/; inputs["endpointType"] = undefined /*out*/; inputs["gatewayId"] = undefined /*out*/; inputs["gatewayNetworkInterfaces"] = undefined /*out*/; inputs["hostEnvironment"] = undefined /*out*/; inputs["tagsAll"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(Gateway.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering Gateway resources. */ export interface GatewayState { /** * Gateway activation key during resource creation. Conflicts with `gatewayIpAddress`. Additional information is available in the [Storage Gateway User Guide](https://docs.aws.amazon.com/storagegateway/latest/userguide/get-activation-key.html). */ activationKey?: pulumi.Input<string>; /** * Amazon Resource Name (ARN) of the gateway. */ arn?: pulumi.Input<string>; /** * The average download bandwidth rate limit in bits per second. This is supported for the `CACHED`, `STORED`, and `VTL` gateway types. */ averageDownloadRateLimitInBitsPerSec?: pulumi.Input<number>; /** * The average upload bandwidth rate limit in bits per second. This is supported for the `CACHED`, `STORED`, and `VTL` gateway types. */ averageUploadRateLimitInBitsPerSec?: pulumi.Input<number>; /** * The Amazon Resource Name (ARN) of the Amazon CloudWatch log group to use to monitor and log events in the gateway. */ cloudwatchLogGroupArn?: pulumi.Input<string>; /** * The ID of the Amazon EC2 instance that was used to launch the gateway. */ ec2InstanceId?: pulumi.Input<string>; /** * The type of endpoint for your gateway. */ endpointType?: pulumi.Input<string>; /** * Identifier of the gateway. */ gatewayId?: pulumi.Input<string>; /** * Gateway IP address to retrieve activation key during resource creation. Conflicts with `activationKey`. Gateway must be accessible on port 80 from where this provider is running. Additional information is available in the [Storage Gateway User Guide](https://docs.aws.amazon.com/storagegateway/latest/userguide/get-activation-key.html). */ gatewayIpAddress?: pulumi.Input<string>; /** * Name of the gateway. */ gatewayName?: pulumi.Input<string>; /** * An array that contains descriptions of the gateway network interfaces. See Gateway Network Interface. */ gatewayNetworkInterfaces?: pulumi.Input<pulumi.Input<inputs.storagegateway.GatewayGatewayNetworkInterface>[]>; /** * Time zone for the gateway. The time zone is of the format "GMT", "GMT-hr:mm", or "GMT+hr:mm". For example, `GMT-4:00` indicates the time is 4 hours behind GMT. The time zone is used, for example, for scheduling snapshots and your gateway's maintenance schedule. */ gatewayTimezone?: pulumi.Input<string>; /** * Type of the gateway. The default value is `STORED`. Valid values: `CACHED`, `FILE_FSX_SMB`, `FILE_S3`, `STORED`, `VTL`. */ gatewayType?: pulumi.Input<string>; /** * VPC endpoint address to be used when activating your gateway. This should be used when your instance is in a private subnet. Requires HTTP access from client computer running this provider. More info on what ports are required by your VPC Endpoint Security group in [Activating a Gateway in a Virtual Private Cloud](https://docs.aws.amazon.com/storagegateway/latest/userguide/gateway-private-link.html). */ gatewayVpcEndpoint?: pulumi.Input<string>; /** * The type of hypervisor environment used by the host. */ hostEnvironment?: pulumi.Input<string>; /** * Type of medium changer to use for tape gateway. This provider cannot detect drift of this argument. Valid values: `STK-L700`, `AWS-Gateway-VTL`, `IBM-03584L32-0402`. */ mediumChangerType?: pulumi.Input<string>; /** * Nested argument with Active Directory domain join information for Server Message Block (SMB) file shares. Only valid for `FILE_S3` and `FILE_FSX_SMB` gateway types. Must be set before creating `ActiveDirectory` authentication SMB file shares. More details below. */ smbActiveDirectorySettings?: pulumi.Input<inputs.storagegateway.GatewaySmbActiveDirectorySettings>; /** * Specifies whether the shares on this gateway appear when listing shares. */ smbFileShareVisibility?: pulumi.Input<boolean>; /** * Guest password for Server Message Block (SMB) file shares. Only valid for `FILE_S3` and `FILE_FSX_SMB` gateway types. Must be set before creating `GuestAccess` authentication SMB file shares. This provider can only detect drift of the existence of a guest password, not its actual value from the gateway. This provider can however update the password with changing the argument. */ smbGuestPassword?: pulumi.Input<string>; /** * Specifies the type of security strategy. Valid values are: `ClientSpecified`, `MandatorySigning`, and `MandatoryEncryption`. See [Setting a Security Level for Your Gateway](https://docs.aws.amazon.com/storagegateway/latest/userguide/managing-gateway-file.html#security-strategy) for more information. */ smbSecurityStrategy?: pulumi.Input<string>; /** * Key-value map of resource tags */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * A map of tags assigned to the resource, including those inherited from the provider . */ tagsAll?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * Type of tape drive to use for tape gateway. This provider cannot detect drift of this argument. Valid values: `IBM-ULT3580-TD5`. */ tapeDriveType?: pulumi.Input<string>; } /** * The set of arguments for constructing a Gateway resource. */ export interface GatewayArgs { /** * Gateway activation key during resource creation. Conflicts with `gatewayIpAddress`. Additional information is available in the [Storage Gateway User Guide](https://docs.aws.amazon.com/storagegateway/latest/userguide/get-activation-key.html). */ activationKey?: pulumi.Input<string>; /** * The average download bandwidth rate limit in bits per second. This is supported for the `CACHED`, `STORED`, and `VTL` gateway types. */ averageDownloadRateLimitInBitsPerSec?: pulumi.Input<number>; /** * The average upload bandwidth rate limit in bits per second. This is supported for the `CACHED`, `STORED`, and `VTL` gateway types. */ averageUploadRateLimitInBitsPerSec?: pulumi.Input<number>; /** * The Amazon Resource Name (ARN) of the Amazon CloudWatch log group to use to monitor and log events in the gateway. */ cloudwatchLogGroupArn?: pulumi.Input<string>; /** * Gateway IP address to retrieve activation key during resource creation. Conflicts with `activationKey`. Gateway must be accessible on port 80 from where this provider is running. Additional information is available in the [Storage Gateway User Guide](https://docs.aws.amazon.com/storagegateway/latest/userguide/get-activation-key.html). */ gatewayIpAddress?: pulumi.Input<string>; /** * Name of the gateway. */ gatewayName: pulumi.Input<string>; /** * Time zone for the gateway. The time zone is of the format "GMT", "GMT-hr:mm", or "GMT+hr:mm". For example, `GMT-4:00` indicates the time is 4 hours behind GMT. The time zone is used, for example, for scheduling snapshots and your gateway's maintenance schedule. */ gatewayTimezone: pulumi.Input<string>; /** * Type of the gateway. The default value is `STORED`. Valid values: `CACHED`, `FILE_FSX_SMB`, `FILE_S3`, `STORED`, `VTL`. */ gatewayType?: pulumi.Input<string>; /** * VPC endpoint address to be used when activating your gateway. This should be used when your instance is in a private subnet. Requires HTTP access from client computer running this provider. More info on what ports are required by your VPC Endpoint Security group in [Activating a Gateway in a Virtual Private Cloud](https://docs.aws.amazon.com/storagegateway/latest/userguide/gateway-private-link.html). */ gatewayVpcEndpoint?: pulumi.Input<string>; /** * Type of medium changer to use for tape gateway. This provider cannot detect drift of this argument. Valid values: `STK-L700`, `AWS-Gateway-VTL`, `IBM-03584L32-0402`. */ mediumChangerType?: pulumi.Input<string>; /** * Nested argument with Active Directory domain join information for Server Message Block (SMB) file shares. Only valid for `FILE_S3` and `FILE_FSX_SMB` gateway types. Must be set before creating `ActiveDirectory` authentication SMB file shares. More details below. */ smbActiveDirectorySettings?: pulumi.Input<inputs.storagegateway.GatewaySmbActiveDirectorySettings>; /** * Specifies whether the shares on this gateway appear when listing shares. */ smbFileShareVisibility?: pulumi.Input<boolean>; /** * Guest password for Server Message Block (SMB) file shares. Only valid for `FILE_S3` and `FILE_FSX_SMB` gateway types. Must be set before creating `GuestAccess` authentication SMB file shares. This provider can only detect drift of the existence of a guest password, not its actual value from the gateway. This provider can however update the password with changing the argument. */ smbGuestPassword?: pulumi.Input<string>; /** * Specifies the type of security strategy. Valid values are: `ClientSpecified`, `MandatorySigning`, and `MandatoryEncryption`. See [Setting a Security Level for Your Gateway](https://docs.aws.amazon.com/storagegateway/latest/userguide/managing-gateway-file.html#security-strategy) for more information. */ smbSecurityStrategy?: pulumi.Input<string>; /** * Key-value map of resource tags */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * Type of tape drive to use for tape gateway. This provider cannot detect drift of this argument. Valid values: `IBM-ULT3580-TD5`. */ tapeDriveType?: pulumi.Input<string>; }
the_stack
* @module Curve */ import { BSplineCurve3d, BSplineCurve3dBase } from "../bspline/BSplineCurve"; import { BSplineCurve3dH } from "../bspline/BSplineCurve3dH"; import { Geometry } from "../Geometry"; import { NullGeometryHandler } from "../geometry3d/GeometryHandler"; import { GrowableFloat64Array } from "../geometry3d/GrowableFloat64Array"; import { Point3d, Vector3d } from "../geometry3d/Point3dVector3d"; import { Range3d } from "../geometry3d/Range"; import { AnalyticRoots, SmallSystem } from "../numerics/Polynomials"; import { Arc3d } from "./Arc3d"; import { CurveIntervalRole, CurveLocationDetail, CurveLocationDetailPair } from "./CurveLocationDetail"; import { CurvePrimitive } from "./CurvePrimitive"; import { GeometryQuery } from "./GeometryQuery"; import { LineSegment3d } from "./LineSegment3d"; import { LineString3d } from "./LineString3d"; // cspell:word XYRR /** * Set bits for comparison to range xy * * bit 0x01 => x smaller than range.low.x * * bit 0x02 => x larger than range.high.x * * bit 0x04 => x smaller than range.low.y * * bit 0x08 => x larger than range.high.y * @param xy point to test * @param range range for comparison */ function classifyBitsPointRangeXY(x: number, y: number, range: Range3d): number { let result = 0; if (x < range.low.x) result = 0x01; else if (x > range.high.x) result = 0x02; if (y < range.low.y) result |= 0x04; else if (y > range.high.y) result |= 0x08; return result; } /** * * Instances are initialized and called from CurveCurve. * * Constructor is told two geometry items A and B * * geometryB is saved for later reference * * type-specific handler methods will "see" geometry A repeatedly. * * Hence geometryA is NOT saved by the constructor. * @internal */ export class CurveCurveCloseApproachXY extends NullGeometryHandler { // private geometryA: GeometryQuery; // nb never used -- passed through handlers. /* geometryA exists through the handler call. * geometryB is static through (possibly multiple) geometryA. * at geometryB setup time, a strongly typed version of geometryB may be saved. */ private _geometryB: GeometryQuery | undefined; private _circularArcB: Arc3d | undefined; private _circularRadiusB: number | undefined; private setGeometryB(geometryB: GeometryQuery | undefined) { this._geometryB = geometryB; this._circularArcB = undefined; this._circularRadiusB = undefined; if (geometryB instanceof Arc3d) { const r = geometryB.circularRadiusXY(); if (r !== undefined) { this._circularRadiusB = r; this._circularArcB = geometryB; } } } /** approach larger than this is not interesting. * This is caller defined and can be undefined. */ private _maxDistanceToAccept: number | undefined; /** Squared max distance. This is private, and is forced to at least small metric distance squared */ private _maxDistanceSquared: number; private _results!: CurveLocationDetailPair[]; // private _coincidentGeometryContext: CoincidentGeometryQuery; private reinitialize() { this._results = []; } /** * @param _geometryA first curve for intersection. This is NOT saved. * @param geometryB second curve for intersection. Saved for reference by specific handler methods. */ public constructor(_geometryA: GeometryQuery | undefined, geometryB: GeometryQuery | undefined) { super(); // this.geometryA = _geometryA; this.setGeometryB(geometryB); this._maxDistanceSquared = Geometry.smallMetricDistanceSquared; // this._coincidentGeometryContext = CoincidentGeometryQuery.create(); this.reinitialize(); } /** Access the (possibly undefined) max distance to accept. */ public set maxDistanceToAccept(value: number | undefined) { this._maxDistanceToAccept = value; if (this._maxDistanceToAccept !== undefined && this._maxDistanceToAccept > 0) this._maxDistanceSquared = this._maxDistanceToAccept * this._maxDistanceToAccept; } /** Set the (possibly undefined) max distance to accept. */ public get maxDistanceToAccept(): number | undefined { return this._maxDistanceToAccept; } /** Ask if the maxDistanceToAccept value is defined and positive */ public get isMaxDistanceSet(): boolean { return this._maxDistanceToAccept !== undefined && this._maxDistanceToAccept > 0; } /** Reset the geometry and flags, leaving all other parts unchanged (and preserving accumulated intersections) */ public resetGeometry(_geometryA: GeometryQuery, geometryB: GeometryQuery) { this.setGeometryB(geometryB); } private acceptFraction(fraction: number, fractionTol: number = 1.0e-12) { if (fraction < -fractionTol) return false; if (fraction > 1.0 + fractionTol) return false; return true; } /** * * Return the results structure for the intersection calculation, structured as an array of CurveLocationDetailPair * @param reinitialize if true, a new results structure is created for use by later calls. * */ public grabPairedResults(reinitialize: boolean = false): CurveLocationDetailPair[] { const result = this._results; if (reinitialize) this.reinitialize(); return result; } private sameCurveAndFraction(cp: CurvePrimitive, fraction: number, detail: CurveLocationDetail): boolean { return cp === detail.curve && Geometry.isAlmostEqualNumber(fraction, detail.fraction); } private testAndRecordPointPairApproach(cpA: CurvePrimitive, fA: number, pointA: Point3d, cpB: CurvePrimitive, fB: number, pointB: Point3d, reversed: boolean) { const d2 = pointA.distanceSquaredXY(pointB); if (d2 < this._maxDistanceSquared) { const detailA = CurveLocationDetail.createCurveFractionPoint(cpA, fA, pointA); const detailB = CurveLocationDetail.createCurveFractionPoint(cpB, fB, pointB); const pair = CurveLocationDetailPair.createCapture(detailA, detailB); if (reversed) pair.swapDetails(); this._results.push(pair); } } /** compute intersection of two line segments. * filter by extension rules. * record with fraction mapping. */ private recordPointWithLocalFractions( localFractionA: number, cpA: CurvePrimitive, fractionA0: number, fractionA1: number, localFractionB: number, // Computed intersection fraction cpB: CurvePrimitive, fractionB0: number, fractionB1: number, reversed: boolean, intervalDetails?: undefined | CurveLocationDetailPair) { let globalFractionA, globalFractionB; let globalFractionA1, globalFractionB1; const isInterval = intervalDetails !== undefined && intervalDetails.detailA.hasFraction1 && intervalDetails.detailB.hasFraction1; if (isInterval) { globalFractionA = Geometry.interpolate(fractionA0, intervalDetails.detailA.fraction, fractionA1); globalFractionB = Geometry.interpolate(fractionB0, intervalDetails.detailB.fraction, fractionB1); globalFractionA1 = Geometry.interpolate(fractionA0, intervalDetails.detailA.fraction1!, fractionA1); globalFractionB1 = Geometry.interpolate(fractionB0, intervalDetails.detailB.fraction1!, fractionB1); } else { globalFractionA = globalFractionA1 = Geometry.interpolate(fractionA0, localFractionA, fractionA1); globalFractionB = globalFractionB1 = Geometry.interpolate(fractionB0, localFractionB, fractionB1); } // ignore duplicate of most recent point . .. const numPrevious = this._results.length; if (numPrevious > 0 && !isInterval) { const oldDetailA = this._results[numPrevious - 1].detailA; const oldDetailB = this._results[numPrevious - 1].detailB; if (reversed) { if (this.sameCurveAndFraction(cpA, globalFractionA, oldDetailB) && this.sameCurveAndFraction(cpB, globalFractionB, oldDetailA)) return; } else { if (this.sameCurveAndFraction(cpA, globalFractionA, oldDetailA) && this.sameCurveAndFraction(cpB, globalFractionB, oldDetailB)) return; } } const detailA = CurveLocationDetail.createCurveFractionPoint(cpA, globalFractionA, cpA.fractionToPoint(globalFractionA)); const detailB = CurveLocationDetail.createCurveFractionPoint(cpB, globalFractionB, cpB.fractionToPoint(globalFractionB)); if (isInterval) { detailA.captureFraction1Point1(globalFractionA1, cpA.fractionToPoint(globalFractionA1)); detailB.captureFraction1Point1(globalFractionB1, cpB.fractionToPoint(globalFractionB1)); } else { detailA.setIntervalRole(CurveIntervalRole.isolated); detailB.setIntervalRole(CurveIntervalRole.isolated); } if (reversed) { this._results.push(new CurveLocationDetailPair(detailB, detailA)); } else { this._results.push(new CurveLocationDetailPair(detailA, detailB)); } } /** * capture a close approach pair that has point and local fraction but not curve. * record with fraction mapping. */ private capturePairWithLocalFractions( pair: CurveLocationDetailPair, cpA: CurvePrimitive, fractionA0: number, fractionA1: number, cpB: CurvePrimitive, fractionB0: number, fractionB1: number, reversed: boolean) { const globalFractionA = Geometry.interpolate(fractionA0, pair.detailA.fraction, fractionA1); const globalFractionB = Geometry.interpolate(fractionB0, pair.detailB.fraction, fractionB1); // ignore duplicate of most recent point . .. const numPrevious = this._results.length; if (numPrevious > 0) { const oldDetailA = this._results[numPrevious - 1].detailA; const oldDetailB = this._results[numPrevious - 1].detailB; if (reversed) { if (this.sameCurveAndFraction(cpA, globalFractionA, oldDetailB) && this.sameCurveAndFraction(cpB, globalFractionB, oldDetailA)) return; } else { if (this.sameCurveAndFraction(cpA, globalFractionA, oldDetailA) && this.sameCurveAndFraction(cpB, globalFractionB, oldDetailB)) return; } } pair.detailA.setIntervalRole(CurveIntervalRole.isolated); pair.detailB.setIntervalRole(CurveIntervalRole.isolated); if (reversed) { this._results.push(pair); } else { pair.swapDetails(); this._results.push(pair); } } /** * emit recordPoint for multiple pairs (on full curve!) * @param cpA first curve primitive. (possibly different from curve in detailA, but fraction compatible) * @param cpB second curve primitive. (possibly different from curve in detailA, but fraction compatible) * @param pairs array of pairs * @param reversed true to have order reversed in final structures. */ public recordPairs(cpA: CurvePrimitive, cpB: CurvePrimitive, pairs: CurveLocationDetailPair[] | undefined, reversed: boolean) { if (pairs !== undefined) { for (const p of pairs) { this.recordPointWithLocalFractions(p.detailA.fraction, cpA, 0, 1, p.detailB.fraction, cpB, 0, 1, reversed, p); } } } /** * record fully assembled (but possibly reversed) detail pair. * @param detailA first detail * @param detailB second detail * @param reversed true to have order reversed in final structures. */ public captureDetailPair(detailA: CurveLocationDetail | undefined, detailB: CurveLocationDetail | undefined, reversed: boolean) { if (detailA && detailB) { if (reversed) { this._results.push(CurveLocationDetailPair.createCapture(detailA, detailB)); } else { this._results.push(CurveLocationDetailPair.createCapture(detailB, detailA)); } } } /** * * @param fractionA * @param pointA * @param pointB0 * @param pointB1 * @param fractionB * @param minDistanceSquared * @param closestApproach */ private static updatePointToSegmentDistance(fractionA: number, pointA: Point3d, pointB0: Point3d, pointB1: Point3d, fractionB: number, minDistanceSquared: number, closestApproach?: CurveLocationDetailPair): CurveLocationDetailPair | undefined { if (fractionB < 0) fractionB = 0; else if (fractionB > 1) fractionB = 1; this._workPointB0 = pointB0.interpolate(fractionB, pointB1, this._workPointB0); const distanceSquared = this._workPointB0.distanceSquaredXY(pointA); if (distanceSquared < minDistanceSquared) { if (closestApproach === undefined || distanceSquared < closestApproach.detailA.a) { if (closestApproach === undefined) closestApproach = CurveLocationDetailPair.createCapture(CurveLocationDetail.create(), CurveLocationDetail.create()); closestApproach.detailA.setFP(fractionA, pointA); closestApproach.detailA.a = distanceSquared; closestApproach.detailB.setFP(fractionB, this._workPointB0); closestApproach.detailA.a = distanceSquared; } } return closestApproach; } /** * Return fractions of close approach within minDistance between two line segments( a0,a1) and (b0, b1) * * minDistance is assumed positive * Return the fractional (not xy) coordinates in result.x, result.y * @param a0 start point of line a * @param a1 end point of line a * @param b0 start point of line b * @param b1 end point of line b * @param result point to receive fractional coordinates of intersection. result.x is fraction on line a. result.y is fraction on line b. */ private static segmentSegmentBoundedApproach(a0: Point3d, a1: Point3d, b0: Point3d, b1: Point3d, minDistanceSquared: number): CurveLocationDetailPair | undefined { const ux = a1.x - a0.x; const uy = a1.y - a0.y; const vx = b1.x - b0.x; const vy = b1.y - b0.y; const e00x = b0.x - a0.x; const e00y = b0.y - a0.y; const e01x = b1.x - a0.x; const e01y = b1.y - a0.y; const e10x = b0.x - a1.x; const e10y = b0.y - a1.y; const e11x = b1.x - a1.x; const e11y = b1.y - a1.y; const hab0 = Geometry.crossProductXYXY(ux, uy, e00x, e00y); const hab1 = Geometry.crossProductXYXY(ux, uy, e01x, e01y); const hba0 = -Geometry.crossProductXYXY(vx, vy, e00x, e00y); const hba1 = -Geometry.crossProductXYXY(vx, vy, e11x, e11y); if (hab0 * hab1 < 0.0 && hba0 * hba1 < 0.0) { // true intersection, strictly within both segments !!! const fractionA = -hba0 / (hba1 - hba0); const fractionB = -hab0 / (hab1 - hab0); return CurveLocationDetailPair.createCapture(CurveLocationDetail.createCurveFractionPoint(undefined, fractionA, a0.interpolate(fractionA, a1)), CurveLocationDetail.createCurveFractionPoint(undefined, fractionB, b0.interpolate(fractionB, b1))); } let closestApproach: CurveLocationDetailPair | undefined; const uu = Geometry.hypotenuseSquaredXY(ux, uy); if (hab0 * hab0 < minDistanceSquared * uu) closestApproach = this.updatePointToSegmentDistance(0, b0, a0, a1, Geometry.dotProductXYXY(ux, uy, e00x, e00y) / uu, minDistanceSquared, closestApproach); if (hab1 * hab1 < minDistanceSquared * uu) closestApproach = this.updatePointToSegmentDistance(1, b1, a0, a1, Geometry.dotProductXYXY(ux, uy, e01x, e01y) / uu, minDistanceSquared, closestApproach); const vv = Geometry.hypotenuseSquaredXY(vx, vy); if (hba0 * hba0 < minDistanceSquared * vv) closestApproach = this.updatePointToSegmentDistance(0, a0, b0, b1, -Geometry.dotProductXYXY(vx, vy, e00x, e00y) / vv, minDistanceSquared, closestApproach); if (hba1 * hba1 < minDistanceSquared * vv) closestApproach = this.updatePointToSegmentDistance(1, a1, b0, b1, -Geometry.dotProductXYXY(vx, vy, e10x, e10y) / vv, minDistanceSquared, closestApproach); return closestApproach; } /** * Return fractions of close approach within minDistance between two line segments( a0,a1) and (b0, b1) * * minDistance is assumed positive * Return the fractional (not xy) coordinates in result.x, result.y * @param a0 start point of line a * @param a1 end point of line a * @param b0 start point of line b * @param b1 end point of line b * @param result point to receive fractional coordinates of intersection. result.x is fraction on line a. result.y is fraction on line b. */ private testAndRecordFractionalPairApproach(cpA: CurvePrimitive, fA0: number, fA1: number, testProjectionOnA: boolean, cpB: CurvePrimitive, fB0: number, fB1: number, testProjectionOnB: boolean, reversed: boolean) { const pointA0 = cpA.fractionToPoint(fA0); const pointA1 = cpA.fractionToPoint(fA1); const pointB0 = cpB.fractionToPoint(fB0); const pointB1 = cpB.fractionToPoint(fB1); this.testAndRecordPointPairApproach(cpA, fA0, pointA0, cpB, fB0, pointB0, reversed); this.testAndRecordPointPairApproach(cpA, fA1, pointA1, cpB, fB0, pointB0, reversed); this.testAndRecordPointPairApproach(cpA, fA0, pointA0, cpB, fB1, pointB1, reversed); this.testAndRecordPointPairApproach(cpA, fA1, pointA1, cpB, fB1, pointB1, reversed); if (testProjectionOnB) { this.testAndRecordProjection(cpA, fA0, pointA0, cpB, fB0, fB1, reversed); this.testAndRecordProjection(cpA, fA1, pointA1, cpB, fB0, fB1, reversed); } if (testProjectionOnA) { this.testAndRecordProjection(cpB, fB0, pointB0, cpA, fA0, fA1, !reversed); this.testAndRecordProjection(cpB, fB1, pointB1, cpA, fA0, fA1, !reversed); } } private testAndRecordProjection(cpA: CurvePrimitive, fA: number, pointA: Point3d, cpB: CurvePrimitive, fB0: number, fB1: number, reversed: boolean) { // NO NO NO -- this is 3D closest point --- need 2d !! const detail = cpB.closestPoint(pointA, false); if (detail) { const fB = Geometry.restrictToInterval(detail.fraction, fB0, fB1); if (fB === detail.fraction) { this.testAndRecordPointPairApproach(cpA, fA, pointA, cpB, detail.fraction, detail.point, reversed); } } } /** compute intersection of two line segments. * filter by extension rules. * record with fraction mapping. * * The fraction mappings allow portions of a linestring to be passed here. */ private computeSegmentSegment3D( cpA: CurvePrimitive, pointA0: Point3d, fractionA0: number, pointA1: Point3d, fractionA1: number, cpB: CurvePrimitive, pointB0: Point3d, fractionB0: number, pointB1: Point3d, fractionB1: number, reversed: boolean, ) { const approach = CurveCurveCloseApproachXY.segmentSegmentBoundedApproach(pointA0, pointA1, pointB0, pointB1, this._maxDistanceSquared); if (approach) this.capturePairWithLocalFractions(approach, cpA, fractionA0, fractionA1, cpB, fractionB0, fractionB1, reversed); } // Caller accesses data from a line segment and passes to here. // (The line segment in question might be (a) a full line segment or (b) a fragment within a linestring. The fraction and extend parameters // allow all combinations to be passed in) // This method applies transform. private dispatchSegmentSegment( cpA: CurvePrimitive, pointA0: Point3d, fractionA0: number, pointA1: Point3d, fractionA1: number, cpB: CurvePrimitive, pointB0: Point3d, fractionB0: number, pointB1: Point3d, fractionB1: number, reversed: boolean, ) { this.computeSegmentSegment3D( cpA, pointA0, fractionA0, pointA1, fractionA1, cpB, pointB0, fractionB0, pointB1, fractionB1, reversed); } // Caller accesses data from a linestring or segment and passes it here. // (The line segment in question might be (a) a full line segment or (b) a fragment within a linestring. The fraction and extend parameters // allow all combinations to be passed in) private dispatchSegmentArc( cpA: CurvePrimitive, pointA0: Point3d, fractionA0: number, pointA1: Point3d, fractionA1: number, arc: Arc3d, reversed: boolean, ) { // To consider: // 1) endpoint to endpoint or projection // 2) true intersection // 3) line parallel to arc tangent. this.testAndRecordFractionalPairApproach(cpA, 0, 1, true, arc, 0, 1, false, reversed); // Arc: X = C + cU + sV // Line: contains points A0,A1 // Arc point colinear with line if det (A0, A1, X) = 0 // with homogeneous xyw points and vectors. // With equational X: det (A0, A1, C) + c det (A0, A1,U) + s det (A0, A1, V) = 0. // solve for theta. // evaluate points. // project back to line. const data = arc.toTransformedVectors(); const pointA0Local = pointA0; const pointA1Local = pointA1; const alpha = Geometry.tripleProductXYW(pointA0Local, 1, pointA1Local, 1, data.center, 1); const beta = Geometry.tripleProductXYW(pointA0Local, 1, pointA1Local, 1, data.vector0, 0); const gamma = Geometry.tripleProductXYW(pointA0Local, 1, pointA1Local, 1, data.vector90, 0); const cosines = new GrowableFloat64Array(2); const sines = new GrowableFloat64Array(2); const radians = new GrowableFloat64Array(2); const numRoots = AnalyticRoots.appendImplicitLineUnitCircleIntersections(alpha, beta, gamma, cosines, sines, radians); for (let i = 0; i < numRoots; i++) { const arcPoint = data.center.plus2Scaled(data.vector0, cosines.atUncheckedIndex(i), data.vector90, sines.atUncheckedIndex(i)); const arcFraction = data.sweep.radiansToSignedPeriodicFraction(radians.atUncheckedIndex(i)); const lineFraction = SmallSystem.lineSegment3dXYClosestPointUnbounded(pointA0Local, pointA1Local, arcPoint); if (lineFraction !== undefined && this.acceptFraction(lineFraction) && this.acceptFraction(arcFraction)) { this.recordPointWithLocalFractions(lineFraction, cpA, fractionA0, fractionA1, arcFraction, arc, 0, 1, reversed); } } // line parallel to arc tangent. const dotUT = data.vector0.crossProductStartEndXY(pointA0, pointA1); const dotVT = data.vector90.crossProductStartEndXY(pointA0, pointA1); const parallelRadians = Math.atan2(dotVT, dotUT); for (const radians1 of [parallelRadians, parallelRadians + Math.PI]) { const arcPoint = data.center.plus2Scaled(data.vector0, Math.cos(radians1), data.vector90, Math.sin(radians1)); const arcFraction = data.sweep.radiansToSignedPeriodicFraction(radians1); const lineFraction = SmallSystem.lineSegment3dXYClosestPointUnbounded(pointA0Local, pointA1Local, arcPoint); if (lineFraction !== undefined && this.acceptFraction(lineFraction) && this.acceptFraction(arcFraction)) { this.recordPointWithLocalFractions(lineFraction, cpA, fractionA0, fractionA1, arcFraction, arc, 0, 1, reversed); } } } // Caller accesses data from two arcs, ensures circular, and orders with radiusA >= radiusB private dispatchCircularCircularOrdered( cpA: Arc3d, radiusA: number, cpB: Arc3d, radiusB: number, reversed: boolean, ) { const c = cpA.center.distance(cpB.center); const e = this._maxDistanceToAccept !== undefined ? this._maxDistanceToAccept : Geometry.smallMetricDistance; if (c > radiusA + radiusB + e) // widely separated !! return; // To consider: // 1) endpoint to endpoint or projection // 2) true intersection // 3) line parallel to arc tangent. this.testAndRecordFractionalPairApproach(cpA, 0, 1, false, cpB, 0, 1, false, reversed); if (Geometry.isSmallMetricDistance(c)) { } else { // ?? endpoint hits are recorded. Maybe also need overlap? const vectorAB = Vector3d.createStartEnd(cpA.center, cpB.center); vectorAB.scaleInPlace(1.0 / c); if (c - radiusA - radiusB > e) { // no approaches possible } else { for (const rA of [-radiusA, radiusA]) { for (const rB of [-radiusB, radiusB]) { const tangentDistance = c - rA + rB; if (tangentDistance < e) { const detailA = this.resolveDirectionToArcXYFraction(cpA, vectorAB, rA); if (detailA) { const detailB = this.resolveDirectionToArcXYFraction(cpB, vectorAB, rB); if (detailB) { this.captureDetailPair(detailA, detailB, reversed); } } } } } } } } /** Find the fractional point (if any) on an arc, known to be circular and displayed from the center in the direction of a scaled vector. * */ private resolveDirectionToArcXYFraction(arc: Arc3d, radialVector: Vector3d, scale: number): CurveLocationDetail | undefined { // The scale ultimately only affects the direction --- easiest way to use it is two multiplies const c = scale * arc.matrixRef.columnDotXYZ(0, radialVector.x, radialVector.y, 0); const s = scale * arc.matrixRef.columnDotXYZ(1, radialVector.x, radialVector.y, 0); const radians = Math.atan2(s, c); const fraction = arc.sweep.radiansToPositivePeriodicFraction(radians, 0); if (fraction < 1.0) return CurveLocationDetail.createCurveEvaluatedFraction(arc, fraction); return undefined; } // Caller accesses data from two arcs. // Selects the best conditioned arc (in xy parts) as "circle after inversion" // Solves the arc-arc equations private dispatchArcArc( cpA: Arc3d, cpB: Arc3d, reversed: boolean, ) { if (this._circularArcB) { const radiusB = this._circularRadiusB!; const radiusA = cpA.circularRadiusXY(); if (radiusA !== undefined) { if (radiusA >= radiusB) this.dispatchCircularCircularOrdered(cpA, radiusA, cpB, radiusB, reversed); else this.dispatchCircularCircularOrdered(cpB, radiusB, cpA, radiusA, !reversed); return; } } // Fall through for } // Caller accesses data from two arcs. // Selects the best conditioned arc (in xy parts) as "circle after inversion" // Solves the arc-arc equations private dispatchArcBsplineCurve3d( cpA: Arc3d, cpB: BSplineCurve3d, reversed: boolean) { const ls = LineString3d.create(); cpB.emitStrokes(ls); this.computeArcLineString(cpA, ls, reversed); } // Caller accesses data from two arcs. // Selects the best conditioned arc (in xy parts) as "circle after inversion" // Solves the arc-arc equations private dispatchBSplineCurve3dBSplineCurve3d( bcurveA: BSplineCurve3dBase, bcurveB: BSplineCurve3dBase, reversed: boolean) { const lsA = LineString3d.create(); bcurveA.emitStrokes(lsA); const lsB = LineString3d.create(); bcurveB.emitStrokes(lsB); this.computeLineStringLineString(lsA, lsB, reversed); } private static _workPointAA0 = Point3d.create(); private static _workPointAA1 = Point3d.create(); private static _workPointBB0 = Point3d.create(); private static _workPointBB1 = Point3d.create(); private static _workPointBB2 = Point3d.create(); private static _workVectorA = Vector3d.create(); /** low level dispatch of linestring with (beziers of) a bspline curve */ public dispatchLineStringBSplineCurve(lsA: LineString3d, curveB: BSplineCurve3d, reversed: boolean): any { const lsB = LineString3d.create(); curveB.emitStrokes(lsB); this.computeLineStringLineString(lsA, lsB, reversed); } /** low level dispatch of linestring with (beziers of) a bspline curve */ public dispatchSegmentBsplineCurve(lsA: LineSegment3d, curveB: BSplineCurve3d, reversed: boolean): any { const lsB = LineString3d.create(); curveB.emitStrokes(lsB); this.computeSegmentLineString(lsA, lsB, reversed); } /** Detail computation for segment approaching linestring. */ public computeSegmentLineString(lsA: LineSegment3d, lsB: LineString3d, reversed: boolean): any { const pointA0 = lsA.point0Ref; const pointA1 = lsA.point1Ref; let pointB0 = CurveCurveCloseApproachXY._workPointBB0; let pointB1 = CurveCurveCloseApproachXY._workPointBB1; let pointB2 = CurveCurveCloseApproachXY._workPointBB2; let cross0, cross1, cross2; let dot0, dot1, dot2; const vectorA = CurveCurveCloseApproachXY._workVectorA; Vector3d.createStartEnd(pointA0, pointA1, vectorA); const aa = vectorA.magnitudeSquared(); const numB = lsB.numPoints(); lsB.packedPoints.getPoint3dAtUncheckedPointIndex(0, pointB0); lsB.packedPoints.getPoint3dAtUncheckedPointIndex(1, pointB0); cross0 = vectorA.crossProductStartEndXY(pointA0, pointB0); cross1 = vectorA.crossProductStartEndXY(pointA0, pointB0); dot0 = vectorA.dotProductStartEndXY(pointA0, pointB0); dot1 = vectorA.dotProductStartEndXY(pointA0, pointB1); for (let iB = 2; iB < numB; iB++) { // project point B[iB] to segmentA. If within limits, see if it is a local minimum distance . . . lsB.packedPoints.getPoint3dAtUncheckedPointIndex(iB, pointB1); cross2 = vectorA.crossProductStartEndXY(pointA0, pointB0); dot2 = vectorA.dotProductStartEndXY(pointA0, pointB2); if ((cross0 - cross1) * (cross2 - cross1) <= 0.0) { // There is a true minimum at point1 ... see if it is within the line if (dot1 >= 0.0 && dot1 <= aa) { const fractionA1 = dot1 / aa; const projection = pointA0.interpolate(dot1 / aa, pointA1); if (pointB1.distanceXY(projection) < this._maxDistanceToAccept!) { const detailA = CurveLocationDetail.createCurveFractionPoint(lsA, fractionA1, projection); const detailB = CurveLocationDetail.createCurveFractionPoint(lsB, iB / (numB - 1), pointB2); const pair = CurveLocationDetailPair.createCaptureOptionalReverse(detailA, detailB, reversed); this._results.push(pair); } } } const tempPoint = pointB0; pointB0 = pointB1; pointB1 = pointB2; pointB2 = tempPoint; const tempCross = cross0; cross0 = cross1; cross1 = cross2; cross2 = tempCross; const tempDot = dot0; dot0 = dot1; dot1 = dot2; dot2 = tempDot; } this.testAndRecordFractionalPairApproach(lsA, 0, 1, true, lsB, 0, 1, false, reversed); return undefined; } /** Detail computation for arcA intersecting lsB. */ public computeArcLineString(arcA: Arc3d, lsB: LineString3d, reversed: boolean): any { const pointB0 = CurveCurveCloseApproachXY._workPointBB0; const pointB1 = CurveCurveCloseApproachXY._workPointBB1; const numB = lsB.numPoints(); if (numB > 1) { const dfB = 1.0 / (numB - 1); let fB0; let fB1; fB0 = 0.0; lsB.pointAt(0, pointB0); for (let ib = 1; ib < numB; ib++, pointB0.setFrom(pointB1), fB0 = fB1) { lsB.pointAt(ib, pointB1); fB1 = ib * dfB; this.dispatchSegmentArc( lsB, pointB0, fB0, pointB1, fB1, arcA, !reversed); } } return undefined; } private static _workPointB0 = Point3d.create(); // private static _workPointB1 = Point3d.create(); /** double dispatch handler for strongly typed segment.. */ public override handleLineSegment3d(segmentA: LineSegment3d): any { if (this._geometryB instanceof LineSegment3d) { const segmentB = this._geometryB; this.dispatchSegmentSegment( segmentA, segmentA.point0Ref, 0.0, segmentA.point1Ref, 1.0, segmentB, segmentB.point0Ref, 0.0, segmentB.point1Ref, 1.0, false); } else if (this._geometryB instanceof LineString3d) { this.computeSegmentLineString(segmentA, this._geometryB, false); } else if (this._geometryB instanceof Arc3d) { this.dispatchSegmentArc( segmentA, segmentA.point0Ref, 0.0, segmentA.point1Ref, 1.0, this._geometryB, false); } else if (this._geometryB instanceof BSplineCurve3d) { this.dispatchSegmentBsplineCurve(segmentA, this._geometryB, false); } } private computeLineStringLineString(lsA: LineString3d, lsB: LineString3d, reversed: boolean) { const rangeA = lsA.range(); const rangeB = lsB.range(); rangeA.expandInPlace(this._maxDistanceToAccept!); if (!rangeB.intersectsRangeXY(rangeA)) return; let bitB0: number; let bitB1: number; const rangeA1 = Range3d.createNull(); const pointA0 = CurveCurveCloseApproachXY._workPointAA0; const pointA1 = CurveCurveCloseApproachXY._workPointAA1; const pointB0 = CurveCurveCloseApproachXY._workPointBB0; const pointB1 = CurveCurveCloseApproachXY._workPointBB1; const numA = lsA.numPoints(); const numB = lsB.numPoints(); if (numA > 1 && numB > 1) { lsA.pointAt(0, pointA0); const dfA = 1.0 / (numA - 1); const dfB = 1.0 / (numB - 1); let fA0 = 0.0; let fB0; let fA1; let fB1; lsA.pointAt(0, pointA0); for (let ia = 1; ia < numA; ia++, pointA0.setFrom(pointA1), fA0 = fA1) { fA1 = ia * dfA; fB0 = 0.0; lsA.pointAt(ia, pointA1); rangeA1.setNull(); rangeA1.extendPoint(pointA0); rangeA1.extendPoint(pointA1); rangeA1.expandInPlace(this._maxDistanceToAccept!); if (rangeA1.intersectsRangeXY(rangeB)) { lsB.pointAt(0, pointB0); bitB0 = classifyBitsPointRangeXY(pointB0.x, pointB0.y, rangeA1); for (let ib = 1; ib < numB; ib++, pointB0.setFrom(pointB1), fB0 = fB1, bitB0 = bitB1) { lsB.pointAt(ib, pointB1); bitB1 = classifyBitsPointRangeXY(pointB1.x, pointB1.y, rangeA1); fB1 = ib * dfB; // Do NOT study the segment in detail if both bitB bits are on for any of the 4 planes . .. if ((bitB0 & bitB1) === 0) { this.dispatchSegmentSegment( lsA, pointA0, fA0, pointA1, fA1, lsB, pointB0, fB0, pointB1, fB1, reversed); } } } } } } /** double dispatch handler for strongly typed linestring.. */ public override handleLineString3d(lsA: LineString3d): any { if (this._geometryB instanceof LineString3d) { const lsB = this._geometryB; this.computeLineStringLineString(lsA, lsB, false); } else if (this._geometryB instanceof LineSegment3d) { this.computeSegmentLineString(this._geometryB, lsA, true); } else if (this._geometryB instanceof Arc3d) { this.computeArcLineString(this._geometryB, lsA, true); } else if (this._geometryB instanceof BSplineCurve3d) { this.dispatchLineStringBSplineCurve(lsA, this._geometryB, false); } return undefined; } /** double dispatch handler for strongly typed arc .. */ public override handleArc3d(arc0: Arc3d): any { if (this._geometryB instanceof LineSegment3d) { this.dispatchSegmentArc( this._geometryB, this._geometryB.point0Ref, 0.0, this._geometryB.point1Ref, 1.0, arc0, true); } else if (this._geometryB instanceof LineString3d) { this.computeArcLineString(arc0, this._geometryB, false); } else if (this._geometryB instanceof Arc3d) { this.dispatchArcArc(arc0, this._geometryB, false); } else if (this._geometryB instanceof BSplineCurve3d) { this.dispatchArcBsplineCurve3d(arc0, this._geometryB, false); } return undefined; } /** double dispatch handler for strongly typed bspline curve .. */ public override handleBSplineCurve3d(curve: BSplineCurve3d): any { if (this._geometryB instanceof LineSegment3d) { this.dispatchSegmentBsplineCurve(this._geometryB, curve, true); } else if (this._geometryB instanceof LineString3d) { this.dispatchLineStringBSplineCurve(this._geometryB, curve, true); } else if (this._geometryB instanceof Arc3d) { this.dispatchArcBsplineCurve3d(this._geometryB, curve, true); } else if (this._geometryB instanceof BSplineCurve3dBase) { this.dispatchBSplineCurve3dBSplineCurve3d(curve, this._geometryB, false); } return undefined; } /** double dispatch handler for strongly typed homogeneous bspline curve .. */ public override handleBSplineCurve3dH(_curve: BSplineCurve3dH): any { /* NEEDS WORK -- make "dispatch" methods tolerant of both 3d and 3dH ..."easy" if both present BezierCurve3dH span loaders if (this._geometryB instanceof LineSegment3d) { this.dispatchSegmentBsplineCurve( this._geometryB, this._extendB, this._geometryB.point0Ref, 0.0, this._geometryB.point1Ref, 1.0, this._extendB, curve, this._extendA, true); } else if (this._geometryB instanceof LineString3d) { this.dispatchLineStringBSplineCurve(this._geometryB, this._extendB, curve, this._extendA, true); } else if (this._geometryB instanceof Arc3d) { this.dispatchArcBsplineCurve3d(this._geometryB, this._extendB, curve, this._extendA, true); } */ return undefined; } }
the_stack
import { XmppJsInstance, XMPP_PROTOCOL } from "./XJSInstance"; import { Element, x } from "@xmpp/xml"; import { jid, JID } from "@xmpp/jid"; import { Logging } from "matrix-appservice-bridge"; import { IConfigBridge } from "../Config"; import { IBasicProtocolMessage } from "..//MessageFormatter"; import { IGatewayJoin, IUserStateChanged, IStoreRemoteUser, IUserInfo } from "../bifrost/Events"; import { IGatewayRoom } from "../bifrost/Gateway"; import { PresenceCache } from "./PresenceCache"; import { XHTMLIM } from "./XHTMLIM"; import { BifrostRemoteUser } from "../store/BifrostRemoteUser"; import { StzaPresenceItem, StzaMessage, StzaMessageSubject, StzaPresenceError, StzaBase, StzaPresenceKick, PresenceAffiliation, PresenceRole } from "./Stanzas"; import { IGateway } from "../bifrost/Gateway"; import { GatewayMUCMembership, IGatewayMemberXmpp, IGatewayMemberMatrix } from "./GatewayMUCMembership"; import { XMPPStatusCode } from "./XMPPConstants"; import { AutoRegistration } from "../AutoRegistration"; import { GatewayStateResolve } from "./GatewayStateResolve"; import { MatrixMembershipEvent } from "../MatrixTypes"; const log = Logging.get("XmppJsGateway"); export interface RemoteGhostExtraData { rooms: { [chatName: string]: {devices: string[], jid: string} } } /** * This class effectively implements a MUC that sits in between the gateway interface * and XMPP. */ export class XmppJsGateway implements IGateway { // For storing room history, should be clipped at MAX_HISTORY per room. private roomHistory: Map<string, [Element]>; // For storing requests to be responded to, like joins private stanzaCache: Map<string, Element>; // id -> stanza private presenceCache: PresenceCache; // Storing every XMPP user and their anonymous. private members: GatewayMUCMembership; constructor(private xmpp: XmppJsInstance, private registration: AutoRegistration, private config: IConfigBridge) { this.roomHistory = new Map(); this.stanzaCache = new Map(); this.members = new GatewayMUCMembership(); this.presenceCache = new PresenceCache(true); } public handleStanza(stanza: Element, gatewayAlias: string) { const delta = this.presenceCache.add(stanza); if (!delta) { log.debug("No delta"); return; } const to = jid(stanza.attrs.to); const convName = `${to.local}@${to.domain}`; const isMucType = stanza.getChildByAttr("xmlns", "http://jabber.org/protocol/muc"); log.info(`Handling ${stanza.name} from=${stanza.attrs.from} to=${stanza.attrs.to} for ${gatewayAlias}`); if ((delta.changed.includes("online") || delta.changed.includes("newdevice")) && isMucType) { this.addStanzaToCache(stanza); // Gateways are special. // We also want to drop the resource from the sender. const from = jid(stanza.attrs.from); const sender = `${from.local}@${from.domain}`; this.xmpp.emit("gateway-joinroom", { join_id: stanza.attrs.id, roomAlias: gatewayAlias, sender, nick: to.resource, protocol_id: XMPP_PROTOCOL.id, room_name: `${to.local}@${to.domain}`, } as IGatewayJoin); } else if (delta.changed.includes("offline")) { const wasKicked = delta.status!.kick; let kicker: string|undefined; if (wasKicked && wasKicked.kicker) { kicker = `${convName}/${wasKicked.kicker}`; } const member = this.members.getXmppMemberByDevice(convName, stanza.attrs.from); const lastDevice = this.remoteLeft(stanza); if (!member) { log.warn("User has gone offline, but we don't have a member for them"); return; } if (!lastDevice) { // User still has other devices, not leaving. log.info(`User has ${member.devices.size} other devices, not leaving.`); return; } this.xmpp.emit("chat-user-left", { conv: { name: convName, }, account: { protocol_id: XMPP_PROTOCOL.id, username: convName, }, sender: member.realJid.toString(), state: "left", kicker, reason: wasKicked ? wasKicked.reason : delta.status!.status, gatewayAlias, } as IUserStateChanged); } else { log.debug("Nothing to do"); } } public addStanzaToCache(stanza: Element) { this.stanzaCache.set(stanza.attrs.id, stanza); log.debug("Added cached stanza for " + stanza.attrs.id); } public memberInRoom(chatName: string, matrixId: string) { return !!this.members.getXmppMemberByMatrixId(chatName, matrixId); } public isJIDInMuc(chatName: string, j: JID) { return !!this.members.getXmppMemberByDevice(chatName, j); } public getMatrixIDForJID(chatName: string, j: JID) { const user = this.members.getMemberByAnonJid<IGatewayMemberMatrix>(chatName, j.toString()); if (!user) { return false; } log.debug(`Got ${user.matrixId} for ${chatName}`); return user.matrixId; } public getAnonIDForJID(chatName: string, j: JID): string|null { const member = this.members.getXmppMemberByRealJid(chatName, j.toString()); if (member) { return member.anonymousJid.toString(); } return null; } public sendMatrixMessage( chatName: string, sender: string, msg: IBasicProtocolMessage, room: IGatewayRoom) { this.updateMatrixMemberListForRoom(chatName, room); log.info(`Sending ${msg.id} to ${chatName}`); const from = this.members.getMatrixMemberByMatrixId(chatName, sender); if (!from) { log.error(`Cannot send ${msg.id}: No member cached.`); return; } this.xmpp.xmppAddSentMessage(msg.id!); // Ensure that the html portion is XHTMLIM if (msg.formatted) { msg.formatted!.forEach((fmt) => { if (fmt.type === "html") { fmt.body = XHTMLIM.HTMLToXHTML(fmt.body); } }); } const msgs = [...this.members.getXmppMembersDevices(chatName)].map((device) => new StzaMessage( from.anonymousJid.toString(), device, msg, "groupchat", ) ); return this.xmpp.xmppSendBulk(msgs); } /** * Send a XMPP message to the occupants of a gateway. * * @param chatName The XMPP MUC name * @param stanza The XMPP stanza message * @returns If the message was sent successfully. */ public async reflectXMPPMessage(chatName: string, stanza: Element, kickNonMember=true): Promise<boolean> { const member = this.members.getXmppMemberByRealJid(chatName, stanza.attrs.from); if (!member && kickNonMember) { log.warn(`${stanza.attrs.from} is not part of this room.`); // Send the sender an error. const kick = new StzaPresenceKick( stanza.attrs.to, stanza.attrs.from, ); kick.statusCodes.add(XMPPStatusCode.SelfPresence); kick.statusCodes.add(XMPPStatusCode.SelfKicked); kick.statusCodes.add(XMPPStatusCode.SelfKickedTechnical); await this.xmpp.xmppSend(kick); return false; } const preserveFrom = stanza.attrs.from; try { stanza.attrs.from = member!.anonymousJid; const devices = this.members.getXmppMembersDevices(chatName); for (const deviceJid of devices) { stanza.attrs.to = deviceJid; this.xmpp.xmppWriteToStream(stanza); } } catch (err) { log.warn("Failed to reflect XMPP message:", err); stanza.attrs.from = preserveFrom; return false; } stanza.attrs.from = preserveFrom; return true; } public reflectXMPPStanza(chatName: string, stanza: StzaBase) { const xmppDevices = [...this.members.getXmppMembersDevices(chatName)]; return Promise.all(xmppDevices.map((device) => { stanza.to = device; return this.xmpp.xmppSend(stanza); })); } public reflectPM(stanza: Element) { const to = jid(stanza.attrs.to); const convName = `${to.local}@${to.domain}`; // This is quite easy.. const sender = this.members.getXmppMemberByRealJid(convName, stanza.attrs.from); if (!sender) { log.error("Cannot find sender in memberlist for PM"); return; } const recipient = this.members.getMemberByAnonJid<IGatewayMemberXmpp>(convName, stanza.attrs.to); if (!recipient) { log.error("Cannot find recipient in memberlist for PM"); return; } stanza.attrs.from = sender.anonymousJid.toString(); for (const device of recipient.devices) { stanza.attrs.to = device; log.info(`Reflecting PM message ${stanza.attrs.from} -> ${stanza.attrs.to}`); this.xmpp.xmppWriteToStream(stanza); } } public async sendMatrixMembership( chatName: string, event: MatrixMembershipEvent, ) { log.info(`Got new ${event.content.membership} for ${event.state_key} (from: ${event.sender}) in ${chatName}`); // Iterate around each joined member and add the new presence step. const presenceEvents = GatewayStateResolve.resolveMatrixStateToXMPP(chatName, this.members, event); if (presenceEvents.length === 0) { log.info(`Nothing to do for ${event.event_id}`); return; } await this.xmpp.xmppSendBulk(presenceEvents); } public sendStateChange( chatName: string, sender: string, type: "topic"|"name"|"avatar", room: IGatewayRoom, ) { log.info(`Got new ${type} for ${sender} in ${chatName}`); // Iterate around each joined member and add the new presence step. const users = this.members.getXmppMembers(chatName); if (users.length === 0) { log.warn("No users found for gateway room!"); } if (type !== "topic" && type !== "name") { return; } this.reflectXMPPStanza(chatName, new StzaMessageSubject(chatName, "", undefined, `${room.name || ""} ${room.topic ? "| " + room.topic : ""}`, )); } public getMxidForRemote(sender: string) { const j = jid(sender); const username = `${j.local}@${j.domain}`; return XMPP_PROTOCOL.getMxIdForProtocol(username, this.config.domain, this.config.userPrefix).getId(); } public async onRemoteJoin( err: string|null, joinId: string, room: IGatewayRoom|undefined, ownMxid: string|undefined, ) { const startTs = Date.now(); log.debug("Handling remote join for " + joinId); const stanza = this.stanzaCache.get(joinId); this.stanzaCache.delete(joinId); if (!stanza) { log.error("Could not find stanza in cache for remoteJoin. Cannot handle"); throw Error("Stanza for join not in cache, cannot handle"); } const from = jid(stanza.attrs.from); const to = jid(stanza.attrs.to); const chatName = `${to.local}@${to.domain}`; if (err || !room) { const presenceStatus = this.presenceCache.getStatus(stanza.attrs.from); if (presenceStatus) { presenceStatus.online = false; this.presenceCache.modifyStatus(stanza.attrs.from, presenceStatus); } log.warn("Responding with an error to remote join:", err); // XXX: Specify the actual failure reason. this.xmpp.xmppSend(new StzaPresenceError( stanza.attrs.to, stanza.attrs.from, stanza.attrs.id, chatName, "cancel", "service-unavailable", err, )); return; } room = room!; if (!ownMxid) { throw Error('ownMxid is not defined'); } // Ensure our membership is accurate. this.updateMatrixMemberListForRoom(chatName, room, true); // HACK: Always update members for joiners // Check if the nick conflicts. const existingMember = this.members.getMemberByAnonJid(chatName, stanza.attrs.to); if (existingMember) { if (existingMember.type === "matrix") { log.error("Conflicting nickname, not joining"); this.xmpp.xmppSend(new StzaPresenceError( stanza.attrs.to, stanza.attrs.from, stanza.attrs.id, chatName, "cancel", "conflict", )); throw Error("Conflicting nickname, not joining"); } const existingXmppMember = existingMember as IGatewayMemberXmpp; const existingUserId = `${existingXmppMember.realJid!.local}@${existingXmppMember.realJid!.domain}`; const currentUserId = `${from.local}@${from.domain}`; if (existingXmppMember.devices.has(stanza.attrs.from)) { log.debug("Existing device has requested a join"); // An existing device has reconnected, so fall through here. } else if (existingUserId === currentUserId) { log.debug(`${currentUserId} is joining from a new device ${from.resource}`); } else { // Different user after the same nick, heck them. log.error("Conflicting nickname, not joining"); this.xmpp.xmppSend(new StzaPresenceError( stanza.attrs.to, stanza.attrs.from, stanza.attrs.id, chatName, "cancel", "conflict", )); throw Error("Conflicting nickname, not joining"); } } /* Critical section - We need to emit membership to the user, but we can't store they are joined yet. https://github.com/matrix-org/matrix-bifrost/issues/132 */ // https://xmpp.org/extensions/xep-0045.html#order // 1. membership of others. log.debug('Emitting membership of other users'); // Ensure we chunk this const allMembershipPromises: Promise<unknown>[] = []; for (const member of this.members.getMembers(chatName)) { if (member.anonymousJid.toString() === stanza.attrs.to) { continue; } allMembershipPromises.push((async () => { let realJid; if ((member as IGatewayMemberXmpp).realJid) { realJid = (member as IGatewayMemberXmpp).realJid.toString(); } else { realJid = this.registration.generateParametersFor( XMPP_PROTOCOL.id, (member as IGatewayMemberMatrix).matrixId, ).username; } return this.xmpp.xmppSend( new StzaPresenceItem( member.anonymousJid.toString(), stanza.attrs.from, undefined, PresenceAffiliation.Member, PresenceRole.Participant, false, realJid, ), ) })()); } // Wait for all presence to be sent first. await Promise.all(allMembershipPromises); log.debug("Emitting membership of self"); // 2. Send everyone else the users new presence. const reflectedPresence = new StzaPresenceItem( stanza.attrs.to, "", undefined, PresenceAffiliation.Member, PresenceRole.Participant, false, stanza.attrs.from, ); await this.reflectXMPPStanza(chatName, reflectedPresence); // FROM THIS POINT ON, WE CONSIDER THE USER JOINED. // 3. Send the user self presence const selfPresence = new StzaPresenceItem( stanza.attrs.to, stanza.attrs.from, stanza.attrs.id, PresenceAffiliation.Member, PresenceRole.Participant, true, ); // Matrix is non-anon, and Matrix logs. selfPresence.statusCodes.add(XMPPStatusCode.RoomNonAnonymous); selfPresence.statusCodes.add(XMPPStatusCode.RoomLoggingEnabled); await this.xmpp.xmppSend(selfPresence); this.members.addXmppMember( `${to.local}@${to.domain}`, from, to, ownMxid, ); // 4. Room history log.debug("Emitting history"); const history: Element[] = this.roomHistory.get(room.roomId) || []; history.forEach((e) => { e.attrs.to = stanza.attrs.from; // TODO: Add delay info to this. this.xmpp.xmppWriteToStream(e); }); log.debug("Emitting subject"); // 5. The room subject this.xmpp.xmppSend(new StzaMessageSubject(chatName, stanza.attrs.from, undefined, `${room.name || ""} ${room.topic ? "| " + room.topic : ""}`, )); // All done, now for some house cleaning. // Store this user so we can reconnect them on restart. this.upsertXMPPUser(from, ownMxid); log.debug(`Join complete for ${to}. Took ${Date.now() - startTs}ms`); } private upsertXMPPUser(realJid: JID, mxId: string) { const rooms = this.members.getAnonJidsForXmppJid(realJid); const realJidStripped = `${realJid.local}@${realJid.domain}`; this.xmpp.emit("store-remote-user", { mxId, remoteId: realJidStripped, protocol_id: XMPP_PROTOCOL.id, data: { rooms, }, } as IStoreRemoteUser); log.debug(`Upserted XMPP user ${realJidStripped} ${realJidStripped}`); } public initialMembershipSync(chatName: string, room: IGatewayRoom, ghosts: BifrostRemoteUser[]) { log.info(`Adding initial synced member list to ${chatName}`); this.updateMatrixMemberListForRoom(chatName, room); for (const xmppUser of ghosts) { log.debug(`Connecting ${xmppUser.id} to ${chatName}`); const extraData = xmppUser.extraData as RemoteGhostExtraData; if (!extraData.rooms) { log.debug("Didn't connect, no data"); return; } const roomData = extraData.rooms[chatName]; if (!roomData) { log.warn(`No information stored for ${xmppUser.id} to ${chatName}`); return; } roomData.devices.forEach((device: string) => this.members.addXmppMember( chatName, jid(device), jid(roomData.jid), xmppUser.id, )); } } public async getUserInfo(who: string): Promise<IUserInfo> { const j = jid(who); let nickname = j.resource || j.local; let photo: string|undefined; try { const res = await this.xmpp.getVCard(who); nickname = res.getChild("NICKNAME")?.getText() || nickname; const photoElement = res.getChild("PHOTO"); if (photoElement) { photo = `${photoElement.getChildText("TYPE")}|${photoElement.getChildText("BINVAL")}`; } } catch (ex) { log.warn("Failed to fetch VCard", ex); } const ui: IUserInfo = { Nickname: j.resource || j.local, Avatar: photo, eventName: "meh", who, account: { protocol_id: "", username: "", }, }; return ui; } public async getAvatarBuffer(uri: string, senderId: string): Promise<{ type: string; data: Buffer; }> { // The URI is the base64 value of the data prefixed by the type. const [type, dataBase64] = uri.split("|"); if (!type || !type.includes("/") || !dataBase64) { throw Error("Avatar uri was malformed"); } const data = Buffer.from(dataBase64, "base64"); return { type, data }; } public maskPMSenderRecipient(senderMxid: string, recipientJid: string) : {recipient: string, sender: string}|undefined { const j = jid(recipientJid); const convName = `${j.local}@${j.domain}`; log.info("Looking up possible gateway:", senderMxid, recipientJid, convName); const recipient = this.members.getMemberByAnonJid<IGatewayMemberXmpp>(convName, recipientJid); if (!recipient) { return undefined; } const sender = this.members.getMatrixMemberByMatrixId(convName, senderMxid); if (!sender) { log.warn("Couldn't get sender's mxid"); throw Error("Couldn't find the senders anonymous jid for a MUC PM over the gateway"); } return { recipient: recipient.devices[recipient.devices.size - 1].toString(), sender: sender.anonymousJid.toString(), }; } private updateMatrixMemberListForRoom(chatName: string, room: IGatewayRoom, allowForJoin = false) { if (!allowForJoin && this.members.getMatrixMembers(chatName)) { return; } let joined = 0; let left = 0; for (const member of room.membership) { if (member.isRemote) { continue; } if (member.membership === "join") { joined++; this.members.addMatrixMember( chatName, member.stateKey, jid(`${chatName}/${member.displayname || member.stateKey}`), ); } else if (member.membership === "leave") { left++; this.members.removeMatrixMember( chatName, member.stateKey, ); } } log.info(`Updating membership for ${chatName} ${room.roomId} j:${joined} l:${left}`); } private remoteLeft(stanza: Element) { log.info(`${stanza.attrs.from} left ${stanza.attrs.to}`); const to = jid(stanza.attrs.to); const chatName = `${to.local}@${to.domain}`; const user = this.members.getXmppMemberByRealJid(chatName, stanza.attrs.from); if (!user) { log.error(`User tried to leave room, but they aren't in the member list`); return false; } const lastDevice = this.members.removeXmppMember(chatName, stanza.attrs.from); const leaveStza = new StzaPresenceItem( user.anonymousJid.toString(), stanza.attrs.from, undefined, PresenceAffiliation.Member, PresenceRole.None, true, stanza.attrs.from, ); leaveStza.presenceType = "unavailable"; this.xmpp.xmppWriteToStream(leaveStza); this.upsertXMPPUser(stanza.attrs.from, user.matrixId); // If this is the last device for that member, reflect // that change to everyone. if (lastDevice) { leaveStza.self = false; this.reflectXMPPStanza(chatName, leaveStza); return true; } return false; } }
the_stack
import * as _ from 'lodash'; import {AbstractComponent} from '@common/component/abstract.component'; import { Component, ElementRef, EventEmitter, Injector, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChange, SimpleChanges, ViewChild } from '@angular/core'; import {TimeUnit} from '@domain/workbook/configurations/field/timestamp-field'; import {CommonUtil} from '@common/util/common.util'; import {EventBroadcaster} from '@common/event/event.broadcaster'; import {PickerSettings} from '@domain/common/datepicker.settings'; import {TimeDateFilter} from '@domain/workbook/configurations/filter/time-date-filter'; import {FilterUtil} from '../../util/filter.util'; declare let moment: any; declare let $: any; @Component({ selector: 'component-time-date', templateUrl: 'time-date.component.html' }) export class TimeDateComponent extends AbstractComponent implements OnInit, OnChanges, OnDestroy{ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ // DatePicker 객체 private _datePicker; private _date: Date; @ViewChild('datePickerInput') private _datePickerInput: ElementRef; // Quarter 및 Week 목록 private _quarterList: ComboItem[] = []; private _weekList: ComboItem[] = []; /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ @Input('mode') public mode: 'CHANGE' | 'WIDGET' | 'PANEL' = 'CHANGE'; // 화면 모드 @Input('initial') public compData: TimeDateData; @Output() public onDateChange: EventEmitter<any> = new EventEmitter(); public comboList: ComboItem[] = []; public dateComboIdx: number = 0; public selectedDateComboItem: ComboItem; public isLatestDateTime: boolean = false; /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Constructor |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ // 생성자 constructor(protected broadCaster: EventBroadcaster, protected elementRef: ElementRef, protected injector: Injector) { super(elementRef, injector); for (let idx = 1; idx <= 52; idx++) { this._weekList.push(new ComboItem('W' + idx, idx)); } for (let idx = 1; idx <= 4; idx++) { this._quarterList.push(new ComboItem('Q' + idx, idx)); } } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Override Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * 컴포넌트 초기 실행 */ public ngOnInit() { super.ngOnInit(); } /** * Input 값 변경 체크 * @param {SimpleChanges} changes */ public ngOnChanges(changes: SimpleChanges): void { const compDataChanges: SimpleChange = changes.compData; if (compDataChanges){ const currVal: TimeDateData = compDataChanges.currentValue; const preVal: TimeDateData = compDataChanges.previousValue; if(!preVal || currVal.timeUnit !== preVal.timeUnit || currVal.valueDate !== preVal.valueDate ) { this._setPicker(); } } } /** * 컴포넌트 제거 */ public ngOnDestroy() { super.ngOnDestroy(); // Date Picker 객체 제거 (this._datePicker) && (this._datePicker.destroy()); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Getter / Setter |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * 위젯 모드 여부 */ public get isWidgetMode(): boolean { return 'WIDGET' === this.mode; } // get - isWidgetMode /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * 콤보박스 선택 이벤트 * @param {ComboItem} item * @param {boolean} isFrom */ public onSelectComboItem(item: ComboItem) { this.selectedDateComboItem = item; this.onDateChange.emit(this._getTimeDate()); } // function - onSelectComboItem /** * 콤보박스 표시 여부 * @param {boolean} isShow */ public onToggleSelectOptions(isShow: boolean) { this.broadCaster.broadcast('TIME_DATE_SHOW_SELECT_OPTS', { isShow : isShow }); } // func - onToggleSelectOptions /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * DatePicker 설정 * @private */ private _setPicker(){ this.safelyDetectChanges(); if( !this.compData ) { return; } const maxTime: Date = this.compData.maxTime; let valueDate = this.compData.valueDate; if (valueDate === TimeDateFilter.LATEST_DATETIME) { if( this.isWidgetMode ) { this.isLatestDateTime = false; valueDate = FilterUtil.getDateTimeFormat(maxTime, this.compData.timeUnit); } else { this.isLatestDateTime = true; } } else { this.isLatestDateTime = false; } this.safelyDetectChanges(); if (this.isLatestDateTime) { if(this._datePicker) { this._datePicker.destroy(); this._datePicker = undefined; } } else { let dateMoment; if (valueDate && 'undefined' !== valueDate){ dateMoment = (TimeUnit.WEEK === this.compData.timeUnit) ? valueDate : this.customMoment(valueDate); } else{ dateMoment = moment(); } if (TimeUnit.WEEK === this.compData.timeUnit){ this.comboList = _.cloneDeep(this._weekList); let dateWeek; const arrDateInfo = (valueDate as string).split('-'); dateMoment = moment(arrDateInfo[0] + '-01-01'); dateWeek = Number(arrDateInfo[1]); this.dateComboIdx = this.comboList.findIndex(item => item.value === dateWeek); this.selectedDateComboItem = this.comboList[this.dateComboIdx]; } else if (TimeUnit.QUARTER === this.compData.timeUnit){ this.comboList = _.cloneDeep(this._quarterList); const dateQuarter: number = dateMoment.quarter(); this.dateComboIdx = this.comboList.findIndex(item => item.value === dateQuarter); this.selectedDateComboItem = this.comboList[this.dateComboIdx]; } this._date = dateMoment.toDate(); if(this.isNullOrUndefined(this._datePicker)){ const datePickerSettings: TimeDatePickerSettings = new TimeDatePickerSettings( 'ddp-text-calen', (_date: string, date: Date) => { this._date= date; }, ()=>{ this.onDateChange.emit(this._getTimeDate()); }, this.compData.timeUnit ); this._datePicker = $(this._datePickerInput.nativeElement).datepicker(datePickerSettings).data('datepicker'); } this._datePicker.date = this._date; this._datePicker.selectDate(this._date); } } // func - _setPicker /** * 값 검증 * @returns {TimeDate} */ private _getTimeDate(): TimeDate{ const currTimeUnit: TimeUnit = this.compData.timeUnit; if (TimeUnit.YEAR === currTimeUnit){ return this._getDateFromMoment(moment().year(this._date.getFullYear()),'year'); } else if (TimeUnit.QUARTER === currTimeUnit) { return this._getDateFromMoment(moment().year(this._date.getFullYear()).quarter(this.selectedDateComboItem.value), 'quarter'); } else if (TimeUnit.MONTH === currTimeUnit) { return this._getDateFromMoment(moment().year(this._date.getFullYear()).month(this._date.getMonth()), 'month'); } else if (TimeUnit.WEEK === currTimeUnit) { return new TimeDate( this._date.getFullYear() + '-' + this.selectedDateComboItem.value) } else if (TimeUnit.DAY === currTimeUnit) { return new TimeDate(moment().year(this._date.getFullYear()).month(this._date.getMonth()).date(this._date.getDate()).startOf('date').format('YYYY-MM-DDTHH:mm:ss.sss') + 'Z') } else { return new TimeDate(moment(this._date).format('YYYY-MM-DDTHH:mm:ss.sss') + 'Z'); } } /** * Moment 로 부터 Date 정보를 얻음 * @param dateMoment * @param range * @private */ private _getDateFromMoment(dateMoment: any, range: string): TimeDate{ return new TimeDate( dateMoment.startOf(range).format('YYYY-MM-DDTHH:mm:ss.sss') + 'Z' ); } } export class TimeDate{ public valueDate: Date | string; constructor(valueDate: Date | string) { this.valueDate = valueDate; } } export class TimeDateData { public minTime: Date; public maxTime: Date; public valueDate: Date | string; public timeUnit: TimeUnit; constructor(valueDate: Date | string, minTime: Date, maxTime: Date, timeUnit?: TimeUnit) { this.valueDate = valueDate; this.minTime = minTime; this.maxTime = maxTime; this.timeUnit = (CommonUtil.isNullOrUndefined(timeUnit)) ? TimeUnit.NONE : timeUnit; } } /** * 콤보 박스 아이템 */ class ComboItem { public label: string; public value: number; constructor(label: string, value: number) { this.label = label; this.value = value; } } // structure - ComboItem class TimeDatePickerSettings extends PickerSettings { constructor(clz: string, onSelectDate: (fdate: string, date: Date) => void, onHide: () => void, timeUnit: TimeUnit) { super(clz, onSelectDate, onHide); switch (timeUnit) { case TimeUnit.YEAR: case TimeUnit.QUARTER: case TimeUnit.WEEK : this.dateFormat = 'yyyy'; this.minView = 'years'; this.view = 'years'; break; case TimeUnit.MONTH : this.dateFormat = 'yyyy-mm'; this.minView = 'months'; this.view = 'months'; break; case TimeUnit.DAY : this.dateFormat = 'yyyy-mm-dd'; this.minView = 'days'; this.view = 'days'; break; case TimeUnit.HOUR: this.dateFormat = 'yyyy-mm-dd'; this.timeFormat = 'hh'; this.minView = 'days'; this.view = 'days'; this.timepicker = true; break; default : this.dateFormat = 'yyyy-mm-dd'; this.timeFormat = 'hh:ii'; this.minView = 'days'; this.view = 'days'; this.timepicker = true; break; } } } // structure - TimeDatePickerSettings
the_stack
import * as fs from "fs"; import * as parse5 from "parse5"; import * as dom5 from "dom5"; import * as path from "path"; import {Node} from 'dom5'; import {fail, unexpectedSwitchValue} from "../utils/common"; import {readMultilineParamFile} from "../utils/command-line"; import { HtmlSrcFilePath, JsSrcFilePath, HtmlTargetFilePath, JsTargetFilePath, FileUtils, FilePath } from "../utils/file-utils"; import { AbsoluteWebPath, getRelativeImport, NodeModuleImportPath, SrcWebSite } from "../utils/web-site-utils"; /** * Update source code by moving all scripts out of HTML files. * Input: * input_output_html_param_file - list of file paths, each file path on a separate line * The first 3 line contains the path to the first input HTML file and 2 output paths * (for HTML and JS files) * The second 3 line contains paths for the second HTML file, and so on. * * input_output_js_param_file - similar to input_output_html_param_file, but has only 2 lines * per file (input JS file and output JS file) * * input_web_root_path - path (in filesystem) which should be treated as a web-site root path. * For each HTML file it creates 2 output files - HTML and JS file. * HTML file contains everything from HTML input file, except <script> tags. * JS file contains (in the same order, as in original HTML): * - inline javascript code from HTML file * - each <script src = "path/to/file.js" > from HTML is converted to * import 'path/to/output/file.js' * statement. Such import statement run all side-effects in file.js (i.e. it run all # * global code). * - each <link rel="import" href = "path/to/file.html"> adds to .js file as * import 'path/to/output/file.html.js * i.e. instead of html, the .js script imports * Because output JS keeps the order of imports, all global variables are * initialized in a correct order (this is important for gerrit; it is impossible to use * AMD modules here). */ enum RefType { Html, InlineJS, JSFile } type LinkOrScript = HtmlFileRef | HtmlFileNodeModuleRef | JsFileReference | JsFileNodeModuleReference | InlineJS; interface HtmlFileRef { type: RefType.Html, path: HtmlSrcFilePath; isNodeModule: false; } interface HtmlFileNodeModuleRef { type: RefType.Html, path: NodeModuleImportPath; isNodeModule: true; } function isHtmlFileRef(ref: LinkOrScript): ref is HtmlFileRef { return ref.type === RefType.Html; } interface JsFileReference { type: RefType.JSFile, path: JsSrcFilePath; isModule: boolean; isNodeModule: false; } interface JsFileNodeModuleReference { type: RefType.JSFile, path: NodeModuleImportPath; isModule: boolean; isNodeModule: true; } interface InlineJS { type: RefType.InlineJS, isModule: boolean; content: string; } interface HtmlOutputs { html: HtmlTargetFilePath; js: JsTargetFilePath; } interface JsOutputs { js: JsTargetFilePath; } type HtmlSrcToOutputMap = Map<HtmlSrcFilePath, HtmlOutputs>; type JsSrcToOutputMap = Map<JsSrcFilePath, JsOutputs>; interface HtmlFileInfo { src: HtmlSrcFilePath; ast: parse5.AST.Document; linksAndScripts: LinkOrScript[] } /** HtmlScriptAndLinksCollector walks through HTML file and collect * all links and inline scripts. */ class HtmlScriptAndLinksCollector { public constructor(private readonly webSite: SrcWebSite) { } public collect(src: HtmlSrcFilePath): HtmlFileInfo { const ast = HtmlScriptAndLinksCollector.getAst(src); const isHtmlImport = (node: Node) => node.tagName == "link" && dom5.getAttribute(node, "rel") == "import"; const isScriptTag = (node: Node) => node.tagName == "script"; const linksAndScripts: LinkOrScript[] = dom5 .nodeWalkAll(ast as Node, (node) => isHtmlImport(node) || isScriptTag(node)) .map((node) => { if (isHtmlImport(node)) { const href = dom5.getAttribute(node, "href"); if (!href) { fail(`Tag <link rel="import...> in the file '${src}' doesn't have href attribute`); } if(this.webSite.isNodeModuleReference(href)) { return { type: RefType.Html, path: this.webSite.getNodeModuleImport(href), isNodeModule: true, } } else { return { type: RefType.Html, path: this.webSite.resolveHtmlImport(src, href), isNodeModule: false, } } } else { const isModule = dom5.getAttribute(node, "type") === "module"; if (dom5.hasAttribute(node, "src")) { let srcPath = dom5.getAttribute(node, "src")!; if(this.webSite.isNodeModuleReference(srcPath)) { return { type: RefType.JSFile, isModule: isModule, path: this.webSite.getNodeModuleImport(srcPath), isNodeModule: true }; } else { return { type: RefType.JSFile, isModule: isModule, path: this.webSite.resolveScriptSrc(src, srcPath), isNodeModule: false }; } } return { type: RefType.InlineJS, isModule: isModule, content: dom5.getTextContent(node) }; } }); return { src, ast, linksAndScripts }; }; private static getAst(file: string): parse5.AST.Document { const html = fs.readFileSync(file, "utf-8"); return parse5.parse(html, {locationInfo: true}); } } /** Generate js files */ class ScriptGenerator { public constructor(private readonly pathMapper: SrcToTargetPathMapper) { } public generateFromJs(src: JsSrcFilePath) { FileUtils.copyFile(src, this.pathMapper.getJsTargetForJs(src)); } public generateFromHtml(html: HtmlFileInfo) { const content: string[] = []; const src = html.src; const targetJsFile: JsTargetFilePath = this.pathMapper.getJsTargetForHtml(src); html.linksAndScripts.forEach((linkOrScript) => { switch (linkOrScript.type) { case RefType.Html: if(linkOrScript.isNodeModule) { const importPath = this.pathMapper.getJsTargetForHtmlInNodeModule(linkOrScript.path) content.push(`import '${importPath}';`); } else { const importPath = this.pathMapper.getJsTargetForHtml(linkOrScript.path); const htmlRelativePath = getRelativeImport(targetJsFile, importPath); content.push(`import '${htmlRelativePath}';`); } break; case RefType.JSFile: if(linkOrScript.isNodeModule) { content.push(`import '${linkOrScript.path}'`); } else { const importFromJs = this.pathMapper.getJsTargetForJs(linkOrScript.path); const scriptRelativePath = getRelativeImport(targetJsFile, importFromJs); content.push(`import '${scriptRelativePath}';`); } break; case RefType.InlineJS: content.push(linkOrScript.content); break; default: unexpectedSwitchValue(linkOrScript); } }); FileUtils.writeContent(targetJsFile, content.join("\n")); } } /** Generate html files*/ class HtmlGenerator { constructor(private readonly pathMapper: SrcToTargetPathMapper) { } public generateFromHtml(html: HtmlFileInfo) { const ast = html.ast; dom5.nodeWalkAll(ast as Node, (node) => node.tagName === "script") .forEach((scriptNode) => dom5.remove(scriptNode)); const newContent = parse5.serialize(ast); if(newContent.indexOf("<script") >= 0) { fail(`Has content ${html.src}`); } FileUtils.writeContent(this.pathMapper.getHtmlTargetForHtml(html.src), newContent); } } function readHtmlSrcToTargetMap(paramFile: string): HtmlSrcToOutputMap { const htmlSrcToTarget: HtmlSrcToOutputMap = new Map(); const input = readMultilineParamFile(paramFile); for(let i = 0; i < input.length; i += 3) { const srcHtmlFile = path.resolve(input[i]) as HtmlSrcFilePath; const targetHtmlFile = path.resolve(input[i + 1]) as HtmlTargetFilePath; const targetJsFile = path.resolve(input[i + 2]) as JsTargetFilePath; htmlSrcToTarget.set(srcHtmlFile, { html: targetHtmlFile, js: targetJsFile }); } return htmlSrcToTarget; } function readJsSrcToTargetMap(paramFile: string): JsSrcToOutputMap { const jsSrcToTarget: JsSrcToOutputMap = new Map(); const input = readMultilineParamFile(paramFile); for(let i = 0; i < input.length; i += 2) { const srcJsFile = path.resolve(input[i]) as JsSrcFilePath; const targetJsFile = path.resolve(input[i + 1]) as JsTargetFilePath; jsSrcToTarget.set(srcJsFile as JsSrcFilePath, { js: targetJsFile as JsTargetFilePath }); } return jsSrcToTarget; } class SrcToTargetPathMapper { public constructor( private readonly htmlSrcToTarget: HtmlSrcToOutputMap, private readonly jsSrcToTarget: JsSrcToOutputMap) { } public getJsTargetForHtmlInNodeModule(file: NodeModuleImportPath): JsTargetFilePath { return `${file}_gen.js` as JsTargetFilePath; } public getJsTargetForHtml(html: HtmlSrcFilePath): JsTargetFilePath { return this.getHtmlOutputs(html).js; } public getHtmlTargetForHtml(html: HtmlSrcFilePath): HtmlTargetFilePath { return this.getHtmlOutputs(html).html; } public getJsTargetForJs(js: JsSrcFilePath): JsTargetFilePath { return this.getJsOutputs(js).js; } private getHtmlOutputs(html: HtmlSrcFilePath): HtmlOutputs { if(!this.htmlSrcToTarget.has(html)) { fail(`There are no outputs for the file '${html}'`); } return this.htmlSrcToTarget.get(html)!; } private getJsOutputs(js: JsSrcFilePath): JsOutputs { if(!this.jsSrcToTarget.has(js)) { fail(`There are no outputs for the file '${js}'`); } return this.jsSrcToTarget.get(js)!; } } function main() { if(process.argv.length < 5) { const execFileName = path.basename(__filename); fail(`Usage:\nnode ${execFileName} input_web_root_path input_output_html_param_file input_output_js_param_file\n`); } const srcWebSite = new SrcWebSite(path.resolve(process.argv[2]) as FilePath); const htmlSrcToTarget: HtmlSrcToOutputMap = readHtmlSrcToTargetMap(process.argv[3]); const jsSrcToTarget: JsSrcToOutputMap = readJsSrcToTargetMap(process.argv[4]); const pathMapper = new SrcToTargetPathMapper(htmlSrcToTarget, jsSrcToTarget); const scriptGenerator = new ScriptGenerator(pathMapper); const htmlGenerator = new HtmlGenerator(pathMapper); const scriptAndLinksCollector = new HtmlScriptAndLinksCollector(srcWebSite); htmlSrcToTarget.forEach((targets, src) => { const htmlFileInfo = scriptAndLinksCollector.collect(src); scriptGenerator.generateFromHtml(htmlFileInfo); htmlGenerator.generateFromHtml(htmlFileInfo); }); jsSrcToTarget.forEach((targets, src) => { scriptGenerator.generateFromJs(src); }); } main();
the_stack
import * as pulumi from "@pulumi/pulumi"; import { permutation } from "js-combinatorics"; pulumi.runtime.setConfig("aws:region", "us-east-2"); import * as assert from "assert"; import * as utils from "../../utils"; import { Cidr32Block } from "../../ec2/cidr"; import { VpcSubnetArgs } from "../../ec2/vpc"; import * as vpcTopology from "../../ec2/vpcTopology"; function topology( cidr: string, availabilityZones: vpcTopology.AvailabilityZoneDescription[], numberOfNatGateways: number, subnets: VpcSubnetArgs[]) { return vpcTopology.create( undefined, "testing", cidr, undefined, availabilityZones, numberOfNatGateways, false, subnets); } function subnets( cidr: string, availabilityZones: vpcTopology.AvailabilityZoneDescription[], subnets: VpcSubnetArgs[]) { return topology(cidr, availabilityZones, availabilityZones.length, subnets).subnets; } async function jsonEqual(desc1: vpcTopology.VpcTopologyDescription, desc2: vpcTopology.VpcTopologyDescription) { const unwrapped1 = await (<any>pulumi.output(desc1)).promise(); const unwrapped2 = await (<any>pulumi.output(desc2)).promise(); return assert.equal(JSON.stringify(unwrapped1, null, 4), JSON.stringify(unwrapped2, null, 4)); } async function subnetsEqual(desc1: vpcTopology.SubnetDescription[], desc2: vpcTopology.SubnetDescription[]) { const unwrapped1 = await (<any>pulumi.output(desc1)).promise(); const unwrapped2 = await (<any>pulumi.output(desc2)).promise(); return assert.equal(JSON.stringify(unwrapped1, null, 4), JSON.stringify(unwrapped2, null, 4)); } const AZ1 = { name: "name_a", id: "id_a" }; const AZ2 = { name: "name_b", id: "id_b" }; const AZ3 = { name: "name_c", id: "id_c" }; const AZ4 = { name: "name_d", id: "id_d" }; const AZ5 = { name: "name_e", id: "id_e" }; const oneAZ: vpcTopology.AvailabilityZoneDescription[] = [AZ1]; const twoAZs: vpcTopology.AvailabilityZoneDescription[] = [AZ1, AZ2]; const threeAZs: vpcTopology.AvailabilityZoneDescription[] = [AZ1, AZ2, AZ3]; const fourAZs: vpcTopology.AvailabilityZoneDescription[] = [AZ1, AZ2, AZ3, AZ4]; const fiveAZs: vpcTopology.AvailabilityZoneDescription[] = [AZ1, AZ2, AZ3, AZ5]; describe("cidr", () => { it("throws without /", () => { assert.throws(() => { Cidr32Block.fromCidrNotation("10.0.0.0"); }); }); it("throws without enough portions", () => { assert.throws(() => { Cidr32Block.fromCidrNotation("10.0.0/16"); }); }); it("throws with too many portions", () => { assert.throws(() => { Cidr32Block.fromCidrNotation("10.0.0.0.0/16"); }); }); it("throws with invalid octet", () => { assert.throws(() => { Cidr32Block.fromCidrNotation("10.0.0.256/16"); }); }); it("roundtrip", () => { assert.equal(Cidr32Block.fromCidrNotation("10.0.0.0/16").toString(), "10.0.0.0/16"); }); it("permutations", () => { // Try a lot of interesting permutations of values const values = [0, 1, 10, 127, 128, 200, 255]; for (const arr of permutation(values, 4).toArray()) { for (let i = 0; i <= 32; i++) { assert.doesNotThrow(() => { Cidr32Block.fromCidrNotation(`${arr.join(".")}/${i}`); }); } } }); describe("start/end", () => { it("0", () => { const cidr = Cidr32Block.fromCidrNotation("10.0.0.0/0"); assert.throws(() => cidr.nextBlock().toString()); }); it("1", () => { const cidr = Cidr32Block.fromCidrNotation("10.0.0.0/1"); assert.throws(() => cidr.nextBlock().toString()); }); it("4", () => { const cidr = Cidr32Block.fromCidrNotation("10.0.0.0/4"); assert.equal(cidr.nextBlock().toString(), "16.0.0.0/4"); }); it("5", () => { const cidr = Cidr32Block.fromCidrNotation("10.0.0.0/5"); assert.equal(cidr.nextBlock().toString(), "16.0.0.0/5"); }); it("6", () => { const cidr = Cidr32Block.fromCidrNotation("10.0.0.0/6"); assert.equal(cidr.nextBlock().toString(), "12.0.0.0/6"); }); it("8", () => { const cidr = Cidr32Block.fromCidrNotation("10.0.0.0/8"); assert.equal(cidr.nextBlock().toString(), "11.0.0.0/8"); }); it("12", () => { const cidr = Cidr32Block.fromCidrNotation("10.0.0.0/12"); assert.equal(cidr.nextBlock().toString(), "10.16.0.0/12"); }); it("16", () => { const cidr = Cidr32Block.fromCidrNotation("10.0.0.0/16"); assert.equal(cidr.nextBlock().toString(), "10.1.0.0/16"); }); it("20", () => { const cidr = Cidr32Block.fromCidrNotation("10.0.0.0/20"); assert.equal(cidr.nextBlock().toString(), "10.0.16.0/20"); }); it("21", () => { const cidr = Cidr32Block.fromCidrNotation("10.0.0.0/21"); assert.equal(cidr.nextBlock().toString(), "10.0.8.0/21"); }); it("30", () => { const cidr = Cidr32Block.fromCidrNotation("10.0.0.0/30"); assert.equal(cidr.nextBlock().toString(), "10.0.0.4/30"); }); it("31", () => { const cidr = Cidr32Block.fromCidrNotation("10.0.0.0/31"); assert.equal(cidr.nextBlock().toString(), "10.0.0.2/31"); }); it("32", () => { const cidr = Cidr32Block.fromCidrNotation("10.0.0.0/32"); assert.equal(cidr.nextBlock().toString(), "10.0.0.1/32"); }); }); }); describe("topology", () => { describe("default", () => { it("1 AZ", async () => { await subnetsEqual(subnets("10.0.0.0/16", oneAZ, [ { type: "public" }, { type: "private" }, ]), [ { "type": "public", "subnetName": "testing-public-0", args: { "availabilityZone": AZ1.name, "availabilityZoneId": AZ1.id, "cidrBlock": "10.0.0.0/17", mapPublicIpOnLaunch: true, assignIpv6AddressOnCreation: false, }, }, { "type": "private", "subnetName": "testing-private-0", args: { "availabilityZone": AZ1.name, "availabilityZoneId": AZ1.id, "cidrBlock": "10.0.128.0/17", mapPublicIpOnLaunch: false, assignIpv6AddressOnCreation: false, }, }, ]); }); it("2 AZs", async () => { await subnetsEqual(subnets("10.0.0.0/16", twoAZs, [ { type: "public" }, { type: "private" }, ]), [ { "type": "public", "subnetName": "testing-public-0", args: { "availabilityZone": AZ1.name, "availabilityZoneId": AZ1.id, "cidrBlock": "10.0.0.0/18", mapPublicIpOnLaunch: true, assignIpv6AddressOnCreation: false, }, }, { "type": "public", "subnetName": "testing-public-1", args: { "availabilityZone": AZ2.name, "availabilityZoneId": AZ2.id, "cidrBlock": "10.0.64.0/18", mapPublicIpOnLaunch: true, assignIpv6AddressOnCreation: false, }, }, { "type": "private", "subnetName": "testing-private-0", args: { "availabilityZone": AZ1.name, "availabilityZoneId": AZ1.id, "cidrBlock": "10.0.128.0/18", mapPublicIpOnLaunch: false, assignIpv6AddressOnCreation: false, }, }, { "type": "private", "subnetName": "testing-private-1", args: { "availabilityZone": AZ2.name, "availabilityZoneId": AZ2.id, "cidrBlock": "10.0.192.0/18", mapPublicIpOnLaunch: false, assignIpv6AddressOnCreation: false, }, }, ]); }); it("3 AZs", async () => { await subnetsEqual(subnets("10.0.0.0/16", threeAZs, [ { type: "public" }, { type: "private" }, ]), [ { "type": "public", "subnetName": "testing-public-0", args: { "availabilityZone": AZ1.name, "availabilityZoneId": AZ1.id, "cidrBlock": "10.0.0.0/19", mapPublicIpOnLaunch: true, assignIpv6AddressOnCreation: false, }, }, { "type": "public", "subnetName": "testing-public-1", args: { "availabilityZone": AZ2.name, "availabilityZoneId": AZ2.id, "cidrBlock": "10.0.32.0/19", mapPublicIpOnLaunch: true, assignIpv6AddressOnCreation: false, }, }, { "type": "public", "subnetName": "testing-public-2", args: { "availabilityZone": AZ3.name, "availabilityZoneId": AZ3.id, "cidrBlock": "10.0.64.0/19", mapPublicIpOnLaunch: true, assignIpv6AddressOnCreation: false, }, }, { "type": "private", "subnetName": "testing-private-0", args: { "availabilityZone": AZ1.name, "availabilityZoneId": AZ1.id, "cidrBlock": "10.0.96.0/19", mapPublicIpOnLaunch: false, assignIpv6AddressOnCreation: false, }, }, { "type": "private", "subnetName": "testing-private-1", args: { "availabilityZone": AZ2.name, "availabilityZoneId": AZ2.id, "cidrBlock": "10.0.128.0/19", mapPublicIpOnLaunch: false, assignIpv6AddressOnCreation: false, }, }, { "type": "private", "subnetName": "testing-private-2", args: { "availabilityZone": AZ3.name, "availabilityZoneId": AZ3.id, "cidrBlock": "10.0.160.0/19", mapPublicIpOnLaunch: false, assignIpv6AddressOnCreation: false, }, }, ]); }); }); describe("custom cidr", () => { it("custom 1", async () => { await subnetsEqual(subnets("10.10.0.0/16", twoAZs, [ { type: "public", cidrMask: 24 }, { type: "private", cidrMask: 28 }, ]), [ { "type": "public", "subnetName": "testing-public-0", args: { "availabilityZone": AZ1.name, "availabilityZoneId": AZ1.id, "cidrBlock": "10.10.0.0/24", mapPublicIpOnLaunch: true, assignIpv6AddressOnCreation: false, }, }, { "type": "public", "subnetName": "testing-public-1", args: { "availabilityZone": AZ2.name, "availabilityZoneId": AZ2.id, "cidrBlock": "10.10.1.0/24", mapPublicIpOnLaunch: true, assignIpv6AddressOnCreation: false, }, }, { "type": "private", "subnetName": "testing-private-0", args: { "availabilityZone": AZ1.name, "availabilityZoneId": AZ1.id, "cidrBlock": "10.10.2.0/28", mapPublicIpOnLaunch: false, assignIpv6AddressOnCreation: false, }, }, { "type": "private", "subnetName": "testing-private-1", args: { "availabilityZone": AZ2.name, "availabilityZoneId": AZ2.id, "cidrBlock": "10.10.2.16/28", mapPublicIpOnLaunch: false, assignIpv6AddressOnCreation: false, }, }, ]); }); it("custom 2", async () => { await subnetsEqual(subnets("10.10.0.0/16", twoAZs, [ { type: "public", cidrMask: 26 }, { type: "private" }, { type: "isolated", cidrMask: 28 }, ]), [ { "type": "public", "subnetName": "testing-public-0", args: { "availabilityZone": AZ1.name, "availabilityZoneId": AZ1.id, "cidrBlock": "10.10.0.0/26", mapPublicIpOnLaunch: true, assignIpv6AddressOnCreation: false, }, }, { "type": "public", "subnetName": "testing-public-1", args: { "availabilityZone": AZ2.name, "availabilityZoneId": AZ2.id, "cidrBlock": "10.10.0.64/26", mapPublicIpOnLaunch: true, assignIpv6AddressOnCreation: false, }, }, { "type": "isolated", "subnetName": "testing-isolated-0", args: { "availabilityZone": AZ1.name, "availabilityZoneId": AZ1.id, "cidrBlock": "10.10.0.128/28", mapPublicIpOnLaunch: false, assignIpv6AddressOnCreation: false, }, }, { "type": "isolated", "subnetName": "testing-isolated-1", args: { "availabilityZone": AZ2.name, "availabilityZoneId": AZ2.id, "cidrBlock": "10.10.0.144/28", mapPublicIpOnLaunch: false, assignIpv6AddressOnCreation: false, }, }, { "type": "private", "subnetName": "testing-private-0", args: { "availabilityZone": AZ1.name, "availabilityZoneId": AZ1.id, "cidrBlock": "10.10.0.160/18", mapPublicIpOnLaunch: false, assignIpv6AddressOnCreation: false, }, }, { "type": "private", "subnetName": "testing-private-1", args: { "availabilityZone": AZ2.name, "availabilityZoneId": AZ2.id, "cidrBlock": "10.10.64.160/18", mapPublicIpOnLaunch: false, assignIpv6AddressOnCreation: false, }, }, ]); }); it("custom 3", async () => { await subnetsEqual(subnets("10.10.0.0/16", twoAZs, [ { type: "public", cidrMask: 24 }, { type: "private", name: "private1" }, { type: "private", name: "private2" }, { type: "isolated", cidrMask: 24 }, ]), [ { "type": "public", "subnetName": "testing-public-0", args: { "availabilityZone": AZ1.name, "availabilityZoneId": AZ1.id, "cidrBlock": "10.10.0.0/24", mapPublicIpOnLaunch: true, assignIpv6AddressOnCreation: false, }, }, { "type": "public", "subnetName": "testing-public-1", args: { "availabilityZone": AZ2.name, "availabilityZoneId": AZ2.id, "cidrBlock": "10.10.1.0/24", mapPublicIpOnLaunch: true, assignIpv6AddressOnCreation: false, }, }, { "type": "isolated", "subnetName": "testing-isolated-0", args: { "availabilityZone": AZ1.name, "availabilityZoneId": AZ1.id, "cidrBlock": "10.10.2.0/24", mapPublicIpOnLaunch: false, assignIpv6AddressOnCreation: false, }, }, { "type": "isolated", "subnetName": "testing-isolated-1", args: { "availabilityZone": AZ2.name, "availabilityZoneId": AZ2.id, "cidrBlock": "10.10.3.0/24", mapPublicIpOnLaunch: false, assignIpv6AddressOnCreation: false, }, }, { "type": "private", "subnetName": "testing-private1-private-0", args: { "availabilityZone": AZ1.name, "availabilityZoneId": AZ1.id, "cidrBlock": "10.10.4.0/19", mapPublicIpOnLaunch: false, assignIpv6AddressOnCreation: false, }, }, { "type": "private", "subnetName": "testing-private1-private-1", args: { "availabilityZone": AZ2.name, "availabilityZoneId": AZ2.id, "cidrBlock": "10.10.36.0/19", mapPublicIpOnLaunch: false, assignIpv6AddressOnCreation: false, }, }, { "type": "private", "subnetName": "testing-private2-private-0", args: { "availabilityZone": AZ1.name, "availabilityZoneId": AZ1.id, "cidrBlock": "10.10.68.0/19", mapPublicIpOnLaunch: false, assignIpv6AddressOnCreation: false, }, }, { "type": "private", "subnetName": "testing-private2-private-1", args: { "availabilityZone": AZ2.name, "availabilityZoneId": AZ2.id, "cidrBlock": "10.10.100.0/19", mapPublicIpOnLaunch: false, assignIpv6AddressOnCreation: false, }, }, ]); }); }); describe("26 block", () => { // a 26 block can only fit four subnets since it only has 64 addresses available. it("1 AZ, 1 subnet", async () => { await subnetsEqual(subnets("10.0.0.0/26", oneAZ, [ { type: "private" }, ]), [ { "type": "private", "subnetName": "testing-private-0", args: { "availabilityZone": AZ1.name, "availabilityZoneId": AZ1.id, "cidrBlock": "10.0.0.0/26", mapPublicIpOnLaunch: false, assignIpv6AddressOnCreation: false, }, }, ]); }); it("1 AZ, 2 subnets", async () => { await subnetsEqual(subnets("10.0.0.0/26", oneAZ, [ { type: "public" }, { type: "private" }, ]), [ { "type": "public", "subnetName": "testing-public-0", args: { "availabilityZone": AZ1.name, "availabilityZoneId": AZ1.id, "cidrBlock": "10.0.0.0/27", mapPublicIpOnLaunch: true, assignIpv6AddressOnCreation: false, }, }, { "type": "private", "subnetName": "testing-private-0", args: { "availabilityZone": AZ1.name, "availabilityZoneId": AZ1.id, "cidrBlock": "10.0.0.32/27", mapPublicIpOnLaunch: false, assignIpv6AddressOnCreation: false, }, }, ]); }); it("2 AZs, 1 subnets", async () => { await subnetsEqual(subnets("10.0.0.0/26", twoAZs, [ { type: "private" }, ]), [ { "type": "private", "subnetName": "testing-private-0", args: { "availabilityZone": AZ1.name, "availabilityZoneId": AZ1.id, "cidrBlock": "10.0.0.0/27", mapPublicIpOnLaunch: false, assignIpv6AddressOnCreation: false, }, }, { "type": "private", "subnetName": "testing-private-1", args: { "availabilityZone": AZ2.name, "availabilityZoneId": AZ2.id, "cidrBlock": "10.0.0.32/27", mapPublicIpOnLaunch: false, assignIpv6AddressOnCreation: false, }, }, ]); }); it("2 AZs, 2 subnets", async () => { await subnetsEqual(subnets("10.0.0.0/26", twoAZs, [ { type: "public" }, { type: "private" }, ]), [ { "type": "public", "subnetName": "testing-public-0", args: { "availabilityZone": AZ1.name, "availabilityZoneId": AZ1.id, "cidrBlock": "10.0.0.0/28", mapPublicIpOnLaunch: true, assignIpv6AddressOnCreation: false, }, }, { "type": "public", "subnetName": "testing-public-1", args: { "availabilityZone": AZ2.name, "availabilityZoneId": AZ2.id, "cidrBlock": "10.0.0.16/28", mapPublicIpOnLaunch: true, assignIpv6AddressOnCreation: false, }, }, { "type": "private", "subnetName": "testing-private-0", args: { "availabilityZone": AZ1.name, "availabilityZoneId": AZ1.id, "cidrBlock": "10.0.0.32/28", mapPublicIpOnLaunch: false, assignIpv6AddressOnCreation: false, }, }, { "type": "private", "subnetName": "testing-private-1", args: { "availabilityZone": AZ2.name, "availabilityZoneId": AZ2.id, "cidrBlock": "10.0.0.48/28", mapPublicIpOnLaunch: false, assignIpv6AddressOnCreation: false, }, }, ]); }); it("2 AZs, 3 subnets", () => { assert.throws(() => subnets("10.0.0.0/26", twoAZs, [ { type: "public" }, { type: "private" }, { type: "isolated" }, ])); }); }); describe("27 block", () => { // a 27 block can only fit two subnets since it only has 32 addresses available. it("1 AZ, 1 subnet", async () => { await subnetsEqual(subnets("10.0.0.0/27", oneAZ, [ { type: "private" }, ]), [ { "type": "private", "subnetName": "testing-private-0", args: { "availabilityZone": AZ1.name, "availabilityZoneId": AZ1.id, "cidrBlock": "10.0.0.0/27", mapPublicIpOnLaunch: false, assignIpv6AddressOnCreation: false, }, }, ]); }); it("1 AZ, 2 subnets", async () => { await subnetsEqual(subnets("10.0.0.0/27", oneAZ, [ { type: "public" }, { type: "private" }, ]), [ { "type": "public", "subnetName": "testing-public-0", args: { "availabilityZone": AZ1.name, "availabilityZoneId": AZ1.id, "cidrBlock": "10.0.0.0/28", mapPublicIpOnLaunch: true, assignIpv6AddressOnCreation: false, }, }, { "type": "private", "subnetName": "testing-private-0", args: { "availabilityZone": AZ1.name, "availabilityZoneId": AZ1.id, "cidrBlock": "10.0.0.16/28", mapPublicIpOnLaunch: false, assignIpv6AddressOnCreation: false, }, }, ]); }); it("2 AZs, 1 subnets", async () => { await subnetsEqual(subnets("10.0.0.0/27", twoAZs, [ { type: "private" }, ]), [ { "type": "private", "subnetName": "testing-private-0", args: { "availabilityZone": AZ1.name, "availabilityZoneId": AZ1.id, "cidrBlock": "10.0.0.0/28", mapPublicIpOnLaunch: false, assignIpv6AddressOnCreation: false, }, }, { "type": "private", "subnetName": "testing-private-1", args: { "availabilityZone": AZ2.name, "availabilityZoneId": AZ2.id, "cidrBlock": "10.0.0.16/28", mapPublicIpOnLaunch: false, assignIpv6AddressOnCreation: false, }, }, ]); }); it("2 AZs, 2 subnets", () => { assert.throws(() => subnets("10.0.0.0/27", twoAZs, [ { type: "public" }, { type: "private" }, ])); }); }); describe("28 block", () => { // a 28 block can only fit a single subnet since it only has 16 addresses available. it("1 AZ, 1 subnet", async () => { await subnetsEqual(subnets("10.0.0.0/28", oneAZ, [ { type: "private" }, ]), [ { "type": "private", "subnetName": "testing-private-0", args: { "availabilityZone": AZ1.name, "availabilityZoneId": AZ1.id, "cidrBlock": "10.0.0.0/28", mapPublicIpOnLaunch: false, assignIpv6AddressOnCreation: false, }, }, ]); }); it("1 AZ, 2 subnets", () => { assert.throws(() => subnets("10.0.0.0/28", oneAZ, [ { type: "public" }, { type: "private" }, ])); }); it("2 AZs, 1 subnets", () => { assert.throws(() => subnets("10.0.0.0/28", twoAZs, [ { type: "private" }, ])); }); it("2 AZs, 2 subnets", () => { assert.throws(() => subnets("10.0.0.0/28", twoAZs, [ { type: "public" }, { type: "private" }, ])); }); }); describe("custom locations", () => { it("custom one azs", async () => { await jsonEqual(topology("10.0.0.0/16", oneAZ, 1, [ { type: "public", location: "10.0.0.0/24" }, { type: "private", location: "10.0.1.0/24" }, { type: "isolated", name: "db", location: "10.0.2.0/24" }, { type: "isolated", name: "redis", location: "10.0.3.0/24" }, ]), { "subnets": [ { "subnetName": "public-0", "type": "public", "args": { "cidrBlock": "10.0.0.0/24", "mapPublicIpOnLaunch": true, "assignIpv6AddressOnCreation": false, }, }, { "subnetName": "private-1", "type": "private", "args": { "cidrBlock": "10.0.1.0/24", "mapPublicIpOnLaunch": false, "assignIpv6AddressOnCreation": false, }, }, { "subnetName": "db", "type": "isolated", "args": { "cidrBlock": "10.0.2.0/24", "mapPublicIpOnLaunch": false, "assignIpv6AddressOnCreation": false, }, }, { "subnetName": "redis", "type": "isolated", "args": { "cidrBlock": "10.0.3.0/24", "mapPublicIpOnLaunch": false, "assignIpv6AddressOnCreation": false, }, }, ], "natGateways": [ { "name": "testing-0", "publicSubnet": "public-0", }, ], "natRoutes": [ { "name": "nat-0", "privateSubnet": "private-1", "natGateway": "testing-0", }, ], }); }); it("custom two private one public", async () => { await jsonEqual(topology("10.0.0.0/16", twoAZs, 2, [ { type: "public", location: "10.0.0.0/24" }, { type: "private", location: { cidrBlock: "10.0.1.0/24", availabilityZone: AZ1.name } }, { type: "private", location: { cidrBlock: "10.0.2.0/24", availabilityZone: AZ2.name } }, ]), { "subnets": [ { "subnetName": "public-0", "type": "public", "args": { "cidrBlock": "10.0.0.0/24", "mapPublicIpOnLaunch": true, "assignIpv6AddressOnCreation": false, }, }, { "subnetName": "private-1", "type": "private", "args": { "cidrBlock": "10.0.1.0/24", "availabilityZone": "name_a", "mapPublicIpOnLaunch": false, "assignIpv6AddressOnCreation": false, }, }, { "subnetName": "private-2", "type": "private", "args": { "cidrBlock": "10.0.2.0/24", "availabilityZone": "name_b", "mapPublicIpOnLaunch": false, "assignIpv6AddressOnCreation": false, }, }, ], "natGateways": [ { "name": "testing-0", "publicSubnet": "public-0", }, ], "natRoutes": [ { "name": "nat-0", "privateSubnet": "private-1", "natGateway": "testing-0", }, { "name": "nat-1", "privateSubnet": "private-2", "natGateway": "testing-0", }, ], }); }); it("custom two private two public", async () => { await jsonEqual(topology("10.0.0.0/16", twoAZs, 2, [ { type: "public", location: { cidrBlock: "10.0.1.0/24", availabilityZone: AZ1.name } }, { type: "public", location: { cidrBlock: "10.0.2.0/24", availabilityZone: AZ2.name } }, { type: "private", location: { cidrBlock: "10.0.3.0/24", availabilityZone: AZ1.name } }, { type: "private", location: { cidrBlock: "10.0.4.0/24", availabilityZone: AZ2.name } }, ]), { "subnets": [ { "subnetName": "public-0", "type": "public", "args": { "cidrBlock": "10.0.1.0/24", "availabilityZone": "name_a", "mapPublicIpOnLaunch": true, "assignIpv6AddressOnCreation": false, }, }, { "subnetName": "public-1", "type": "public", "args": { "cidrBlock": "10.0.2.0/24", "availabilityZone": "name_b", "mapPublicIpOnLaunch": true, "assignIpv6AddressOnCreation": false, }, }, { "subnetName": "private-2", "type": "private", "args": { "cidrBlock": "10.0.3.0/24", "availabilityZone": "name_a", "mapPublicIpOnLaunch": false, "assignIpv6AddressOnCreation": false, }, }, { "subnetName": "private-3", "type": "private", "args": { "cidrBlock": "10.0.4.0/24", "availabilityZone": "name_b", "mapPublicIpOnLaunch": false, "assignIpv6AddressOnCreation": false, }, }, ], "natGateways": [ { "name": "testing-0", "publicSubnet": "public-0", }, { "name": "testing-1", "publicSubnet": "public-1", }, ], "natRoutes": [ { "name": "nat-0", "privateSubnet": "private-2", "natGateway": "testing-0", }, { "name": "nat-1", "privateSubnet": "private-3", "natGateway": "testing-1", }, ], }); }); it("custom two private three public", async () => { await jsonEqual(topology("10.0.0.0/16", fiveAZs, 5, [ { type: "public", location: { cidrBlock: "10.0.1.0/24", availabilityZone: AZ1.name } }, { type: "public", location: { cidrBlock: "10.0.2.0/24", availabilityZone: AZ2.name } }, // first private subnet should get natgateway from second public subnet (since it's // in the same AZ). Remaining private subnets should round-robin between the two // natgateways we make. { type: "private", location: { cidrBlock: "10.0.3.0/24", availabilityZone: AZ2.name } }, { type: "private", location: { cidrBlock: "10.0.4.0/24", availabilityZone: AZ3.name } }, { type: "private", location: { cidrBlock: "10.0.5.0/24", availabilityZone: AZ4.name } }, { type: "private", location: { cidrBlock: "10.0.6.0/24", availabilityZone: AZ5.name } }, ]), { "subnets": [ { "subnetName": "public-0", "type": "public", "args": { "cidrBlock": "10.0.1.0/24", "availabilityZone": "name_a", "mapPublicIpOnLaunch": true, "assignIpv6AddressOnCreation": false, }, }, { "subnetName": "public-1", "type": "public", "args": { "cidrBlock": "10.0.2.0/24", "availabilityZone": "name_b", "mapPublicIpOnLaunch": true, "assignIpv6AddressOnCreation": false, }, }, { "subnetName": "private-2", "type": "private", "args": { "cidrBlock": "10.0.3.0/24", "availabilityZone": "name_b", "mapPublicIpOnLaunch": false, "assignIpv6AddressOnCreation": false, }, }, { "subnetName": "private-3", "type": "private", "args": { "cidrBlock": "10.0.4.0/24", "availabilityZone": "name_c", "mapPublicIpOnLaunch": false, "assignIpv6AddressOnCreation": false, }, }, { "subnetName": "private-4", "type": "private", "args": { "cidrBlock": "10.0.5.0/24", "availabilityZone": "name_d", "mapPublicIpOnLaunch": false, "assignIpv6AddressOnCreation": false, }, }, { "subnetName": "private-5", "type": "private", "args": { "cidrBlock": "10.0.6.0/24", "availabilityZone": "name_e", "mapPublicIpOnLaunch": false, "assignIpv6AddressOnCreation": false, }, }, ], "natGateways": [ { "name": "testing-0", "publicSubnet": "public-1", }, { "name": "testing-1", "publicSubnet": "public-0", }, ], "natRoutes": [ { "name": "nat-0", "privateSubnet": "private-2", "natGateway": "testing-0", }, { "name": "nat-1", "privateSubnet": "private-3", "natGateway": "testing-1", }, { "name": "nat-2", "privateSubnet": "private-4", "natGateway": "testing-0", }, { "name": "nat-3", "privateSubnet": "private-5", "natGateway": "testing-1", }, ], }); }); }); describe("no locations", () => { it("less nat gateways", async () => { await jsonEqual(topology("10.0.0.0/16", threeAZs, 1, [ { type: "public" }, { type: "private" }, ]), { "subnets": [{ "type": "public", "subnetName": "testing-public-0", "args": { "availabilityZone": "name_a", "availabilityZoneId": "id_a", "cidrBlock": "10.0.0.0/19", "mapPublicIpOnLaunch": true, "assignIpv6AddressOnCreation": false, }, }, { "type": "public", "subnetName": "testing-public-1", "args": { "availabilityZone": "name_b", "availabilityZoneId": "id_b", "cidrBlock": "10.0.32.0/19", "mapPublicIpOnLaunch": true, "assignIpv6AddressOnCreation": false, }, }, { "type": "public", "subnetName": "testing-public-2", "args": { "availabilityZone": "name_c", "availabilityZoneId": "id_c", "cidrBlock": "10.0.64.0/19", "mapPublicIpOnLaunch": true, "assignIpv6AddressOnCreation": false, }, }, { "type": "private", "subnetName": "testing-private-0", "args": { "availabilityZone": "name_a", "availabilityZoneId": "id_a", "cidrBlock": "10.0.96.0/19", "mapPublicIpOnLaunch": false, "assignIpv6AddressOnCreation": false, }, }, { "type": "private", "subnetName": "testing-private-1", "args": { "availabilityZone": "name_b", "availabilityZoneId": "id_b", "cidrBlock": "10.0.128.0/19", "mapPublicIpOnLaunch": false, "assignIpv6AddressOnCreation": false, }, }, { "type": "private", "subnetName": "testing-private-2", "args": { "availabilityZone": "name_c", "availabilityZoneId": "id_c", "cidrBlock": "10.0.160.0/19", "mapPublicIpOnLaunch": false, "assignIpv6AddressOnCreation": false, }, }], "natGateways": [{ "name": "testing-0", "publicSubnet": "testing-public-0", }], "natRoutes": [{ "name": "nat-0", "privateSubnet": "testing-private-0", "natGateway": "testing-0", }, { "name": "nat-1", "privateSubnet": "testing-private-1", "natGateway": "testing-0", }, { "name": "nat-2", "privateSubnet": "testing-private-2", "natGateway": "testing-0", }], }); }); }); });
the_stack
import { gql } from '@apollo/client'; import * as Apollo from '@apollo/client'; export type Maybe<T> = T | null; export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] }; export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> }; export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> }; /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { ID: string; String: string; Boolean: boolean; Int: number; Float: number; /** A date string, such as 2007-12-03 (YYYY-MM-DD), compliant with ISO 8601 standard for representation of dates using the Gregorian calendar. */ Date: any; /** A date-time string at UTC, such as 2007-12-03T10:15:30Z, compliant with the date-timeformat outlined in section 5.6 of the RFC 3339 profile of the ISO 8601 standard for representationof dates and times using the Gregorian calendar. */ DateTime: any; Hex: any; /** Raw JSON value */ Json: any; /** The Long scalar type represents non-fractional signed whole numeric values. Long can represent values between -(2^63) and 2^63 - 1. */ Long: any; RGBAHue: any; RGBATransparency: any; /** Slate-compatible RichText AST */ RichTextAST: any; }; export type Aggregate = { __typename?: 'Aggregate'; count: Scalars['Int']; }; /** Asset system model */ export type Asset = Node & { __typename?: 'Asset'; /** System stage field */ stage: Stage; /** System Locale field */ locale: Locale; /** Get the other localizations for this document */ localizations: Array<Asset>; /** Get the document in other stages */ documentInStages: Array<Asset>; /** The unique identifier */ id: Scalars['ID']; /** The time the document was created */ createdAt: Scalars['DateTime']; /** The time the document was updated */ updatedAt: Scalars['DateTime']; /** The time the document was published. Null on documents in draft stage. */ publishedAt?: Maybe<Scalars['DateTime']>; /** The file handle */ handle: Scalars['String']; /** The file name */ fileName: Scalars['String']; /** The height of the file */ height?: Maybe<Scalars['Float']>; /** The file width */ width?: Maybe<Scalars['Float']>; /** The file size */ size?: Maybe<Scalars['Float']>; /** The mime type of the file */ mimeType?: Maybe<Scalars['String']>; productImage: Array<Product>; /** List of Asset versions */ history: Array<Version>; /** Get the url for the asset with provided transformations applied. */ url: Scalars['String']; }; /** Asset system model */ export type AssetLocalizationsArgs = { locales?: Array<Locale>; includeCurrent?: Scalars['Boolean']; }; /** Asset system model */ export type AssetDocumentInStagesArgs = { stages?: Array<Stage>; includeCurrent?: Scalars['Boolean']; inheritLocale?: Scalars['Boolean']; }; /** Asset system model */ export type AssetCreatedAtArgs = { variation?: SystemDateTimeFieldVariation; }; /** Asset system model */ export type AssetUpdatedAtArgs = { variation?: SystemDateTimeFieldVariation; }; /** Asset system model */ export type AssetPublishedAtArgs = { variation?: SystemDateTimeFieldVariation; }; /** Asset system model */ export type AssetProductImageArgs = { where?: Maybe<ProductWhereInput>; orderBy?: Maybe<ProductOrderByInput>; skip?: Maybe<Scalars['Int']>; after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; locales?: Maybe<Array<Locale>>; }; /** Asset system model */ export type AssetHistoryArgs = { limit?: Scalars['Int']; skip?: Scalars['Int']; stageOverride?: Maybe<Stage>; }; /** Asset system model */ export type AssetUrlArgs = { transformation?: Maybe<AssetTransformationInput>; }; export type AssetConnectInput = { /** Document to connect */ where: AssetWhereUniqueInput; /** Allow to specify document position in list of connected documents, will default to appending at end of list */ position?: Maybe<ConnectPositionInput>; }; /** A connection to a list of items. */ export type AssetConnection = { __typename?: 'AssetConnection'; /** Information to aid in pagination. */ pageInfo: PageInfo; /** A list of edges. */ edges: Array<AssetEdge>; aggregate: Aggregate; }; export type AssetCreateInput = { createdAt?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; handle: Scalars['String']; fileName: Scalars['String']; height?: Maybe<Scalars['Float']>; width?: Maybe<Scalars['Float']>; size?: Maybe<Scalars['Float']>; mimeType?: Maybe<Scalars['String']>; productImage?: Maybe<ProductCreateManyInlineInput>; /** Inline mutations for managing document localizations excluding the default locale */ localizations?: Maybe<AssetCreateLocalizationsInput>; }; export type AssetCreateLocalizationDataInput = { createdAt?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; handle: Scalars['String']; fileName: Scalars['String']; height?: Maybe<Scalars['Float']>; width?: Maybe<Scalars['Float']>; size?: Maybe<Scalars['Float']>; mimeType?: Maybe<Scalars['String']>; }; export type AssetCreateLocalizationInput = { /** Localization input */ data: AssetCreateLocalizationDataInput; locale: Locale; }; export type AssetCreateLocalizationsInput = { /** Create localizations for the newly-created document */ create?: Maybe<Array<AssetCreateLocalizationInput>>; }; export type AssetCreateManyInlineInput = { /** Create and connect multiple existing Asset documents */ create?: Maybe<Array<AssetCreateInput>>; /** Connect multiple existing Asset documents */ connect?: Maybe<Array<AssetWhereUniqueInput>>; }; export type AssetCreateOneInlineInput = { /** Create and connect one Asset document */ create?: Maybe<AssetCreateInput>; /** Connect one existing Asset document */ connect?: Maybe<AssetWhereUniqueInput>; }; /** An edge in a connection. */ export type AssetEdge = { __typename?: 'AssetEdge'; /** The item at the end of the edge. */ node: Asset; /** A cursor for use in pagination. */ cursor: Scalars['String']; }; /** Identifies documents */ export type AssetManyWhereInput = { /** Contains search across all appropriate fields. */ _search?: Maybe<Scalars['String']>; /** Logical AND on all given filters. */ AND?: Maybe<Array<AssetWhereInput>>; /** Logical OR on all given filters. */ OR?: Maybe<Array<AssetWhereInput>>; /** Logical NOT on all given filters combined by AND. */ NOT?: Maybe<Array<AssetWhereInput>>; id?: Maybe<Scalars['ID']>; /** All values that are not equal to given value. */ id_not?: Maybe<Scalars['ID']>; /** All values that are contained in given list. */ id_in?: Maybe<Array<Scalars['ID']>>; /** All values that are not contained in given list. */ id_not_in?: Maybe<Array<Scalars['ID']>>; /** All values containing the given string. */ id_contains?: Maybe<Scalars['ID']>; /** All values not containing the given string. */ id_not_contains?: Maybe<Scalars['ID']>; /** All values starting with the given string. */ id_starts_with?: Maybe<Scalars['ID']>; /** All values not starting with the given string. */ id_not_starts_with?: Maybe<Scalars['ID']>; /** All values ending with the given string. */ id_ends_with?: Maybe<Scalars['ID']>; /** All values not ending with the given string */ id_not_ends_with?: Maybe<Scalars['ID']>; createdAt?: Maybe<Scalars['DateTime']>; /** All values that are not equal to given value. */ createdAt_not?: Maybe<Scalars['DateTime']>; /** All values that are contained in given list. */ createdAt_in?: Maybe<Array<Scalars['DateTime']>>; /** All values that are not contained in given list. */ createdAt_not_in?: Maybe<Array<Scalars['DateTime']>>; /** All values less than the given value. */ createdAt_lt?: Maybe<Scalars['DateTime']>; /** All values less than or equal the given value. */ createdAt_lte?: Maybe<Scalars['DateTime']>; /** All values greater than the given value. */ createdAt_gt?: Maybe<Scalars['DateTime']>; /** All values greater than or equal the given value. */ createdAt_gte?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; /** All values that are not equal to given value. */ updatedAt_not?: Maybe<Scalars['DateTime']>; /** All values that are contained in given list. */ updatedAt_in?: Maybe<Array<Scalars['DateTime']>>; /** All values that are not contained in given list. */ updatedAt_not_in?: Maybe<Array<Scalars['DateTime']>>; /** All values less than the given value. */ updatedAt_lt?: Maybe<Scalars['DateTime']>; /** All values less than or equal the given value. */ updatedAt_lte?: Maybe<Scalars['DateTime']>; /** All values greater than the given value. */ updatedAt_gt?: Maybe<Scalars['DateTime']>; /** All values greater than or equal the given value. */ updatedAt_gte?: Maybe<Scalars['DateTime']>; publishedAt?: Maybe<Scalars['DateTime']>; /** All values that are not equal to given value. */ publishedAt_not?: Maybe<Scalars['DateTime']>; /** All values that are contained in given list. */ publishedAt_in?: Maybe<Array<Scalars['DateTime']>>; /** All values that are not contained in given list. */ publishedAt_not_in?: Maybe<Array<Scalars['DateTime']>>; /** All values less than the given value. */ publishedAt_lt?: Maybe<Scalars['DateTime']>; /** All values less than or equal the given value. */ publishedAt_lte?: Maybe<Scalars['DateTime']>; /** All values greater than the given value. */ publishedAt_gt?: Maybe<Scalars['DateTime']>; /** All values greater than or equal the given value. */ publishedAt_gte?: Maybe<Scalars['DateTime']>; productImage_every?: Maybe<ProductWhereInput>; productImage_some?: Maybe<ProductWhereInput>; productImage_none?: Maybe<ProductWhereInput>; }; export enum AssetOrderByInput { IdAsc = 'id_ASC', IdDesc = 'id_DESC', CreatedAtAsc = 'createdAt_ASC', CreatedAtDesc = 'createdAt_DESC', UpdatedAtAsc = 'updatedAt_ASC', UpdatedAtDesc = 'updatedAt_DESC', PublishedAtAsc = 'publishedAt_ASC', PublishedAtDesc = 'publishedAt_DESC', HandleAsc = 'handle_ASC', HandleDesc = 'handle_DESC', FileNameAsc = 'fileName_ASC', FileNameDesc = 'fileName_DESC', HeightAsc = 'height_ASC', HeightDesc = 'height_DESC', WidthAsc = 'width_ASC', WidthDesc = 'width_DESC', SizeAsc = 'size_ASC', SizeDesc = 'size_DESC', MimeTypeAsc = 'mimeType_ASC', MimeTypeDesc = 'mimeType_DESC' } /** Transformations for Assets */ export type AssetTransformationInput = { image?: Maybe<ImageTransformationInput>; document?: Maybe<DocumentTransformationInput>; /** Pass true if you want to validate the passed transformation parameters */ validateOptions?: Maybe<Scalars['Boolean']>; }; export type AssetUpdateInput = { handle?: Maybe<Scalars['String']>; fileName?: Maybe<Scalars['String']>; height?: Maybe<Scalars['Float']>; width?: Maybe<Scalars['Float']>; size?: Maybe<Scalars['Float']>; mimeType?: Maybe<Scalars['String']>; productImage?: Maybe<ProductUpdateManyInlineInput>; /** Manage document localizations */ localizations?: Maybe<AssetUpdateLocalizationsInput>; }; export type AssetUpdateLocalizationDataInput = { handle?: Maybe<Scalars['String']>; fileName?: Maybe<Scalars['String']>; height?: Maybe<Scalars['Float']>; width?: Maybe<Scalars['Float']>; size?: Maybe<Scalars['Float']>; mimeType?: Maybe<Scalars['String']>; }; export type AssetUpdateLocalizationInput = { data: AssetUpdateLocalizationDataInput; locale: Locale; }; export type AssetUpdateLocalizationsInput = { /** Localizations to create */ create?: Maybe<Array<AssetCreateLocalizationInput>>; /** Localizations to update */ update?: Maybe<Array<AssetUpdateLocalizationInput>>; upsert?: Maybe<Array<AssetUpsertLocalizationInput>>; /** Localizations to delete */ delete?: Maybe<Array<Locale>>; }; export type AssetUpdateManyInlineInput = { /** Create and connect multiple Asset documents */ create?: Maybe<Array<AssetCreateInput>>; /** Connect multiple existing Asset documents */ connect?: Maybe<Array<AssetConnectInput>>; /** Override currently-connected documents with multiple existing Asset documents */ set?: Maybe<Array<AssetWhereUniqueInput>>; /** Update multiple Asset documents */ update?: Maybe<Array<AssetUpdateWithNestedWhereUniqueInput>>; /** Upsert multiple Asset documents */ upsert?: Maybe<Array<AssetUpsertWithNestedWhereUniqueInput>>; /** Disconnect multiple Asset documents */ disconnect?: Maybe<Array<AssetWhereUniqueInput>>; /** Delete multiple Asset documents */ delete?: Maybe<Array<AssetWhereUniqueInput>>; }; export type AssetUpdateManyInput = { fileName?: Maybe<Scalars['String']>; height?: Maybe<Scalars['Float']>; width?: Maybe<Scalars['Float']>; size?: Maybe<Scalars['Float']>; mimeType?: Maybe<Scalars['String']>; /** Optional updates to localizations */ localizations?: Maybe<AssetUpdateManyLocalizationsInput>; }; export type AssetUpdateManyLocalizationDataInput = { fileName?: Maybe<Scalars['String']>; height?: Maybe<Scalars['Float']>; width?: Maybe<Scalars['Float']>; size?: Maybe<Scalars['Float']>; mimeType?: Maybe<Scalars['String']>; }; export type AssetUpdateManyLocalizationInput = { data: AssetUpdateManyLocalizationDataInput; locale: Locale; }; export type AssetUpdateManyLocalizationsInput = { /** Localizations to update */ update?: Maybe<Array<AssetUpdateManyLocalizationInput>>; }; export type AssetUpdateManyWithNestedWhereInput = { /** Document search */ where: AssetWhereInput; /** Update many input */ data: AssetUpdateManyInput; }; export type AssetUpdateOneInlineInput = { /** Create and connect one Asset document */ create?: Maybe<AssetCreateInput>; /** Update single Asset document */ update?: Maybe<AssetUpdateWithNestedWhereUniqueInput>; /** Upsert single Asset document */ upsert?: Maybe<AssetUpsertWithNestedWhereUniqueInput>; /** Connect existing Asset document */ connect?: Maybe<AssetWhereUniqueInput>; /** Disconnect currently connected Asset document */ disconnect?: Maybe<Scalars['Boolean']>; /** Delete currently connected Asset document */ delete?: Maybe<Scalars['Boolean']>; }; export type AssetUpdateWithNestedWhereUniqueInput = { /** Unique document search */ where: AssetWhereUniqueInput; /** Document to update */ data: AssetUpdateInput; }; export type AssetUpsertInput = { /** Create document if it didn't exist */ create: AssetCreateInput; /** Update document if it exists */ update: AssetUpdateInput; }; export type AssetUpsertLocalizationInput = { update: AssetUpdateLocalizationDataInput; create: AssetCreateLocalizationDataInput; locale: Locale; }; export type AssetUpsertWithNestedWhereUniqueInput = { /** Unique document search */ where: AssetWhereUniqueInput; /** Upsert data */ data: AssetUpsertInput; }; /** Identifies documents */ export type AssetWhereInput = { /** Contains search across all appropriate fields. */ _search?: Maybe<Scalars['String']>; /** Logical AND on all given filters. */ AND?: Maybe<Array<AssetWhereInput>>; /** Logical OR on all given filters. */ OR?: Maybe<Array<AssetWhereInput>>; /** Logical NOT on all given filters combined by AND. */ NOT?: Maybe<Array<AssetWhereInput>>; id?: Maybe<Scalars['ID']>; /** All values that are not equal to given value. */ id_not?: Maybe<Scalars['ID']>; /** All values that are contained in given list. */ id_in?: Maybe<Array<Scalars['ID']>>; /** All values that are not contained in given list. */ id_not_in?: Maybe<Array<Scalars['ID']>>; /** All values containing the given string. */ id_contains?: Maybe<Scalars['ID']>; /** All values not containing the given string. */ id_not_contains?: Maybe<Scalars['ID']>; /** All values starting with the given string. */ id_starts_with?: Maybe<Scalars['ID']>; /** All values not starting with the given string. */ id_not_starts_with?: Maybe<Scalars['ID']>; /** All values ending with the given string. */ id_ends_with?: Maybe<Scalars['ID']>; /** All values not ending with the given string */ id_not_ends_with?: Maybe<Scalars['ID']>; createdAt?: Maybe<Scalars['DateTime']>; /** All values that are not equal to given value. */ createdAt_not?: Maybe<Scalars['DateTime']>; /** All values that are contained in given list. */ createdAt_in?: Maybe<Array<Scalars['DateTime']>>; /** All values that are not contained in given list. */ createdAt_not_in?: Maybe<Array<Scalars['DateTime']>>; /** All values less than the given value. */ createdAt_lt?: Maybe<Scalars['DateTime']>; /** All values less than or equal the given value. */ createdAt_lte?: Maybe<Scalars['DateTime']>; /** All values greater than the given value. */ createdAt_gt?: Maybe<Scalars['DateTime']>; /** All values greater than or equal the given value. */ createdAt_gte?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; /** All values that are not equal to given value. */ updatedAt_not?: Maybe<Scalars['DateTime']>; /** All values that are contained in given list. */ updatedAt_in?: Maybe<Array<Scalars['DateTime']>>; /** All values that are not contained in given list. */ updatedAt_not_in?: Maybe<Array<Scalars['DateTime']>>; /** All values less than the given value. */ updatedAt_lt?: Maybe<Scalars['DateTime']>; /** All values less than or equal the given value. */ updatedAt_lte?: Maybe<Scalars['DateTime']>; /** All values greater than the given value. */ updatedAt_gt?: Maybe<Scalars['DateTime']>; /** All values greater than or equal the given value. */ updatedAt_gte?: Maybe<Scalars['DateTime']>; publishedAt?: Maybe<Scalars['DateTime']>; /** All values that are not equal to given value. */ publishedAt_not?: Maybe<Scalars['DateTime']>; /** All values that are contained in given list. */ publishedAt_in?: Maybe<Array<Scalars['DateTime']>>; /** All values that are not contained in given list. */ publishedAt_not_in?: Maybe<Array<Scalars['DateTime']>>; /** All values less than the given value. */ publishedAt_lt?: Maybe<Scalars['DateTime']>; /** All values less than or equal the given value. */ publishedAt_lte?: Maybe<Scalars['DateTime']>; /** All values greater than the given value. */ publishedAt_gt?: Maybe<Scalars['DateTime']>; /** All values greater than or equal the given value. */ publishedAt_gte?: Maybe<Scalars['DateTime']>; handle?: Maybe<Scalars['String']>; /** All values that are not equal to given value. */ handle_not?: Maybe<Scalars['String']>; /** All values that are contained in given list. */ handle_in?: Maybe<Array<Scalars['String']>>; /** All values that are not contained in given list. */ handle_not_in?: Maybe<Array<Scalars['String']>>; /** All values containing the given string. */ handle_contains?: Maybe<Scalars['String']>; /** All values not containing the given string. */ handle_not_contains?: Maybe<Scalars['String']>; /** All values starting with the given string. */ handle_starts_with?: Maybe<Scalars['String']>; /** All values not starting with the given string. */ handle_not_starts_with?: Maybe<Scalars['String']>; /** All values ending with the given string. */ handle_ends_with?: Maybe<Scalars['String']>; /** All values not ending with the given string */ handle_not_ends_with?: Maybe<Scalars['String']>; fileName?: Maybe<Scalars['String']>; /** All values that are not equal to given value. */ fileName_not?: Maybe<Scalars['String']>; /** All values that are contained in given list. */ fileName_in?: Maybe<Array<Scalars['String']>>; /** All values that are not contained in given list. */ fileName_not_in?: Maybe<Array<Scalars['String']>>; /** All values containing the given string. */ fileName_contains?: Maybe<Scalars['String']>; /** All values not containing the given string. */ fileName_not_contains?: Maybe<Scalars['String']>; /** All values starting with the given string. */ fileName_starts_with?: Maybe<Scalars['String']>; /** All values not starting with the given string. */ fileName_not_starts_with?: Maybe<Scalars['String']>; /** All values ending with the given string. */ fileName_ends_with?: Maybe<Scalars['String']>; /** All values not ending with the given string */ fileName_not_ends_with?: Maybe<Scalars['String']>; height?: Maybe<Scalars['Float']>; /** All values that are not equal to given value. */ height_not?: Maybe<Scalars['Float']>; /** All values that are contained in given list. */ height_in?: Maybe<Array<Scalars['Float']>>; /** All values that are not contained in given list. */ height_not_in?: Maybe<Array<Scalars['Float']>>; /** All values less than the given value. */ height_lt?: Maybe<Scalars['Float']>; /** All values less than or equal the given value. */ height_lte?: Maybe<Scalars['Float']>; /** All values greater than the given value. */ height_gt?: Maybe<Scalars['Float']>; /** All values greater than or equal the given value. */ height_gte?: Maybe<Scalars['Float']>; width?: Maybe<Scalars['Float']>; /** All values that are not equal to given value. */ width_not?: Maybe<Scalars['Float']>; /** All values that are contained in given list. */ width_in?: Maybe<Array<Scalars['Float']>>; /** All values that are not contained in given list. */ width_not_in?: Maybe<Array<Scalars['Float']>>; /** All values less than the given value. */ width_lt?: Maybe<Scalars['Float']>; /** All values less than or equal the given value. */ width_lte?: Maybe<Scalars['Float']>; /** All values greater than the given value. */ width_gt?: Maybe<Scalars['Float']>; /** All values greater than or equal the given value. */ width_gte?: Maybe<Scalars['Float']>; size?: Maybe<Scalars['Float']>; /** All values that are not equal to given value. */ size_not?: Maybe<Scalars['Float']>; /** All values that are contained in given list. */ size_in?: Maybe<Array<Scalars['Float']>>; /** All values that are not contained in given list. */ size_not_in?: Maybe<Array<Scalars['Float']>>; /** All values less than the given value. */ size_lt?: Maybe<Scalars['Float']>; /** All values less than or equal the given value. */ size_lte?: Maybe<Scalars['Float']>; /** All values greater than the given value. */ size_gt?: Maybe<Scalars['Float']>; /** All values greater than or equal the given value. */ size_gte?: Maybe<Scalars['Float']>; mimeType?: Maybe<Scalars['String']>; /** All values that are not equal to given value. */ mimeType_not?: Maybe<Scalars['String']>; /** All values that are contained in given list. */ mimeType_in?: Maybe<Array<Scalars['String']>>; /** All values that are not contained in given list. */ mimeType_not_in?: Maybe<Array<Scalars['String']>>; /** All values containing the given string. */ mimeType_contains?: Maybe<Scalars['String']>; /** All values not containing the given string. */ mimeType_not_contains?: Maybe<Scalars['String']>; /** All values starting with the given string. */ mimeType_starts_with?: Maybe<Scalars['String']>; /** All values not starting with the given string. */ mimeType_not_starts_with?: Maybe<Scalars['String']>; /** All values ending with the given string. */ mimeType_ends_with?: Maybe<Scalars['String']>; /** All values not ending with the given string */ mimeType_not_ends_with?: Maybe<Scalars['String']>; productImage_every?: Maybe<ProductWhereInput>; productImage_some?: Maybe<ProductWhereInput>; productImage_none?: Maybe<ProductWhereInput>; }; /** References Asset record uniquely */ export type AssetWhereUniqueInput = { id?: Maybe<Scalars['ID']>; }; export type BatchPayload = { __typename?: 'BatchPayload'; /** The number of nodes that have been affected by the Batch operation. */ count: Scalars['Long']; }; /** Representing a color value comprising of HEX, RGBA and css color values */ export type Color = { __typename?: 'Color'; hex: Scalars['Hex']; rgba: Rgba; css: Scalars['String']; }; /** Accepts either HEX or RGBA color value. At least one of hex or rgba value should be passed. If both are passed RGBA is used. */ export type ColorInput = { hex?: Maybe<Scalars['Hex']>; rgba?: Maybe<RgbaInput>; }; export type ConnectPositionInput = { /** Connect document after specified document */ after?: Maybe<Scalars['ID']>; /** Connect document before specified document */ before?: Maybe<Scalars['ID']>; /** Connect document at first position */ start?: Maybe<Scalars['Boolean']>; /** Connect document at last position */ end?: Maybe<Scalars['Boolean']>; }; export enum DocumentFileTypes { Jpg = 'jpg', Odp = 'odp', Ods = 'ods', Odt = 'odt', Png = 'png', Svg = 'svg', Txt = 'txt', Webp = 'webp', Docx = 'docx', Pdf = 'pdf', Html = 'html', Doc = 'doc', Xlsx = 'xlsx', Xls = 'xls', Pptx = 'pptx', Ppt = 'ppt' } export type DocumentOutputInput = { /** * Transforms a document into a desired file type. * See this matrix for format support: * * PDF: jpg, odp, ods, odt, png, svg, txt, and webp * DOC: docx, html, jpg, odt, pdf, png, svg, txt, and webp * DOCX: doc, html, jpg, odt, pdf, png, svg, txt, and webp * ODT: doc, docx, html, jpg, pdf, png, svg, txt, and webp * XLS: jpg, pdf, ods, png, svg, xlsx, and webp * XLSX: jpg, pdf, ods, png, svg, xls, and webp * ODS: jpg, pdf, png, xls, svg, xlsx, and webp * PPT: jpg, odp, pdf, png, svg, pptx, and webp * PPTX: jpg, odp, pdf, png, svg, ppt, and webp * ODP: jpg, pdf, png, ppt, svg, pptx, and webp * BMP: jpg, odp, ods, odt, pdf, png, svg, and webp * GIF: jpg, odp, ods, odt, pdf, png, svg, and webp * JPG: jpg, odp, ods, odt, pdf, png, svg, and webp * PNG: jpg, odp, ods, odt, pdf, png, svg, and webp * WEBP: jpg, odp, ods, odt, pdf, png, svg, and webp * TIFF: jpg, odp, ods, odt, pdf, png, svg, and webp * AI: jpg, odp, ods, odt, pdf, png, svg, and webp * PSD: jpg, odp, ods, odt, pdf, png, svg, and webp * SVG: jpg, odp, ods, odt, pdf, png, and webp * HTML: jpg, odt, pdf, svg, txt, and webp * TXT: jpg, html, odt, pdf, svg, and webp */ format?: Maybe<DocumentFileTypes>; }; /** Transformations for Documents */ export type DocumentTransformationInput = { /** Changes the output for the file. */ output?: Maybe<DocumentOutputInput>; }; export type DocumentVersion = { __typename?: 'DocumentVersion'; id: Scalars['ID']; stage: Stage; revision: Scalars['Int']; createdAt: Scalars['DateTime']; data?: Maybe<Scalars['Json']>; }; export enum ImageFit { /** Resizes the image to fit within the specified parameters without distorting, cropping, or changing the aspect ratio. */ Clip = 'clip', /** Resizes the image to fit the specified parameters exactly by removing any parts of the image that don't fit within the boundaries. */ Crop = 'crop', /** Resizes the image to fit the specified parameters exactly by scaling the image to the desired size. The aspect ratio of the image is not respected and the image can be distorted using this method. */ Scale = 'scale', /** Resizes the image to fit within the parameters, but as opposed to 'fit:clip' will not scale the image if the image is smaller than the output size. */ Max = 'max' } export type ImageResizeInput = { /** The width in pixels to resize the image to. The value must be an integer from 1 to 10000. */ width?: Maybe<Scalars['Int']>; /** The height in pixels to resize the image to. The value must be an integer from 1 to 10000. */ height?: Maybe<Scalars['Int']>; /** The default value for the fit parameter is fit:clip. */ fit?: Maybe<ImageFit>; }; /** Transformations for Images */ export type ImageTransformationInput = { /** Resizes the image */ resize?: Maybe<ImageResizeInput>; }; /** Locale system enumeration */ export enum Locale { /** System locale */ En = 'en', De = 'de' } /** Representing a geolocation point with latitude and longitude */ export type Location = { __typename?: 'Location'; latitude: Scalars['Float']; longitude: Scalars['Float']; distance: Scalars['Float']; }; /** Representing a geolocation point with latitude and longitude */ export type LocationDistanceArgs = { from: LocationInput; }; /** Input for a geolocation point with latitude and longitude */ export type LocationInput = { latitude: Scalars['Float']; longitude: Scalars['Float']; }; export type Mutation = { __typename?: 'Mutation'; /** * Create one asset * @deprecated Asset mutations will be overhauled soon */ createAsset?: Maybe<Asset>; /** Update one asset */ updateAsset?: Maybe<Asset>; /** Delete one asset from _all_ existing stages. Returns deleted document. */ deleteAsset?: Maybe<Asset>; /** Upsert one asset */ upsertAsset?: Maybe<Asset>; /** Publish one asset */ publishAsset?: Maybe<Asset>; /** Unpublish one asset from selected stages. Unpublish either the complete document with its relations, localizations and base data or specific localizations only. */ unpublishAsset?: Maybe<Asset>; /** Update many Asset documents */ updateManyAssetsConnection: AssetConnection; /** Delete many Asset documents, return deleted documents */ deleteManyAssetsConnection: AssetConnection; /** Publish many Asset documents */ publishManyAssetsConnection: AssetConnection; /** Find many Asset documents that match criteria in specified stage and unpublish from target stages */ unpublishManyAssetsConnection: AssetConnection; /** * Update many assets * @deprecated Please use the new paginated many mutation (updateManyAssetsConnection) */ updateManyAssets: BatchPayload; /** * Delete many Asset documents * @deprecated Please use the new paginated many mutation (deleteManyAssetsConnection) */ deleteManyAssets: BatchPayload; /** * Publish many Asset documents * @deprecated Please use the new paginated many mutation (publishManyAssetsConnection) */ publishManyAssets: BatchPayload; /** * Unpublish many Asset documents * @deprecated Please use the new paginated many mutation (unpublishManyAssetsConnection) */ unpublishManyAssets: BatchPayload; /** Create one product */ createProduct?: Maybe<Product>; /** Update one product */ updateProduct?: Maybe<Product>; /** Delete one product from _all_ existing stages. Returns deleted document. */ deleteProduct?: Maybe<Product>; /** Upsert one product */ upsertProduct?: Maybe<Product>; /** Publish one product */ publishProduct?: Maybe<Product>; /** Unpublish one product from selected stages. Unpublish either the complete document with its relations, localizations and base data or specific localizations only. */ unpublishProduct?: Maybe<Product>; /** Update many Product documents */ updateManyProductsConnection: ProductConnection; /** Delete many Product documents, return deleted documents */ deleteManyProductsConnection: ProductConnection; /** Publish many Product documents */ publishManyProductsConnection: ProductConnection; /** Find many Product documents that match criteria in specified stage and unpublish from target stages */ unpublishManyProductsConnection: ProductConnection; /** * Update many products * @deprecated Please use the new paginated many mutation (updateManyProductsConnection) */ updateManyProducts: BatchPayload; /** * Delete many Product documents * @deprecated Please use the new paginated many mutation (deleteManyProductsConnection) */ deleteManyProducts: BatchPayload; /** * Publish many Product documents * @deprecated Please use the new paginated many mutation (publishManyProductsConnection) */ publishManyProducts: BatchPayload; /** * Unpublish many Product documents * @deprecated Please use the new paginated many mutation (unpublishManyProductsConnection) */ unpublishManyProducts: BatchPayload; /** Create one review */ createReview?: Maybe<Review>; /** Update one review */ updateReview?: Maybe<Review>; /** Delete one review from _all_ existing stages. Returns deleted document. */ deleteReview?: Maybe<Review>; /** Upsert one review */ upsertReview?: Maybe<Review>; /** Publish one review */ publishReview?: Maybe<Review>; /** Unpublish one review from selected stages. Unpublish either the complete document with its relations, localizations and base data or specific localizations only. */ unpublishReview?: Maybe<Review>; /** Update many Review documents */ updateManyReviewsConnection: ReviewConnection; /** Delete many Review documents, return deleted documents */ deleteManyReviewsConnection: ReviewConnection; /** Publish many Review documents */ publishManyReviewsConnection: ReviewConnection; /** Find many Review documents that match criteria in specified stage and unpublish from target stages */ unpublishManyReviewsConnection: ReviewConnection; /** * Update many reviews * @deprecated Please use the new paginated many mutation (updateManyReviewsConnection) */ updateManyReviews: BatchPayload; /** * Delete many Review documents * @deprecated Please use the new paginated many mutation (deleteManyReviewsConnection) */ deleteManyReviews: BatchPayload; /** * Publish many Review documents * @deprecated Please use the new paginated many mutation (publishManyReviewsConnection) */ publishManyReviews: BatchPayload; /** * Unpublish many Review documents * @deprecated Please use the new paginated many mutation (unpublishManyReviewsConnection) */ unpublishManyReviews: BatchPayload; /** Create one vote */ createVote?: Maybe<Vote>; /** Update one vote */ updateVote?: Maybe<Vote>; /** Delete one vote from _all_ existing stages. Returns deleted document. */ deleteVote?: Maybe<Vote>; /** Upsert one vote */ upsertVote?: Maybe<Vote>; /** Publish one vote */ publishVote?: Maybe<Vote>; /** Unpublish one vote from selected stages. Unpublish either the complete document with its relations, localizations and base data or specific localizations only. */ unpublishVote?: Maybe<Vote>; /** Update many Vote documents */ updateManyVotesConnection: VoteConnection; /** Delete many Vote documents, return deleted documents */ deleteManyVotesConnection: VoteConnection; /** Publish many Vote documents */ publishManyVotesConnection: VoteConnection; /** Find many Vote documents that match criteria in specified stage and unpublish from target stages */ unpublishManyVotesConnection: VoteConnection; /** * Update many votes * @deprecated Please use the new paginated many mutation (updateManyVotesConnection) */ updateManyVotes: BatchPayload; /** * Delete many Vote documents * @deprecated Please use the new paginated many mutation (deleteManyVotesConnection) */ deleteManyVotes: BatchPayload; /** * Publish many Vote documents * @deprecated Please use the new paginated many mutation (publishManyVotesConnection) */ publishManyVotes: BatchPayload; /** * Unpublish many Vote documents * @deprecated Please use the new paginated many mutation (unpublishManyVotesConnection) */ unpublishManyVotes: BatchPayload; }; export type MutationCreateAssetArgs = { data: AssetCreateInput; }; export type MutationUpdateAssetArgs = { where: AssetWhereUniqueInput; data: AssetUpdateInput; }; export type MutationDeleteAssetArgs = { where: AssetWhereUniqueInput; }; export type MutationUpsertAssetArgs = { where: AssetWhereUniqueInput; upsert: AssetUpsertInput; }; export type MutationPublishAssetArgs = { where: AssetWhereUniqueInput; locales?: Maybe<Array<Locale>>; publishBase?: Maybe<Scalars['Boolean']>; withDefaultLocale?: Maybe<Scalars['Boolean']>; to?: Array<Stage>; }; export type MutationUnpublishAssetArgs = { where: AssetWhereUniqueInput; from?: Array<Stage>; locales?: Maybe<Array<Locale>>; unpublishBase?: Maybe<Scalars['Boolean']>; }; export type MutationUpdateManyAssetsConnectionArgs = { where?: Maybe<AssetManyWhereInput>; data: AssetUpdateManyInput; skip?: Maybe<Scalars['Int']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; before?: Maybe<Scalars['ID']>; after?: Maybe<Scalars['ID']>; }; export type MutationDeleteManyAssetsConnectionArgs = { where?: Maybe<AssetManyWhereInput>; skip?: Maybe<Scalars['Int']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; before?: Maybe<Scalars['ID']>; after?: Maybe<Scalars['ID']>; }; export type MutationPublishManyAssetsConnectionArgs = { where?: Maybe<AssetManyWhereInput>; from?: Maybe<Stage>; to?: Array<Stage>; skip?: Maybe<Scalars['Int']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; before?: Maybe<Scalars['ID']>; after?: Maybe<Scalars['ID']>; locales?: Maybe<Array<Locale>>; publishBase?: Maybe<Scalars['Boolean']>; withDefaultLocale?: Maybe<Scalars['Boolean']>; }; export type MutationUnpublishManyAssetsConnectionArgs = { where?: Maybe<AssetManyWhereInput>; stage?: Maybe<Stage>; from?: Array<Stage>; skip?: Maybe<Scalars['Int']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; before?: Maybe<Scalars['ID']>; after?: Maybe<Scalars['ID']>; locales?: Maybe<Array<Locale>>; unpublishBase?: Maybe<Scalars['Boolean']>; }; export type MutationUpdateManyAssetsArgs = { where?: Maybe<AssetManyWhereInput>; data: AssetUpdateManyInput; }; export type MutationDeleteManyAssetsArgs = { where?: Maybe<AssetManyWhereInput>; }; export type MutationPublishManyAssetsArgs = { where?: Maybe<AssetManyWhereInput>; to?: Array<Stage>; locales?: Maybe<Array<Locale>>; publishBase?: Maybe<Scalars['Boolean']>; withDefaultLocale?: Maybe<Scalars['Boolean']>; }; export type MutationUnpublishManyAssetsArgs = { where?: Maybe<AssetManyWhereInput>; from?: Array<Stage>; locales?: Maybe<Array<Locale>>; unpublishBase?: Maybe<Scalars['Boolean']>; }; export type MutationCreateProductArgs = { data: ProductCreateInput; }; export type MutationUpdateProductArgs = { where: ProductWhereUniqueInput; data: ProductUpdateInput; }; export type MutationDeleteProductArgs = { where: ProductWhereUniqueInput; }; export type MutationUpsertProductArgs = { where: ProductWhereUniqueInput; upsert: ProductUpsertInput; }; export type MutationPublishProductArgs = { where: ProductWhereUniqueInput; locales?: Maybe<Array<Locale>>; publishBase?: Maybe<Scalars['Boolean']>; withDefaultLocale?: Maybe<Scalars['Boolean']>; to?: Array<Stage>; }; export type MutationUnpublishProductArgs = { where: ProductWhereUniqueInput; from?: Array<Stage>; locales?: Maybe<Array<Locale>>; unpublishBase?: Maybe<Scalars['Boolean']>; }; export type MutationUpdateManyProductsConnectionArgs = { where?: Maybe<ProductManyWhereInput>; data: ProductUpdateManyInput; skip?: Maybe<Scalars['Int']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; before?: Maybe<Scalars['ID']>; after?: Maybe<Scalars['ID']>; }; export type MutationDeleteManyProductsConnectionArgs = { where?: Maybe<ProductManyWhereInput>; skip?: Maybe<Scalars['Int']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; before?: Maybe<Scalars['ID']>; after?: Maybe<Scalars['ID']>; }; export type MutationPublishManyProductsConnectionArgs = { where?: Maybe<ProductManyWhereInput>; from?: Maybe<Stage>; to?: Array<Stage>; skip?: Maybe<Scalars['Int']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; before?: Maybe<Scalars['ID']>; after?: Maybe<Scalars['ID']>; locales?: Maybe<Array<Locale>>; publishBase?: Maybe<Scalars['Boolean']>; withDefaultLocale?: Maybe<Scalars['Boolean']>; }; export type MutationUnpublishManyProductsConnectionArgs = { where?: Maybe<ProductManyWhereInput>; stage?: Maybe<Stage>; from?: Array<Stage>; skip?: Maybe<Scalars['Int']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; before?: Maybe<Scalars['ID']>; after?: Maybe<Scalars['ID']>; locales?: Maybe<Array<Locale>>; unpublishBase?: Maybe<Scalars['Boolean']>; }; export type MutationUpdateManyProductsArgs = { where?: Maybe<ProductManyWhereInput>; data: ProductUpdateManyInput; }; export type MutationDeleteManyProductsArgs = { where?: Maybe<ProductManyWhereInput>; }; export type MutationPublishManyProductsArgs = { where?: Maybe<ProductManyWhereInput>; to?: Array<Stage>; locales?: Maybe<Array<Locale>>; publishBase?: Maybe<Scalars['Boolean']>; withDefaultLocale?: Maybe<Scalars['Boolean']>; }; export type MutationUnpublishManyProductsArgs = { where?: Maybe<ProductManyWhereInput>; from?: Array<Stage>; locales?: Maybe<Array<Locale>>; unpublishBase?: Maybe<Scalars['Boolean']>; }; export type MutationCreateReviewArgs = { data: ReviewCreateInput; }; export type MutationUpdateReviewArgs = { where: ReviewWhereUniqueInput; data: ReviewUpdateInput; }; export type MutationDeleteReviewArgs = { where: ReviewWhereUniqueInput; }; export type MutationUpsertReviewArgs = { where: ReviewWhereUniqueInput; upsert: ReviewUpsertInput; }; export type MutationPublishReviewArgs = { where: ReviewWhereUniqueInput; to?: Array<Stage>; }; export type MutationUnpublishReviewArgs = { where: ReviewWhereUniqueInput; from?: Array<Stage>; }; export type MutationUpdateManyReviewsConnectionArgs = { where?: Maybe<ReviewManyWhereInput>; data: ReviewUpdateManyInput; skip?: Maybe<Scalars['Int']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; before?: Maybe<Scalars['ID']>; after?: Maybe<Scalars['ID']>; }; export type MutationDeleteManyReviewsConnectionArgs = { where?: Maybe<ReviewManyWhereInput>; skip?: Maybe<Scalars['Int']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; before?: Maybe<Scalars['ID']>; after?: Maybe<Scalars['ID']>; }; export type MutationPublishManyReviewsConnectionArgs = { where?: Maybe<ReviewManyWhereInput>; from?: Maybe<Stage>; to?: Array<Stage>; skip?: Maybe<Scalars['Int']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; before?: Maybe<Scalars['ID']>; after?: Maybe<Scalars['ID']>; }; export type MutationUnpublishManyReviewsConnectionArgs = { where?: Maybe<ReviewManyWhereInput>; stage?: Maybe<Stage>; from?: Array<Stage>; skip?: Maybe<Scalars['Int']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; before?: Maybe<Scalars['ID']>; after?: Maybe<Scalars['ID']>; }; export type MutationUpdateManyReviewsArgs = { where?: Maybe<ReviewManyWhereInput>; data: ReviewUpdateManyInput; }; export type MutationDeleteManyReviewsArgs = { where?: Maybe<ReviewManyWhereInput>; }; export type MutationPublishManyReviewsArgs = { where?: Maybe<ReviewManyWhereInput>; to?: Array<Stage>; }; export type MutationUnpublishManyReviewsArgs = { where?: Maybe<ReviewManyWhereInput>; from?: Array<Stage>; }; export type MutationCreateVoteArgs = { data: VoteCreateInput; }; export type MutationUpdateVoteArgs = { where: VoteWhereUniqueInput; data: VoteUpdateInput; }; export type MutationDeleteVoteArgs = { where: VoteWhereUniqueInput; }; export type MutationUpsertVoteArgs = { where: VoteWhereUniqueInput; upsert: VoteUpsertInput; }; export type MutationPublishVoteArgs = { where: VoteWhereUniqueInput; to?: Array<Stage>; }; export type MutationUnpublishVoteArgs = { where: VoteWhereUniqueInput; from?: Array<Stage>; }; export type MutationUpdateManyVotesConnectionArgs = { where?: Maybe<VoteManyWhereInput>; data: VoteUpdateManyInput; skip?: Maybe<Scalars['Int']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; before?: Maybe<Scalars['ID']>; after?: Maybe<Scalars['ID']>; }; export type MutationDeleteManyVotesConnectionArgs = { where?: Maybe<VoteManyWhereInput>; skip?: Maybe<Scalars['Int']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; before?: Maybe<Scalars['ID']>; after?: Maybe<Scalars['ID']>; }; export type MutationPublishManyVotesConnectionArgs = { where?: Maybe<VoteManyWhereInput>; from?: Maybe<Stage>; to?: Array<Stage>; skip?: Maybe<Scalars['Int']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; before?: Maybe<Scalars['ID']>; after?: Maybe<Scalars['ID']>; }; export type MutationUnpublishManyVotesConnectionArgs = { where?: Maybe<VoteManyWhereInput>; stage?: Maybe<Stage>; from?: Array<Stage>; skip?: Maybe<Scalars['Int']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; before?: Maybe<Scalars['ID']>; after?: Maybe<Scalars['ID']>; }; export type MutationUpdateManyVotesArgs = { where?: Maybe<VoteManyWhereInput>; data: VoteUpdateManyInput; }; export type MutationDeleteManyVotesArgs = { where?: Maybe<VoteManyWhereInput>; }; export type MutationPublishManyVotesArgs = { where?: Maybe<VoteManyWhereInput>; to?: Array<Stage>; }; export type MutationUnpublishManyVotesArgs = { where?: Maybe<VoteManyWhereInput>; from?: Array<Stage>; }; /** An object with an ID */ export type Node = { /** The id of the object. */ id: Scalars['ID']; /** The Stage of an object */ stage: Stage; }; /** Information about pagination in a connection. */ export type PageInfo = { __typename?: 'PageInfo'; /** When paginating forwards, are there more items? */ hasNextPage: Scalars['Boolean']; /** When paginating backwards, are there more items? */ hasPreviousPage: Scalars['Boolean']; /** When paginating backwards, the cursor to continue. */ startCursor?: Maybe<Scalars['String']>; /** When paginating forwards, the cursor to continue. */ endCursor?: Maybe<Scalars['String']>; /** Number of items in the current page. */ pageSize?: Maybe<Scalars['Int']>; }; export type Product = Node & { __typename?: 'Product'; /** System stage field */ stage: Stage; /** System Locale field */ locale: Locale; /** Get the other localizations for this document */ localizations: Array<Product>; /** Get the document in other stages */ documentInStages: Array<Product>; /** The unique identifier */ id: Scalars['ID']; /** The time the document was created */ createdAt: Scalars['DateTime']; /** The time the document was updated */ updatedAt: Scalars['DateTime']; /** The time the document was published. Null on documents in draft stage. */ publishedAt?: Maybe<Scalars['DateTime']>; name: Scalars['String']; slug: Scalars['String']; description?: Maybe<Scalars['String']>; price: Scalars['Int']; reviews: Array<Review>; votes: Array<Vote>; image?: Maybe<Asset>; content?: Maybe<RichText>; /** List of Product versions */ history: Array<Version>; }; export type ProductLocalizationsArgs = { locales?: Array<Locale>; includeCurrent?: Scalars['Boolean']; }; export type ProductDocumentInStagesArgs = { stages?: Array<Stage>; includeCurrent?: Scalars['Boolean']; inheritLocale?: Scalars['Boolean']; }; export type ProductCreatedAtArgs = { variation?: SystemDateTimeFieldVariation; }; export type ProductUpdatedAtArgs = { variation?: SystemDateTimeFieldVariation; }; export type ProductPublishedAtArgs = { variation?: SystemDateTimeFieldVariation; }; export type ProductReviewsArgs = { where?: Maybe<ReviewWhereInput>; orderBy?: Maybe<ReviewOrderByInput>; skip?: Maybe<Scalars['Int']>; after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; locales?: Maybe<Array<Locale>>; }; export type ProductVotesArgs = { where?: Maybe<VoteWhereInput>; orderBy?: Maybe<VoteOrderByInput>; skip?: Maybe<Scalars['Int']>; after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; locales?: Maybe<Array<Locale>>; }; export type ProductImageArgs = { locales?: Maybe<Array<Locale>>; }; export type ProductHistoryArgs = { limit?: Scalars['Int']; skip?: Scalars['Int']; stageOverride?: Maybe<Stage>; }; export type ProductConnectInput = { /** Document to connect */ where: ProductWhereUniqueInput; /** Allow to specify document position in list of connected documents, will default to appending at end of list */ position?: Maybe<ConnectPositionInput>; }; /** A connection to a list of items. */ export type ProductConnection = { __typename?: 'ProductConnection'; /** Information to aid in pagination. */ pageInfo: PageInfo; /** A list of edges. */ edges: Array<ProductEdge>; aggregate: Aggregate; }; export type ProductCreateInput = { createdAt?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; /** name input for default locale (en) */ name: Scalars['String']; slug: Scalars['String']; description?: Maybe<Scalars['String']>; price: Scalars['Int']; reviews?: Maybe<ReviewCreateManyInlineInput>; votes?: Maybe<VoteCreateManyInlineInput>; image?: Maybe<AssetCreateOneInlineInput>; content?: Maybe<Scalars['RichTextAST']>; /** Inline mutations for managing document localizations excluding the default locale */ localizations?: Maybe<ProductCreateLocalizationsInput>; }; export type ProductCreateLocalizationDataInput = { createdAt?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; name: Scalars['String']; }; export type ProductCreateLocalizationInput = { /** Localization input */ data: ProductCreateLocalizationDataInput; locale: Locale; }; export type ProductCreateLocalizationsInput = { /** Create localizations for the newly-created document */ create?: Maybe<Array<ProductCreateLocalizationInput>>; }; export type ProductCreateManyInlineInput = { /** Create and connect multiple existing Product documents */ create?: Maybe<Array<ProductCreateInput>>; /** Connect multiple existing Product documents */ connect?: Maybe<Array<ProductWhereUniqueInput>>; }; export type ProductCreateOneInlineInput = { /** Create and connect one Product document */ create?: Maybe<ProductCreateInput>; /** Connect one existing Product document */ connect?: Maybe<ProductWhereUniqueInput>; }; /** An edge in a connection. */ export type ProductEdge = { __typename?: 'ProductEdge'; /** The item at the end of the edge. */ node: Product; /** A cursor for use in pagination. */ cursor: Scalars['String']; }; /** Identifies documents */ export type ProductManyWhereInput = { /** Contains search across all appropriate fields. */ _search?: Maybe<Scalars['String']>; /** Logical AND on all given filters. */ AND?: Maybe<Array<ProductWhereInput>>; /** Logical OR on all given filters. */ OR?: Maybe<Array<ProductWhereInput>>; /** Logical NOT on all given filters combined by AND. */ NOT?: Maybe<Array<ProductWhereInput>>; id?: Maybe<Scalars['ID']>; /** All values that are not equal to given value. */ id_not?: Maybe<Scalars['ID']>; /** All values that are contained in given list. */ id_in?: Maybe<Array<Scalars['ID']>>; /** All values that are not contained in given list. */ id_not_in?: Maybe<Array<Scalars['ID']>>; /** All values containing the given string. */ id_contains?: Maybe<Scalars['ID']>; /** All values not containing the given string. */ id_not_contains?: Maybe<Scalars['ID']>; /** All values starting with the given string. */ id_starts_with?: Maybe<Scalars['ID']>; /** All values not starting with the given string. */ id_not_starts_with?: Maybe<Scalars['ID']>; /** All values ending with the given string. */ id_ends_with?: Maybe<Scalars['ID']>; /** All values not ending with the given string */ id_not_ends_with?: Maybe<Scalars['ID']>; createdAt?: Maybe<Scalars['DateTime']>; /** All values that are not equal to given value. */ createdAt_not?: Maybe<Scalars['DateTime']>; /** All values that are contained in given list. */ createdAt_in?: Maybe<Array<Scalars['DateTime']>>; /** All values that are not contained in given list. */ createdAt_not_in?: Maybe<Array<Scalars['DateTime']>>; /** All values less than the given value. */ createdAt_lt?: Maybe<Scalars['DateTime']>; /** All values less than or equal the given value. */ createdAt_lte?: Maybe<Scalars['DateTime']>; /** All values greater than the given value. */ createdAt_gt?: Maybe<Scalars['DateTime']>; /** All values greater than or equal the given value. */ createdAt_gte?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; /** All values that are not equal to given value. */ updatedAt_not?: Maybe<Scalars['DateTime']>; /** All values that are contained in given list. */ updatedAt_in?: Maybe<Array<Scalars['DateTime']>>; /** All values that are not contained in given list. */ updatedAt_not_in?: Maybe<Array<Scalars['DateTime']>>; /** All values less than the given value. */ updatedAt_lt?: Maybe<Scalars['DateTime']>; /** All values less than or equal the given value. */ updatedAt_lte?: Maybe<Scalars['DateTime']>; /** All values greater than the given value. */ updatedAt_gt?: Maybe<Scalars['DateTime']>; /** All values greater than or equal the given value. */ updatedAt_gte?: Maybe<Scalars['DateTime']>; publishedAt?: Maybe<Scalars['DateTime']>; /** All values that are not equal to given value. */ publishedAt_not?: Maybe<Scalars['DateTime']>; /** All values that are contained in given list. */ publishedAt_in?: Maybe<Array<Scalars['DateTime']>>; /** All values that are not contained in given list. */ publishedAt_not_in?: Maybe<Array<Scalars['DateTime']>>; /** All values less than the given value. */ publishedAt_lt?: Maybe<Scalars['DateTime']>; /** All values less than or equal the given value. */ publishedAt_lte?: Maybe<Scalars['DateTime']>; /** All values greater than the given value. */ publishedAt_gt?: Maybe<Scalars['DateTime']>; /** All values greater than or equal the given value. */ publishedAt_gte?: Maybe<Scalars['DateTime']>; slug?: Maybe<Scalars['String']>; /** All values that are not equal to given value. */ slug_not?: Maybe<Scalars['String']>; /** All values that are contained in given list. */ slug_in?: Maybe<Array<Scalars['String']>>; /** All values that are not contained in given list. */ slug_not_in?: Maybe<Array<Scalars['String']>>; /** All values containing the given string. */ slug_contains?: Maybe<Scalars['String']>; /** All values not containing the given string. */ slug_not_contains?: Maybe<Scalars['String']>; /** All values starting with the given string. */ slug_starts_with?: Maybe<Scalars['String']>; /** All values not starting with the given string. */ slug_not_starts_with?: Maybe<Scalars['String']>; /** All values ending with the given string. */ slug_ends_with?: Maybe<Scalars['String']>; /** All values not ending with the given string */ slug_not_ends_with?: Maybe<Scalars['String']>; description?: Maybe<Scalars['String']>; /** All values that are not equal to given value. */ description_not?: Maybe<Scalars['String']>; /** All values that are contained in given list. */ description_in?: Maybe<Array<Scalars['String']>>; /** All values that are not contained in given list. */ description_not_in?: Maybe<Array<Scalars['String']>>; /** All values containing the given string. */ description_contains?: Maybe<Scalars['String']>; /** All values not containing the given string. */ description_not_contains?: Maybe<Scalars['String']>; /** All values starting with the given string. */ description_starts_with?: Maybe<Scalars['String']>; /** All values not starting with the given string. */ description_not_starts_with?: Maybe<Scalars['String']>; /** All values ending with the given string. */ description_ends_with?: Maybe<Scalars['String']>; /** All values not ending with the given string */ description_not_ends_with?: Maybe<Scalars['String']>; price?: Maybe<Scalars['Int']>; /** All values that are not equal to given value. */ price_not?: Maybe<Scalars['Int']>; /** All values that are contained in given list. */ price_in?: Maybe<Array<Scalars['Int']>>; /** All values that are not contained in given list. */ price_not_in?: Maybe<Array<Scalars['Int']>>; /** All values less than the given value. */ price_lt?: Maybe<Scalars['Int']>; /** All values less than or equal the given value. */ price_lte?: Maybe<Scalars['Int']>; /** All values greater than the given value. */ price_gt?: Maybe<Scalars['Int']>; /** All values greater than or equal the given value. */ price_gte?: Maybe<Scalars['Int']>; reviews_every?: Maybe<ReviewWhereInput>; reviews_some?: Maybe<ReviewWhereInput>; reviews_none?: Maybe<ReviewWhereInput>; votes_every?: Maybe<VoteWhereInput>; votes_some?: Maybe<VoteWhereInput>; votes_none?: Maybe<VoteWhereInput>; image?: Maybe<AssetWhereInput>; }; export enum ProductOrderByInput { IdAsc = 'id_ASC', IdDesc = 'id_DESC', CreatedAtAsc = 'createdAt_ASC', CreatedAtDesc = 'createdAt_DESC', UpdatedAtAsc = 'updatedAt_ASC', UpdatedAtDesc = 'updatedAt_DESC', PublishedAtAsc = 'publishedAt_ASC', PublishedAtDesc = 'publishedAt_DESC', NameAsc = 'name_ASC', NameDesc = 'name_DESC', SlugAsc = 'slug_ASC', SlugDesc = 'slug_DESC', DescriptionAsc = 'description_ASC', DescriptionDesc = 'description_DESC', PriceAsc = 'price_ASC', PriceDesc = 'price_DESC' } export type ProductUpdateInput = { /** name input for default locale (en) */ name?: Maybe<Scalars['String']>; slug?: Maybe<Scalars['String']>; description?: Maybe<Scalars['String']>; price?: Maybe<Scalars['Int']>; reviews?: Maybe<ReviewUpdateManyInlineInput>; votes?: Maybe<VoteUpdateManyInlineInput>; image?: Maybe<AssetUpdateOneInlineInput>; content?: Maybe<Scalars['RichTextAST']>; /** Manage document localizations */ localizations?: Maybe<ProductUpdateLocalizationsInput>; }; export type ProductUpdateLocalizationDataInput = { name?: Maybe<Scalars['String']>; }; export type ProductUpdateLocalizationInput = { data: ProductUpdateLocalizationDataInput; locale: Locale; }; export type ProductUpdateLocalizationsInput = { /** Localizations to create */ create?: Maybe<Array<ProductCreateLocalizationInput>>; /** Localizations to update */ update?: Maybe<Array<ProductUpdateLocalizationInput>>; upsert?: Maybe<Array<ProductUpsertLocalizationInput>>; /** Localizations to delete */ delete?: Maybe<Array<Locale>>; }; export type ProductUpdateManyInlineInput = { /** Create and connect multiple Product documents */ create?: Maybe<Array<ProductCreateInput>>; /** Connect multiple existing Product documents */ connect?: Maybe<Array<ProductConnectInput>>; /** Override currently-connected documents with multiple existing Product documents */ set?: Maybe<Array<ProductWhereUniqueInput>>; /** Update multiple Product documents */ update?: Maybe<Array<ProductUpdateWithNestedWhereUniqueInput>>; /** Upsert multiple Product documents */ upsert?: Maybe<Array<ProductUpsertWithNestedWhereUniqueInput>>; /** Disconnect multiple Product documents */ disconnect?: Maybe<Array<ProductWhereUniqueInput>>; /** Delete multiple Product documents */ delete?: Maybe<Array<ProductWhereUniqueInput>>; }; export type ProductUpdateManyInput = { /** name input for default locale (en) */ name?: Maybe<Scalars['String']>; description?: Maybe<Scalars['String']>; price?: Maybe<Scalars['Int']>; content?: Maybe<Scalars['RichTextAST']>; /** Optional updates to localizations */ localizations?: Maybe<ProductUpdateManyLocalizationsInput>; }; export type ProductUpdateManyLocalizationDataInput = { name?: Maybe<Scalars['String']>; }; export type ProductUpdateManyLocalizationInput = { data: ProductUpdateManyLocalizationDataInput; locale: Locale; }; export type ProductUpdateManyLocalizationsInput = { /** Localizations to update */ update?: Maybe<Array<ProductUpdateManyLocalizationInput>>; }; export type ProductUpdateManyWithNestedWhereInput = { /** Document search */ where: ProductWhereInput; /** Update many input */ data: ProductUpdateManyInput; }; export type ProductUpdateOneInlineInput = { /** Create and connect one Product document */ create?: Maybe<ProductCreateInput>; /** Update single Product document */ update?: Maybe<ProductUpdateWithNestedWhereUniqueInput>; /** Upsert single Product document */ upsert?: Maybe<ProductUpsertWithNestedWhereUniqueInput>; /** Connect existing Product document */ connect?: Maybe<ProductWhereUniqueInput>; /** Disconnect currently connected Product document */ disconnect?: Maybe<Scalars['Boolean']>; /** Delete currently connected Product document */ delete?: Maybe<Scalars['Boolean']>; }; export type ProductUpdateWithNestedWhereUniqueInput = { /** Unique document search */ where: ProductWhereUniqueInput; /** Document to update */ data: ProductUpdateInput; }; export type ProductUpsertInput = { /** Create document if it didn't exist */ create: ProductCreateInput; /** Update document if it exists */ update: ProductUpdateInput; }; export type ProductUpsertLocalizationInput = { update: ProductUpdateLocalizationDataInput; create: ProductCreateLocalizationDataInput; locale: Locale; }; export type ProductUpsertWithNestedWhereUniqueInput = { /** Unique document search */ where: ProductWhereUniqueInput; /** Upsert data */ data: ProductUpsertInput; }; /** Identifies documents */ export type ProductWhereInput = { /** Contains search across all appropriate fields. */ _search?: Maybe<Scalars['String']>; /** Logical AND on all given filters. */ AND?: Maybe<Array<ProductWhereInput>>; /** Logical OR on all given filters. */ OR?: Maybe<Array<ProductWhereInput>>; /** Logical NOT on all given filters combined by AND. */ NOT?: Maybe<Array<ProductWhereInput>>; id?: Maybe<Scalars['ID']>; /** All values that are not equal to given value. */ id_not?: Maybe<Scalars['ID']>; /** All values that are contained in given list. */ id_in?: Maybe<Array<Scalars['ID']>>; /** All values that are not contained in given list. */ id_not_in?: Maybe<Array<Scalars['ID']>>; /** All values containing the given string. */ id_contains?: Maybe<Scalars['ID']>; /** All values not containing the given string. */ id_not_contains?: Maybe<Scalars['ID']>; /** All values starting with the given string. */ id_starts_with?: Maybe<Scalars['ID']>; /** All values not starting with the given string. */ id_not_starts_with?: Maybe<Scalars['ID']>; /** All values ending with the given string. */ id_ends_with?: Maybe<Scalars['ID']>; /** All values not ending with the given string */ id_not_ends_with?: Maybe<Scalars['ID']>; createdAt?: Maybe<Scalars['DateTime']>; /** All values that are not equal to given value. */ createdAt_not?: Maybe<Scalars['DateTime']>; /** All values that are contained in given list. */ createdAt_in?: Maybe<Array<Scalars['DateTime']>>; /** All values that are not contained in given list. */ createdAt_not_in?: Maybe<Array<Scalars['DateTime']>>; /** All values less than the given value. */ createdAt_lt?: Maybe<Scalars['DateTime']>; /** All values less than or equal the given value. */ createdAt_lte?: Maybe<Scalars['DateTime']>; /** All values greater than the given value. */ createdAt_gt?: Maybe<Scalars['DateTime']>; /** All values greater than or equal the given value. */ createdAt_gte?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; /** All values that are not equal to given value. */ updatedAt_not?: Maybe<Scalars['DateTime']>; /** All values that are contained in given list. */ updatedAt_in?: Maybe<Array<Scalars['DateTime']>>; /** All values that are not contained in given list. */ updatedAt_not_in?: Maybe<Array<Scalars['DateTime']>>; /** All values less than the given value. */ updatedAt_lt?: Maybe<Scalars['DateTime']>; /** All values less than or equal the given value. */ updatedAt_lte?: Maybe<Scalars['DateTime']>; /** All values greater than the given value. */ updatedAt_gt?: Maybe<Scalars['DateTime']>; /** All values greater than or equal the given value. */ updatedAt_gte?: Maybe<Scalars['DateTime']>; publishedAt?: Maybe<Scalars['DateTime']>; /** All values that are not equal to given value. */ publishedAt_not?: Maybe<Scalars['DateTime']>; /** All values that are contained in given list. */ publishedAt_in?: Maybe<Array<Scalars['DateTime']>>; /** All values that are not contained in given list. */ publishedAt_not_in?: Maybe<Array<Scalars['DateTime']>>; /** All values less than the given value. */ publishedAt_lt?: Maybe<Scalars['DateTime']>; /** All values less than or equal the given value. */ publishedAt_lte?: Maybe<Scalars['DateTime']>; /** All values greater than the given value. */ publishedAt_gt?: Maybe<Scalars['DateTime']>; /** All values greater than or equal the given value. */ publishedAt_gte?: Maybe<Scalars['DateTime']>; name?: Maybe<Scalars['String']>; /** All values that are not equal to given value. */ name_not?: Maybe<Scalars['String']>; /** All values that are contained in given list. */ name_in?: Maybe<Array<Scalars['String']>>; /** All values that are not contained in given list. */ name_not_in?: Maybe<Array<Scalars['String']>>; /** All values containing the given string. */ name_contains?: Maybe<Scalars['String']>; /** All values not containing the given string. */ name_not_contains?: Maybe<Scalars['String']>; /** All values starting with the given string. */ name_starts_with?: Maybe<Scalars['String']>; /** All values not starting with the given string. */ name_not_starts_with?: Maybe<Scalars['String']>; /** All values ending with the given string. */ name_ends_with?: Maybe<Scalars['String']>; /** All values not ending with the given string */ name_not_ends_with?: Maybe<Scalars['String']>; slug?: Maybe<Scalars['String']>; /** All values that are not equal to given value. */ slug_not?: Maybe<Scalars['String']>; /** All values that are contained in given list. */ slug_in?: Maybe<Array<Scalars['String']>>; /** All values that are not contained in given list. */ slug_not_in?: Maybe<Array<Scalars['String']>>; /** All values containing the given string. */ slug_contains?: Maybe<Scalars['String']>; /** All values not containing the given string. */ slug_not_contains?: Maybe<Scalars['String']>; /** All values starting with the given string. */ slug_starts_with?: Maybe<Scalars['String']>; /** All values not starting with the given string. */ slug_not_starts_with?: Maybe<Scalars['String']>; /** All values ending with the given string. */ slug_ends_with?: Maybe<Scalars['String']>; /** All values not ending with the given string */ slug_not_ends_with?: Maybe<Scalars['String']>; description?: Maybe<Scalars['String']>; /** All values that are not equal to given value. */ description_not?: Maybe<Scalars['String']>; /** All values that are contained in given list. */ description_in?: Maybe<Array<Scalars['String']>>; /** All values that are not contained in given list. */ description_not_in?: Maybe<Array<Scalars['String']>>; /** All values containing the given string. */ description_contains?: Maybe<Scalars['String']>; /** All values not containing the given string. */ description_not_contains?: Maybe<Scalars['String']>; /** All values starting with the given string. */ description_starts_with?: Maybe<Scalars['String']>; /** All values not starting with the given string. */ description_not_starts_with?: Maybe<Scalars['String']>; /** All values ending with the given string. */ description_ends_with?: Maybe<Scalars['String']>; /** All values not ending with the given string */ description_not_ends_with?: Maybe<Scalars['String']>; price?: Maybe<Scalars['Int']>; /** All values that are not equal to given value. */ price_not?: Maybe<Scalars['Int']>; /** All values that are contained in given list. */ price_in?: Maybe<Array<Scalars['Int']>>; /** All values that are not contained in given list. */ price_not_in?: Maybe<Array<Scalars['Int']>>; /** All values less than the given value. */ price_lt?: Maybe<Scalars['Int']>; /** All values less than or equal the given value. */ price_lte?: Maybe<Scalars['Int']>; /** All values greater than the given value. */ price_gt?: Maybe<Scalars['Int']>; /** All values greater than or equal the given value. */ price_gte?: Maybe<Scalars['Int']>; reviews_every?: Maybe<ReviewWhereInput>; reviews_some?: Maybe<ReviewWhereInput>; reviews_none?: Maybe<ReviewWhereInput>; votes_every?: Maybe<VoteWhereInput>; votes_some?: Maybe<VoteWhereInput>; votes_none?: Maybe<VoteWhereInput>; image?: Maybe<AssetWhereInput>; }; /** References Product record uniquely */ export type ProductWhereUniqueInput = { id?: Maybe<Scalars['ID']>; slug?: Maybe<Scalars['String']>; }; export type PublishLocaleInput = { /** Locales to publish */ locale: Locale; /** Stages to publish selected locales to */ stages: Array<Stage>; }; export type Query = { __typename?: 'Query'; /** Fetches an object given its ID */ node?: Maybe<Node>; /** Retrieve multiple assets */ assets: Array<Asset>; /** Retrieve a single asset */ asset?: Maybe<Asset>; /** Retrieve multiple assets using the Relay connection interface */ assetsConnection: AssetConnection; /** Retrieve document version */ assetVersion?: Maybe<DocumentVersion>; /** Retrieve multiple products */ products: Array<Product>; /** Retrieve a single product */ product?: Maybe<Product>; /** Retrieve multiple products using the Relay connection interface */ productsConnection: ProductConnection; /** Retrieve document version */ productVersion?: Maybe<DocumentVersion>; /** Retrieve multiple reviews */ reviews: Array<Review>; /** Retrieve a single review */ review?: Maybe<Review>; /** Retrieve multiple reviews using the Relay connection interface */ reviewsConnection: ReviewConnection; /** Retrieve document version */ reviewVersion?: Maybe<DocumentVersion>; /** Retrieve multiple votes */ votes: Array<Vote>; /** Retrieve a single vote */ vote?: Maybe<Vote>; /** Retrieve multiple votes using the Relay connection interface */ votesConnection: VoteConnection; /** Retrieve document version */ voteVersion?: Maybe<DocumentVersion>; }; export type QueryNodeArgs = { id: Scalars['ID']; stage?: Stage; locales?: Array<Locale>; }; export type QueryAssetsArgs = { where?: Maybe<AssetWhereInput>; orderBy?: Maybe<AssetOrderByInput>; skip?: Maybe<Scalars['Int']>; after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; stage?: Stage; locales?: Array<Locale>; }; export type QueryAssetArgs = { where: AssetWhereUniqueInput; stage?: Stage; locales?: Array<Locale>; }; export type QueryAssetsConnectionArgs = { where?: Maybe<AssetWhereInput>; orderBy?: Maybe<AssetOrderByInput>; skip?: Maybe<Scalars['Int']>; after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; stage?: Stage; locales?: Array<Locale>; }; export type QueryAssetVersionArgs = { where: VersionWhereInput; }; export type QueryProductsArgs = { where?: Maybe<ProductWhereInput>; orderBy?: Maybe<ProductOrderByInput>; skip?: Maybe<Scalars['Int']>; after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; stage?: Stage; locales?: Array<Locale>; }; export type QueryProductArgs = { where: ProductWhereUniqueInput; stage?: Stage; locales?: Array<Locale>; }; export type QueryProductsConnectionArgs = { where?: Maybe<ProductWhereInput>; orderBy?: Maybe<ProductOrderByInput>; skip?: Maybe<Scalars['Int']>; after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; stage?: Stage; locales?: Array<Locale>; }; export type QueryProductVersionArgs = { where: VersionWhereInput; }; export type QueryReviewsArgs = { where?: Maybe<ReviewWhereInput>; orderBy?: Maybe<ReviewOrderByInput>; skip?: Maybe<Scalars['Int']>; after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; stage?: Stage; locales?: Array<Locale>; }; export type QueryReviewArgs = { where: ReviewWhereUniqueInput; stage?: Stage; locales?: Array<Locale>; }; export type QueryReviewsConnectionArgs = { where?: Maybe<ReviewWhereInput>; orderBy?: Maybe<ReviewOrderByInput>; skip?: Maybe<Scalars['Int']>; after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; stage?: Stage; locales?: Array<Locale>; }; export type QueryReviewVersionArgs = { where: VersionWhereInput; }; export type QueryVotesArgs = { where?: Maybe<VoteWhereInput>; orderBy?: Maybe<VoteOrderByInput>; skip?: Maybe<Scalars['Int']>; after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; stage?: Stage; locales?: Array<Locale>; }; export type QueryVoteArgs = { where: VoteWhereUniqueInput; stage?: Stage; locales?: Array<Locale>; }; export type QueryVotesConnectionArgs = { where?: Maybe<VoteWhereInput>; orderBy?: Maybe<VoteOrderByInput>; skip?: Maybe<Scalars['Int']>; after?: Maybe<Scalars['String']>; before?: Maybe<Scalars['String']>; first?: Maybe<Scalars['Int']>; last?: Maybe<Scalars['Int']>; stage?: Stage; locales?: Array<Locale>; }; export type QueryVoteVersionArgs = { where: VersionWhereInput; }; /** Representing a RGBA color value: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#rgb()_and_rgba() */ export type Rgba = { __typename?: 'RGBA'; r: Scalars['RGBAHue']; g: Scalars['RGBAHue']; b: Scalars['RGBAHue']; a: Scalars['RGBATransparency']; }; /** Input type representing a RGBA color value: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#rgb()_and_rgba() */ export type RgbaInput = { r: Scalars['RGBAHue']; g: Scalars['RGBAHue']; b: Scalars['RGBAHue']; a: Scalars['RGBATransparency']; }; export type Review = Node & { __typename?: 'Review'; /** System stage field */ stage: Stage; /** Get the document in other stages */ documentInStages: Array<Review>; /** The unique identifier */ id: Scalars['ID']; /** The time the document was created */ createdAt: Scalars['DateTime']; /** The time the document was updated */ updatedAt: Scalars['DateTime']; /** The time the document was published. Null on documents in draft stage. */ publishedAt?: Maybe<Scalars['DateTime']>; name?: Maybe<Scalars['String']>; comment: Scalars['String']; product?: Maybe<Product>; /** List of Review versions */ history: Array<Version>; }; export type ReviewDocumentInStagesArgs = { stages?: Array<Stage>; includeCurrent?: Scalars['Boolean']; inheritLocale?: Scalars['Boolean']; }; export type ReviewProductArgs = { locales?: Maybe<Array<Locale>>; }; export type ReviewHistoryArgs = { limit?: Scalars['Int']; skip?: Scalars['Int']; stageOverride?: Maybe<Stage>; }; export type ReviewConnectInput = { /** Document to connect */ where: ReviewWhereUniqueInput; /** Allow to specify document position in list of connected documents, will default to appending at end of list */ position?: Maybe<ConnectPositionInput>; }; /** A connection to a list of items. */ export type ReviewConnection = { __typename?: 'ReviewConnection'; /** Information to aid in pagination. */ pageInfo: PageInfo; /** A list of edges. */ edges: Array<ReviewEdge>; aggregate: Aggregate; }; export type ReviewCreateInput = { createdAt?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; name?: Maybe<Scalars['String']>; comment: Scalars['String']; product?: Maybe<ProductCreateOneInlineInput>; }; export type ReviewCreateManyInlineInput = { /** Create and connect multiple existing Review documents */ create?: Maybe<Array<ReviewCreateInput>>; /** Connect multiple existing Review documents */ connect?: Maybe<Array<ReviewWhereUniqueInput>>; }; export type ReviewCreateOneInlineInput = { /** Create and connect one Review document */ create?: Maybe<ReviewCreateInput>; /** Connect one existing Review document */ connect?: Maybe<ReviewWhereUniqueInput>; }; /** An edge in a connection. */ export type ReviewEdge = { __typename?: 'ReviewEdge'; /** The item at the end of the edge. */ node: Review; /** A cursor for use in pagination. */ cursor: Scalars['String']; }; /** Identifies documents */ export type ReviewManyWhereInput = { /** Contains search across all appropriate fields. */ _search?: Maybe<Scalars['String']>; /** Logical AND on all given filters. */ AND?: Maybe<Array<ReviewWhereInput>>; /** Logical OR on all given filters. */ OR?: Maybe<Array<ReviewWhereInput>>; /** Logical NOT on all given filters combined by AND. */ NOT?: Maybe<Array<ReviewWhereInput>>; id?: Maybe<Scalars['ID']>; /** All values that are not equal to given value. */ id_not?: Maybe<Scalars['ID']>; /** All values that are contained in given list. */ id_in?: Maybe<Array<Scalars['ID']>>; /** All values that are not contained in given list. */ id_not_in?: Maybe<Array<Scalars['ID']>>; /** All values containing the given string. */ id_contains?: Maybe<Scalars['ID']>; /** All values not containing the given string. */ id_not_contains?: Maybe<Scalars['ID']>; /** All values starting with the given string. */ id_starts_with?: Maybe<Scalars['ID']>; /** All values not starting with the given string. */ id_not_starts_with?: Maybe<Scalars['ID']>; /** All values ending with the given string. */ id_ends_with?: Maybe<Scalars['ID']>; /** All values not ending with the given string */ id_not_ends_with?: Maybe<Scalars['ID']>; createdAt?: Maybe<Scalars['DateTime']>; /** All values that are not equal to given value. */ createdAt_not?: Maybe<Scalars['DateTime']>; /** All values that are contained in given list. */ createdAt_in?: Maybe<Array<Scalars['DateTime']>>; /** All values that are not contained in given list. */ createdAt_not_in?: Maybe<Array<Scalars['DateTime']>>; /** All values less than the given value. */ createdAt_lt?: Maybe<Scalars['DateTime']>; /** All values less than or equal the given value. */ createdAt_lte?: Maybe<Scalars['DateTime']>; /** All values greater than the given value. */ createdAt_gt?: Maybe<Scalars['DateTime']>; /** All values greater than or equal the given value. */ createdAt_gte?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; /** All values that are not equal to given value. */ updatedAt_not?: Maybe<Scalars['DateTime']>; /** All values that are contained in given list. */ updatedAt_in?: Maybe<Array<Scalars['DateTime']>>; /** All values that are not contained in given list. */ updatedAt_not_in?: Maybe<Array<Scalars['DateTime']>>; /** All values less than the given value. */ updatedAt_lt?: Maybe<Scalars['DateTime']>; /** All values less than or equal the given value. */ updatedAt_lte?: Maybe<Scalars['DateTime']>; /** All values greater than the given value. */ updatedAt_gt?: Maybe<Scalars['DateTime']>; /** All values greater than or equal the given value. */ updatedAt_gte?: Maybe<Scalars['DateTime']>; publishedAt?: Maybe<Scalars['DateTime']>; /** All values that are not equal to given value. */ publishedAt_not?: Maybe<Scalars['DateTime']>; /** All values that are contained in given list. */ publishedAt_in?: Maybe<Array<Scalars['DateTime']>>; /** All values that are not contained in given list. */ publishedAt_not_in?: Maybe<Array<Scalars['DateTime']>>; /** All values less than the given value. */ publishedAt_lt?: Maybe<Scalars['DateTime']>; /** All values less than or equal the given value. */ publishedAt_lte?: Maybe<Scalars['DateTime']>; /** All values greater than the given value. */ publishedAt_gt?: Maybe<Scalars['DateTime']>; /** All values greater than or equal the given value. */ publishedAt_gte?: Maybe<Scalars['DateTime']>; name?: Maybe<Scalars['String']>; /** All values that are not equal to given value. */ name_not?: Maybe<Scalars['String']>; /** All values that are contained in given list. */ name_in?: Maybe<Array<Scalars['String']>>; /** All values that are not contained in given list. */ name_not_in?: Maybe<Array<Scalars['String']>>; /** All values containing the given string. */ name_contains?: Maybe<Scalars['String']>; /** All values not containing the given string. */ name_not_contains?: Maybe<Scalars['String']>; /** All values starting with the given string. */ name_starts_with?: Maybe<Scalars['String']>; /** All values not starting with the given string. */ name_not_starts_with?: Maybe<Scalars['String']>; /** All values ending with the given string. */ name_ends_with?: Maybe<Scalars['String']>; /** All values not ending with the given string */ name_not_ends_with?: Maybe<Scalars['String']>; comment?: Maybe<Scalars['String']>; /** All values that are not equal to given value. */ comment_not?: Maybe<Scalars['String']>; /** All values that are contained in given list. */ comment_in?: Maybe<Array<Scalars['String']>>; /** All values that are not contained in given list. */ comment_not_in?: Maybe<Array<Scalars['String']>>; /** All values containing the given string. */ comment_contains?: Maybe<Scalars['String']>; /** All values not containing the given string. */ comment_not_contains?: Maybe<Scalars['String']>; /** All values starting with the given string. */ comment_starts_with?: Maybe<Scalars['String']>; /** All values not starting with the given string. */ comment_not_starts_with?: Maybe<Scalars['String']>; /** All values ending with the given string. */ comment_ends_with?: Maybe<Scalars['String']>; /** All values not ending with the given string */ comment_not_ends_with?: Maybe<Scalars['String']>; product?: Maybe<ProductWhereInput>; }; export enum ReviewOrderByInput { IdAsc = 'id_ASC', IdDesc = 'id_DESC', CreatedAtAsc = 'createdAt_ASC', CreatedAtDesc = 'createdAt_DESC', UpdatedAtAsc = 'updatedAt_ASC', UpdatedAtDesc = 'updatedAt_DESC', PublishedAtAsc = 'publishedAt_ASC', PublishedAtDesc = 'publishedAt_DESC', NameAsc = 'name_ASC', NameDesc = 'name_DESC', CommentAsc = 'comment_ASC', CommentDesc = 'comment_DESC' } export type ReviewUpdateInput = { name?: Maybe<Scalars['String']>; comment?: Maybe<Scalars['String']>; product?: Maybe<ProductUpdateOneInlineInput>; }; export type ReviewUpdateManyInlineInput = { /** Create and connect multiple Review documents */ create?: Maybe<Array<ReviewCreateInput>>; /** Connect multiple existing Review documents */ connect?: Maybe<Array<ReviewConnectInput>>; /** Override currently-connected documents with multiple existing Review documents */ set?: Maybe<Array<ReviewWhereUniqueInput>>; /** Update multiple Review documents */ update?: Maybe<Array<ReviewUpdateWithNestedWhereUniqueInput>>; /** Upsert multiple Review documents */ upsert?: Maybe<Array<ReviewUpsertWithNestedWhereUniqueInput>>; /** Disconnect multiple Review documents */ disconnect?: Maybe<Array<ReviewWhereUniqueInput>>; /** Delete multiple Review documents */ delete?: Maybe<Array<ReviewWhereUniqueInput>>; }; export type ReviewUpdateManyInput = { name?: Maybe<Scalars['String']>; comment?: Maybe<Scalars['String']>; }; export type ReviewUpdateManyWithNestedWhereInput = { /** Document search */ where: ReviewWhereInput; /** Update many input */ data: ReviewUpdateManyInput; }; export type ReviewUpdateOneInlineInput = { /** Create and connect one Review document */ create?: Maybe<ReviewCreateInput>; /** Update single Review document */ update?: Maybe<ReviewUpdateWithNestedWhereUniqueInput>; /** Upsert single Review document */ upsert?: Maybe<ReviewUpsertWithNestedWhereUniqueInput>; /** Connect existing Review document */ connect?: Maybe<ReviewWhereUniqueInput>; /** Disconnect currently connected Review document */ disconnect?: Maybe<Scalars['Boolean']>; /** Delete currently connected Review document */ delete?: Maybe<Scalars['Boolean']>; }; export type ReviewUpdateWithNestedWhereUniqueInput = { /** Unique document search */ where: ReviewWhereUniqueInput; /** Document to update */ data: ReviewUpdateInput; }; export type ReviewUpsertInput = { /** Create document if it didn't exist */ create: ReviewCreateInput; /** Update document if it exists */ update: ReviewUpdateInput; }; export type ReviewUpsertWithNestedWhereUniqueInput = { /** Unique document search */ where: ReviewWhereUniqueInput; /** Upsert data */ data: ReviewUpsertInput; }; /** Identifies documents */ export type ReviewWhereInput = { /** Contains search across all appropriate fields. */ _search?: Maybe<Scalars['String']>; /** Logical AND on all given filters. */ AND?: Maybe<Array<ReviewWhereInput>>; /** Logical OR on all given filters. */ OR?: Maybe<Array<ReviewWhereInput>>; /** Logical NOT on all given filters combined by AND. */ NOT?: Maybe<Array<ReviewWhereInput>>; id?: Maybe<Scalars['ID']>; /** All values that are not equal to given value. */ id_not?: Maybe<Scalars['ID']>; /** All values that are contained in given list. */ id_in?: Maybe<Array<Scalars['ID']>>; /** All values that are not contained in given list. */ id_not_in?: Maybe<Array<Scalars['ID']>>; /** All values containing the given string. */ id_contains?: Maybe<Scalars['ID']>; /** All values not containing the given string. */ id_not_contains?: Maybe<Scalars['ID']>; /** All values starting with the given string. */ id_starts_with?: Maybe<Scalars['ID']>; /** All values not starting with the given string. */ id_not_starts_with?: Maybe<Scalars['ID']>; /** All values ending with the given string. */ id_ends_with?: Maybe<Scalars['ID']>; /** All values not ending with the given string */ id_not_ends_with?: Maybe<Scalars['ID']>; createdAt?: Maybe<Scalars['DateTime']>; /** All values that are not equal to given value. */ createdAt_not?: Maybe<Scalars['DateTime']>; /** All values that are contained in given list. */ createdAt_in?: Maybe<Array<Scalars['DateTime']>>; /** All values that are not contained in given list. */ createdAt_not_in?: Maybe<Array<Scalars['DateTime']>>; /** All values less than the given value. */ createdAt_lt?: Maybe<Scalars['DateTime']>; /** All values less than or equal the given value. */ createdAt_lte?: Maybe<Scalars['DateTime']>; /** All values greater than the given value. */ createdAt_gt?: Maybe<Scalars['DateTime']>; /** All values greater than or equal the given value. */ createdAt_gte?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; /** All values that are not equal to given value. */ updatedAt_not?: Maybe<Scalars['DateTime']>; /** All values that are contained in given list. */ updatedAt_in?: Maybe<Array<Scalars['DateTime']>>; /** All values that are not contained in given list. */ updatedAt_not_in?: Maybe<Array<Scalars['DateTime']>>; /** All values less than the given value. */ updatedAt_lt?: Maybe<Scalars['DateTime']>; /** All values less than or equal the given value. */ updatedAt_lte?: Maybe<Scalars['DateTime']>; /** All values greater than the given value. */ updatedAt_gt?: Maybe<Scalars['DateTime']>; /** All values greater than or equal the given value. */ updatedAt_gte?: Maybe<Scalars['DateTime']>; publishedAt?: Maybe<Scalars['DateTime']>; /** All values that are not equal to given value. */ publishedAt_not?: Maybe<Scalars['DateTime']>; /** All values that are contained in given list. */ publishedAt_in?: Maybe<Array<Scalars['DateTime']>>; /** All values that are not contained in given list. */ publishedAt_not_in?: Maybe<Array<Scalars['DateTime']>>; /** All values less than the given value. */ publishedAt_lt?: Maybe<Scalars['DateTime']>; /** All values less than or equal the given value. */ publishedAt_lte?: Maybe<Scalars['DateTime']>; /** All values greater than the given value. */ publishedAt_gt?: Maybe<Scalars['DateTime']>; /** All values greater than or equal the given value. */ publishedAt_gte?: Maybe<Scalars['DateTime']>; name?: Maybe<Scalars['String']>; /** All values that are not equal to given value. */ name_not?: Maybe<Scalars['String']>; /** All values that are contained in given list. */ name_in?: Maybe<Array<Scalars['String']>>; /** All values that are not contained in given list. */ name_not_in?: Maybe<Array<Scalars['String']>>; /** All values containing the given string. */ name_contains?: Maybe<Scalars['String']>; /** All values not containing the given string. */ name_not_contains?: Maybe<Scalars['String']>; /** All values starting with the given string. */ name_starts_with?: Maybe<Scalars['String']>; /** All values not starting with the given string. */ name_not_starts_with?: Maybe<Scalars['String']>; /** All values ending with the given string. */ name_ends_with?: Maybe<Scalars['String']>; /** All values not ending with the given string */ name_not_ends_with?: Maybe<Scalars['String']>; comment?: Maybe<Scalars['String']>; /** All values that are not equal to given value. */ comment_not?: Maybe<Scalars['String']>; /** All values that are contained in given list. */ comment_in?: Maybe<Array<Scalars['String']>>; /** All values that are not contained in given list. */ comment_not_in?: Maybe<Array<Scalars['String']>>; /** All values containing the given string. */ comment_contains?: Maybe<Scalars['String']>; /** All values not containing the given string. */ comment_not_contains?: Maybe<Scalars['String']>; /** All values starting with the given string. */ comment_starts_with?: Maybe<Scalars['String']>; /** All values not starting with the given string. */ comment_not_starts_with?: Maybe<Scalars['String']>; /** All values ending with the given string. */ comment_ends_with?: Maybe<Scalars['String']>; /** All values not ending with the given string */ comment_not_ends_with?: Maybe<Scalars['String']>; product?: Maybe<ProductWhereInput>; }; /** References Review record uniquely */ export type ReviewWhereUniqueInput = { id?: Maybe<Scalars['ID']>; }; /** Custom type representing a rich text value comprising of raw rich text ast, html, markdown and text values */ export type RichText = { __typename?: 'RichText'; /** Returns AST representation */ raw: Scalars['RichTextAST']; /** Returns HTMl representation */ html: Scalars['String']; /** Returns Markdown representation */ markdown: Scalars['String']; /** Returns plain-text contents of RichText */ text: Scalars['String']; }; /** Stage system enumeration */ export enum Stage { /** The Published stage is where you can publish your content to. */ Published = 'PUBLISHED', /** The Draft is the default stage for all your content. */ Draft = 'DRAFT' } export enum SystemDateTimeFieldVariation { Base = 'BASE', Localization = 'LOCALIZATION', Combined = 'COMBINED' } export type UnpublishLocaleInput = { /** Locales to unpublish */ locale: Locale; /** Stages to unpublish selected locales from */ stages: Array<Stage>; }; /** System User Kind */ export enum UserKind { Member = 'MEMBER', Pat = 'PAT', Public = 'PUBLIC', Webhook = 'WEBHOOK' } export type Version = { __typename?: 'Version'; id: Scalars['ID']; stage: Stage; revision: Scalars['Int']; createdAt: Scalars['DateTime']; }; export type VersionWhereInput = { id: Scalars['ID']; stage: Stage; revision: Scalars['Int']; }; export type Vote = Node & { __typename?: 'Vote'; /** System stage field */ stage: Stage; /** Get the document in other stages */ documentInStages: Array<Vote>; /** The unique identifier */ id: Scalars['ID']; /** The time the document was created */ createdAt: Scalars['DateTime']; /** The time the document was updated */ updatedAt: Scalars['DateTime']; /** The time the document was published. Null on documents in draft stage. */ publishedAt?: Maybe<Scalars['DateTime']>; product?: Maybe<Product>; /** List of Vote versions */ history: Array<Version>; }; export type VoteDocumentInStagesArgs = { stages?: Array<Stage>; includeCurrent?: Scalars['Boolean']; inheritLocale?: Scalars['Boolean']; }; export type VoteProductArgs = { locales?: Maybe<Array<Locale>>; }; export type VoteHistoryArgs = { limit?: Scalars['Int']; skip?: Scalars['Int']; stageOverride?: Maybe<Stage>; }; export type VoteConnectInput = { /** Document to connect */ where: VoteWhereUniqueInput; /** Allow to specify document position in list of connected documents, will default to appending at end of list */ position?: Maybe<ConnectPositionInput>; }; /** A connection to a list of items. */ export type VoteConnection = { __typename?: 'VoteConnection'; /** Information to aid in pagination. */ pageInfo: PageInfo; /** A list of edges. */ edges: Array<VoteEdge>; aggregate: Aggregate; }; export type VoteCreateInput = { createdAt?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; product?: Maybe<ProductCreateOneInlineInput>; }; export type VoteCreateManyInlineInput = { /** Create and connect multiple existing Vote documents */ create?: Maybe<Array<VoteCreateInput>>; /** Connect multiple existing Vote documents */ connect?: Maybe<Array<VoteWhereUniqueInput>>; }; export type VoteCreateOneInlineInput = { /** Create and connect one Vote document */ create?: Maybe<VoteCreateInput>; /** Connect one existing Vote document */ connect?: Maybe<VoteWhereUniqueInput>; }; /** An edge in a connection. */ export type VoteEdge = { __typename?: 'VoteEdge'; /** The item at the end of the edge. */ node: Vote; /** A cursor for use in pagination. */ cursor: Scalars['String']; }; /** Identifies documents */ export type VoteManyWhereInput = { /** Contains search across all appropriate fields. */ _search?: Maybe<Scalars['String']>; /** Logical AND on all given filters. */ AND?: Maybe<Array<VoteWhereInput>>; /** Logical OR on all given filters. */ OR?: Maybe<Array<VoteWhereInput>>; /** Logical NOT on all given filters combined by AND. */ NOT?: Maybe<Array<VoteWhereInput>>; id?: Maybe<Scalars['ID']>; /** All values that are not equal to given value. */ id_not?: Maybe<Scalars['ID']>; /** All values that are contained in given list. */ id_in?: Maybe<Array<Scalars['ID']>>; /** All values that are not contained in given list. */ id_not_in?: Maybe<Array<Scalars['ID']>>; /** All values containing the given string. */ id_contains?: Maybe<Scalars['ID']>; /** All values not containing the given string. */ id_not_contains?: Maybe<Scalars['ID']>; /** All values starting with the given string. */ id_starts_with?: Maybe<Scalars['ID']>; /** All values not starting with the given string. */ id_not_starts_with?: Maybe<Scalars['ID']>; /** All values ending with the given string. */ id_ends_with?: Maybe<Scalars['ID']>; /** All values not ending with the given string */ id_not_ends_with?: Maybe<Scalars['ID']>; createdAt?: Maybe<Scalars['DateTime']>; /** All values that are not equal to given value. */ createdAt_not?: Maybe<Scalars['DateTime']>; /** All values that are contained in given list. */ createdAt_in?: Maybe<Array<Scalars['DateTime']>>; /** All values that are not contained in given list. */ createdAt_not_in?: Maybe<Array<Scalars['DateTime']>>; /** All values less than the given value. */ createdAt_lt?: Maybe<Scalars['DateTime']>; /** All values less than or equal the given value. */ createdAt_lte?: Maybe<Scalars['DateTime']>; /** All values greater than the given value. */ createdAt_gt?: Maybe<Scalars['DateTime']>; /** All values greater than or equal the given value. */ createdAt_gte?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; /** All values that are not equal to given value. */ updatedAt_not?: Maybe<Scalars['DateTime']>; /** All values that are contained in given list. */ updatedAt_in?: Maybe<Array<Scalars['DateTime']>>; /** All values that are not contained in given list. */ updatedAt_not_in?: Maybe<Array<Scalars['DateTime']>>; /** All values less than the given value. */ updatedAt_lt?: Maybe<Scalars['DateTime']>; /** All values less than or equal the given value. */ updatedAt_lte?: Maybe<Scalars['DateTime']>; /** All values greater than the given value. */ updatedAt_gt?: Maybe<Scalars['DateTime']>; /** All values greater than or equal the given value. */ updatedAt_gte?: Maybe<Scalars['DateTime']>; publishedAt?: Maybe<Scalars['DateTime']>; /** All values that are not equal to given value. */ publishedAt_not?: Maybe<Scalars['DateTime']>; /** All values that are contained in given list. */ publishedAt_in?: Maybe<Array<Scalars['DateTime']>>; /** All values that are not contained in given list. */ publishedAt_not_in?: Maybe<Array<Scalars['DateTime']>>; /** All values less than the given value. */ publishedAt_lt?: Maybe<Scalars['DateTime']>; /** All values less than or equal the given value. */ publishedAt_lte?: Maybe<Scalars['DateTime']>; /** All values greater than the given value. */ publishedAt_gt?: Maybe<Scalars['DateTime']>; /** All values greater than or equal the given value. */ publishedAt_gte?: Maybe<Scalars['DateTime']>; product?: Maybe<ProductWhereInput>; }; export enum VoteOrderByInput { IdAsc = 'id_ASC', IdDesc = 'id_DESC', CreatedAtAsc = 'createdAt_ASC', CreatedAtDesc = 'createdAt_DESC', UpdatedAtAsc = 'updatedAt_ASC', UpdatedAtDesc = 'updatedAt_DESC', PublishedAtAsc = 'publishedAt_ASC', PublishedAtDesc = 'publishedAt_DESC' } export type VoteUpdateInput = { product?: Maybe<ProductUpdateOneInlineInput>; }; export type VoteUpdateManyInlineInput = { /** Create and connect multiple Vote documents */ create?: Maybe<Array<VoteCreateInput>>; /** Connect multiple existing Vote documents */ connect?: Maybe<Array<VoteConnectInput>>; /** Override currently-connected documents with multiple existing Vote documents */ set?: Maybe<Array<VoteWhereUniqueInput>>; /** Update multiple Vote documents */ update?: Maybe<Array<VoteUpdateWithNestedWhereUniqueInput>>; /** Upsert multiple Vote documents */ upsert?: Maybe<Array<VoteUpsertWithNestedWhereUniqueInput>>; /** Disconnect multiple Vote documents */ disconnect?: Maybe<Array<VoteWhereUniqueInput>>; /** Delete multiple Vote documents */ delete?: Maybe<Array<VoteWhereUniqueInput>>; }; export type VoteUpdateManyInput = { /** No fields in updateMany data input */ _?: Maybe<Scalars['String']>; }; export type VoteUpdateManyWithNestedWhereInput = { /** Document search */ where: VoteWhereInput; /** Update many input */ data: VoteUpdateManyInput; }; export type VoteUpdateOneInlineInput = { /** Create and connect one Vote document */ create?: Maybe<VoteCreateInput>; /** Update single Vote document */ update?: Maybe<VoteUpdateWithNestedWhereUniqueInput>; /** Upsert single Vote document */ upsert?: Maybe<VoteUpsertWithNestedWhereUniqueInput>; /** Connect existing Vote document */ connect?: Maybe<VoteWhereUniqueInput>; /** Disconnect currently connected Vote document */ disconnect?: Maybe<Scalars['Boolean']>; /** Delete currently connected Vote document */ delete?: Maybe<Scalars['Boolean']>; }; export type VoteUpdateWithNestedWhereUniqueInput = { /** Unique document search */ where: VoteWhereUniqueInput; /** Document to update */ data: VoteUpdateInput; }; export type VoteUpsertInput = { /** Create document if it didn't exist */ create: VoteCreateInput; /** Update document if it exists */ update: VoteUpdateInput; }; export type VoteUpsertWithNestedWhereUniqueInput = { /** Unique document search */ where: VoteWhereUniqueInput; /** Upsert data */ data: VoteUpsertInput; }; /** Identifies documents */ export type VoteWhereInput = { /** Contains search across all appropriate fields. */ _search?: Maybe<Scalars['String']>; /** Logical AND on all given filters. */ AND?: Maybe<Array<VoteWhereInput>>; /** Logical OR on all given filters. */ OR?: Maybe<Array<VoteWhereInput>>; /** Logical NOT on all given filters combined by AND. */ NOT?: Maybe<Array<VoteWhereInput>>; id?: Maybe<Scalars['ID']>; /** All values that are not equal to given value. */ id_not?: Maybe<Scalars['ID']>; /** All values that are contained in given list. */ id_in?: Maybe<Array<Scalars['ID']>>; /** All values that are not contained in given list. */ id_not_in?: Maybe<Array<Scalars['ID']>>; /** All values containing the given string. */ id_contains?: Maybe<Scalars['ID']>; /** All values not containing the given string. */ id_not_contains?: Maybe<Scalars['ID']>; /** All values starting with the given string. */ id_starts_with?: Maybe<Scalars['ID']>; /** All values not starting with the given string. */ id_not_starts_with?: Maybe<Scalars['ID']>; /** All values ending with the given string. */ id_ends_with?: Maybe<Scalars['ID']>; /** All values not ending with the given string */ id_not_ends_with?: Maybe<Scalars['ID']>; createdAt?: Maybe<Scalars['DateTime']>; /** All values that are not equal to given value. */ createdAt_not?: Maybe<Scalars['DateTime']>; /** All values that are contained in given list. */ createdAt_in?: Maybe<Array<Scalars['DateTime']>>; /** All values that are not contained in given list. */ createdAt_not_in?: Maybe<Array<Scalars['DateTime']>>; /** All values less than the given value. */ createdAt_lt?: Maybe<Scalars['DateTime']>; /** All values less than or equal the given value. */ createdAt_lte?: Maybe<Scalars['DateTime']>; /** All values greater than the given value. */ createdAt_gt?: Maybe<Scalars['DateTime']>; /** All values greater than or equal the given value. */ createdAt_gte?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; /** All values that are not equal to given value. */ updatedAt_not?: Maybe<Scalars['DateTime']>; /** All values that are contained in given list. */ updatedAt_in?: Maybe<Array<Scalars['DateTime']>>; /** All values that are not contained in given list. */ updatedAt_not_in?: Maybe<Array<Scalars['DateTime']>>; /** All values less than the given value. */ updatedAt_lt?: Maybe<Scalars['DateTime']>; /** All values less than or equal the given value. */ updatedAt_lte?: Maybe<Scalars['DateTime']>; /** All values greater than the given value. */ updatedAt_gt?: Maybe<Scalars['DateTime']>; /** All values greater than or equal the given value. */ updatedAt_gte?: Maybe<Scalars['DateTime']>; publishedAt?: Maybe<Scalars['DateTime']>; /** All values that are not equal to given value. */ publishedAt_not?: Maybe<Scalars['DateTime']>; /** All values that are contained in given list. */ publishedAt_in?: Maybe<Array<Scalars['DateTime']>>; /** All values that are not contained in given list. */ publishedAt_not_in?: Maybe<Array<Scalars['DateTime']>>; /** All values less than the given value. */ publishedAt_lt?: Maybe<Scalars['DateTime']>; /** All values less than or equal the given value. */ publishedAt_lte?: Maybe<Scalars['DateTime']>; /** All values greater than the given value. */ publishedAt_gt?: Maybe<Scalars['DateTime']>; /** All values greater than or equal the given value. */ publishedAt_gte?: Maybe<Scalars['DateTime']>; product?: Maybe<ProductWhereInput>; }; /** References Vote record uniquely */ export type VoteWhereUniqueInput = { id?: Maybe<Scalars['ID']>; }; export enum _FilterKind { Search = 'search', And = 'AND', Or = 'OR', Not = 'NOT', Eq = 'eq', EqNot = 'eq_not', In = 'in', NotIn = 'not_in', Lt = 'lt', Lte = 'lte', Gt = 'gt', Gte = 'gte', Contains = 'contains', NotContains = 'not_contains', StartsWith = 'starts_with', NotStartsWith = 'not_starts_with', EndsWith = 'ends_with', NotEndsWith = 'not_ends_with', ContainsAll = 'contains_all', ContainsSome = 'contains_some', ContainsNone = 'contains_none', RelationalSingle = 'relational_single', RelationalEvery = 'relational_every', RelationalSome = 'relational_some', RelationalNone = 'relational_none' } export enum _MutationInputFieldKind { Scalar = 'scalar', RichText = 'richText', RichTextWithEmbeds = 'richTextWithEmbeds', Enum = 'enum', Relation = 'relation', Union = 'union', Virtual = 'virtual' } export enum _MutationKind { Create = 'create', Publish = 'publish', Unpublish = 'unpublish', Update = 'update', Upsert = 'upsert', Delete = 'delete', UpdateMany = 'updateMany', PublishMany = 'publishMany', UnpublishMany = 'unpublishMany', DeleteMany = 'deleteMany' } export enum _OrderDirection { Asc = 'asc', Desc = 'desc' } export enum _RelationInputCardinality { One = 'one', Many = 'many' } export enum _RelationInputKind { Create = 'create', Update = 'update' } export enum _RelationKind { Regular = 'regular', Union = 'union' } export enum _SystemDateTimeFieldVariation { Base = 'base', Localization = 'localization', Combined = 'combined' } export type AllProductsQueryVariables = Exact<{ orderBy?: Maybe<ProductOrderByInput>; first?: Maybe<Scalars['Int']>; skip?: Maybe<Scalars['Int']>; where?: Maybe<ProductWhereInput>; }>; export type AllProductsQuery = ( { __typename?: 'Query' } & { products: Array<( { __typename?: 'Product' } & ProductSummaryFragment )> } ); export type ProductSummaryFragment = ( { __typename?: 'Product' } & Pick<Product, 'id' | 'name' | 'slug' | 'description' | 'publishedAt'> ); export const ProductSummaryFragmentDoc = gql` fragment ProductSummary on Product { id name slug description publishedAt } `; export const AllProductsDocument = gql` query allProducts($orderBy: ProductOrderByInput, $first: Int, $skip: Int, $where: ProductWhereInput) { products(orderBy: $orderBy, first: $first, skip: $skip, where: $where) { ...ProductSummary } } ${ProductSummaryFragmentDoc}`; /** * __useAllProductsQuery__ * * To run a query within a React component, call `useAllProductsQuery` and pass it any options that fit your needs. * When your component renders, `useAllProductsQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useAllProductsQuery({ * variables: { * orderBy: // value for 'orderBy' * first: // value for 'first' * skip: // value for 'skip' * where: // value for 'where' * }, * }); */ export function useAllProductsQuery(baseOptions?: Apollo.QueryHookOptions<AllProductsQuery, AllProductsQueryVariables>) { return Apollo.useQuery<AllProductsQuery, AllProductsQueryVariables>(AllProductsDocument, baseOptions); } export function useAllProductsLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<AllProductsQuery, AllProductsQueryVariables>) { return Apollo.useLazyQuery<AllProductsQuery, AllProductsQueryVariables>(AllProductsDocument, baseOptions); } export type AllProductsQueryHookResult = ReturnType<typeof useAllProductsQuery>; export type AllProductsLazyQueryHookResult = ReturnType<typeof useAllProductsLazyQuery>; export type AllProductsQueryResult = Apollo.QueryResult<AllProductsQuery, AllProductsQueryVariables>; export interface PossibleTypesResultData { possibleTypes: { [key: string]: string[] } } const result: PossibleTypesResultData = { "possibleTypes": { "Node": [ "Asset", "Product", "Review", "Vote" ] } }; export default result;
the_stack
import SwaggerParser from '@apidevtools/swagger-parser' import fs from 'fs-extra' import { OpenAPIV3 } from 'openapi-types' import { CollectionDefinition } from 'postman-collection' import * as mockOAS from '../../__tests__/fixtures/mockOAS.json' import * as mockPostman from '../../__tests__/fixtures/mockPostman.json' import { IntegrationTestWriter, VariationWriter } from '../application' import { TestSuite } from '../application/TestSuite' import * as configLoader from '../lib/getConfig' import { OpenApiParser } from '../oas' import { Portman } from '../Portman' import { PostmanParser } from '../postman' import { OpenApiToPostmanService } from '../services' import { PortmanOptions } from '../types' import { omitKeys } from '../utils' import * as validateJsonSchema from '../utils/PortmanConfig.validator' // eslint-disable-next-line @typescript-eslint/no-explicit-any const portmanResult = (collection: CollectionDefinition): any => { return JSON.parse(JSON.stringify(collection)) } const mockPostmanSync = jest.fn(() => Promise.resolve(JSON.stringify({ status: 'success', data: {} })) ) jest.mock('../services/PostmanSyncService', () => { return { PostmanSyncService: jest.fn().mockImplementation(() => { return { sync: mockPostmanSync } }) } }) afterAll(() => { jest.restoreAllMocks() }) describe('Portman', () => { let options: PortmanOptions = {} beforeEach(async () => { /* eslint-disable @typescript-eslint/no-empty-function */ jest.spyOn(global.console, 'log').mockImplementation(() => {}) /* eslint-disable @typescript-eslint/no-empty-function */ jest.spyOn(global.console, 'error').mockImplementation(() => {}) // eslint-disable-next-line @typescript-eslint/no-unused-vars jest.spyOn(process, 'exit').mockImplementation(() => { return undefined as never }) // mock conversions jest .spyOn(SwaggerParser.prototype, 'dereference') .mockImplementation(() => Promise.resolve(mockOAS as OpenAPIV3.Document)) jest .spyOn(SwaggerParser.prototype, 'bundle') .mockImplementation(() => Promise.resolve(mockOAS as OpenAPIV3.Document)) jest .spyOn(OpenApiToPostmanService.prototype, 'convert') .mockImplementation(() => Promise.resolve(mockPostman)) options = { postmanUid: 'eb1ffad6-eece-456b-ad32-3f2a3f605537', oaLocal: './__tests__/fixtures/crm.yml', postmanConfigFile: './__tests__/fixtures/postman-config.json', portmanConfigFile: './__tests__/fixtures/portman.crm.json', portmanConfigPath: './__tests__/fixtures/portman.crm.json', envFile: './__tests__/fixtures/.crm.env', baseUrl: 'http://localhost:3050', syncPostman: false, includeTests: true, runNewman: false } }) afterAll(() => { jest.restoreAllMocks() }) afterEach(() => { jest.clearAllMocks() }) it('should be a function', () => { expect(Portman).toBeInstanceOf(Function) }) it('should return a Portman instance', () => { const portman = new Portman(options) expect(portman).toBeInstanceOf(Portman) }) it('should return a Portman instance with default options', () => { const portman = new Portman({}) expect(portman).toBeInstanceOf(Portman) }) describe('Portman.run()', () => { it('should be a function', () => { const portman = new Portman(options) expect(portman.run).toBeInstanceOf(Function) }) }) describe('Portman.before()', () => { it('should be a function', () => { const portman = new Portman(options) expect(portman.before).toBeInstanceOf(Function) }) it('should get called when calling run', async () => { const portman = new Portman(options) const spy = jest.spyOn(portman, 'before') await portman.run() expect(spy).toHaveBeenCalled() }) it('should load config file with getConfig()', async () => { const portman = new Portman(options) const spy = jest.spyOn(configLoader, 'getConfig') await portman.run() expect(spy).toHaveBeenCalled() }) it('should validate config file with validateJsonSchema()', async () => { const portman = new Portman(options) const spy = jest.spyOn(validateJsonSchema, 'validate') await portman.run() expect(spy).toHaveBeenCalled() }) }) describe('Portman.parseOpenApiSpec()', () => { it('should be a function', () => { const portman = new Portman(options) expect(portman.parseOpenApiSpec).toBeInstanceOf(Function) }) it('should throw an error when no spec is passed', async () => { const portman = new Portman({ portmanConfigFile: './__tests__/fixtures/portman.crm.json' }) await expect(portman.parseOpenApiSpec()).rejects.toThrow('Error initializing OpenApi Spec.') }) it('should throw an error when spec path does not exist', async () => { const portman = new Portman({ oaLocal: './__tests__/fixtures/not_a_spec.yml' }) await expect(portman.parseOpenApiSpec()).rejects.toThrow('Error initializing OpenApi Spec.') }) it('should parse OpenAPI spec and define an OpenApiParser', async () => { const portman = new Portman(options) const spy = jest.spyOn(portman, 'parseOpenApiSpec') await portman.run() expect(spy).toHaveBeenCalled() expect(portman.oasParser).toBeDefined() expect(portman.oasParser).toBeInstanceOf(OpenApiParser) }) }) describe('Portman.convertToPostmanCollection()', () => { it('should be a function', () => { const portman = new Portman(options) expect(portman.convertToPostmanCollection).toBeInstanceOf(Function) }) it('should convert OpenAPI spec to Postman collection', async () => { const portman = new Portman(options) const spy = jest.spyOn(portman, 'convertToPostmanCollection') await portman.run() expect(spy).toHaveBeenCalled() expect(portman.postmanParser).toBeDefined() expect(portman.postmanParser).toBeInstanceOf(PostmanParser) }) it('should call Portman.runPortmanOverrides', async () => { const portman = new Portman(options) const spy = jest.spyOn(portman, 'runPortmanOverrides') await portman.run() expect(spy).toHaveBeenCalled() expect(portman.portmanCollection).toBeDefined() }) }) describe('Portman.injectTestSuite()', () => { it('should be a function', () => { const portman = new Portman(options) expect(portman.injectTestSuite).toBeInstanceOf(Function) }) it('should inject test suite into Postman collection', async () => { const portman = new Portman(options) const spy = jest.spyOn(portman, 'injectTestSuite') await portman.run() expect(spy).toHaveBeenCalled() expect(portman.testSuite).toBeDefined() expect(portman.testSuite).toBeInstanceOf(TestSuite) expect(omitKeys(portman.testSuite.requestTestTypes, ['postmanItemId'])).toMatchSnapshot() }) }) describe('Portman.injectVariationTests()', () => { it('should be a function', () => { const portman = new Portman(options) expect(portman.injectVariationTests).toBeInstanceOf(Function) }) it('should inject variation tests into Postman collection', async () => { const portman = new Portman(options) const spy = jest.spyOn(portman, 'injectVariationTests') await portman.run() expect(spy).toHaveBeenCalled() expect(portman.variationWriter).toBeDefined() expect(portman.variationWriter).toBeInstanceOf(VariationWriter) expect(portman.variationWriter.variationFolder.name).toMatchSnapshot() expect( portmanResult(portman.portmanCollection).item.find( item => item.name === 'Integration Tests' ) ).toBeDefined() }) }) describe('Portman.injectVariationOverwrites()', () => { it('should be a function', () => { const portman = new Portman(options) expect(portman.injectVariationOverwrites).toBeInstanceOf(Function) }) it('should inject variation overwrites into Postman collection', async () => { const portman = new Portman(options) const spy = jest.spyOn(portman, 'injectVariationOverwrites') await portman.run() expect(spy).toHaveBeenCalled() expect(portman.integrationTestWriter).toBeDefined() expect(portman.integrationTestWriter).toBeInstanceOf(IntegrationTestWriter) expect(portman.integrationTestWriter.integrationTestFolder.name).toMatchSnapshot() expect( portmanResult(portman.portmanCollection).item.find( item => item.name === 'Integration Tests' ) ).toBeDefined() }) }) describe('Portman.runPortmanOverrides()', () => { it('should be a function', () => { const portman = new Portman(options) expect(portman.runPortmanOverrides).toBeInstanceOf(Function) }) it('should run portman overrides', async () => { const portman = new Portman(options) const spy = jest.spyOn(portman, 'runPortmanOverrides') await portman.run() expect(spy).toHaveBeenCalled() }) }) describe('Portman.moveContractTestsToFolder()', () => { it('should be a function', () => { const portman = new Portman(options) expect(portman.moveContractTestsToFolder).toBeInstanceOf(Function) }) it('should be called when bundleContractTests true', async () => { const portman = new Portman({ ...options, bundleContractTests: true }) const spy = jest.spyOn(portman, 'moveContractTestsToFolder') await portman.run() expect(spy).toHaveBeenCalled() expect( portmanResult(portman.portmanCollection).item.find(item => item.name === 'Contract Tests') ).toBeDefined() }) }) describe('Portman.writePortmanCollectionToFile()', () => { const jestCollectionFile = './tmp/jest-collection.json' it('should be a function', () => { const portman = new Portman(options) expect(portman.writePortmanCollectionToFile).toBeInstanceOf(Function) }) it('should write portman collection to file', async () => { try { await fs.rm(jestCollectionFile) } catch (e) { // ignore } expect(await fs.pathExists(jestCollectionFile)).toBe(false) const portman = new Portman({ ...options, output: jestCollectionFile }) const spy = jest.spyOn(portman, 'writePortmanCollectionToFile') await portman.run() expect(spy).toHaveBeenCalled() expect(portman.portmanCollection).toBeDefined() expect(portman.collectionFile).toBe(jestCollectionFile) expect(await fs.pathExists(jestCollectionFile)).toBe(true) }) }) describe('Portman.runNewmanSuite()', () => { it('should be a function', () => { const portman = new Portman(options) expect(portman.runNewmanSuite).toBeInstanceOf(Function) }) it('should run newman suite', async () => { const portman = new Portman(options) const spy = jest.spyOn(portman, 'runNewmanSuite') await portman.run() expect(spy).toHaveBeenCalled() }) }) describe('Portman.syncCollectionToPostman()', () => { it('should be a function', () => { const portman = new Portman(options) expect(portman.syncCollectionToPostman).toBeInstanceOf(Function) }) it('should sync collection to postman', async () => { const portman = new Portman(options) const spy = jest.spyOn(portman, 'syncCollectionToPostman') await portman.run() expect(spy).toHaveBeenCalled() }) it('should call PostmanSyncService.sync when syncPostman is true', async () => { const portman = new Portman({ ...options, syncPostman: true }) await portman.run() expect(portman.postmanSyncService).toBeDefined() expect(mockPostmanSync).toHaveBeenCalled() }) }) describe('Portman.after()', () => { it('should be a function', () => { const portman = new Portman(options) expect(portman.after).toBeInstanceOf(Function) }) it('should run after hook', async () => { const portman = new Portman(options) const spy = jest.spyOn(portman, 'after') await portman.run() expect(spy).toHaveBeenCalled() }) }) })
the_stack
import * as React from "react"; import { useCallback, useLayoutEffect, useMemo } from "react"; import { Column, ColumnInstance, DataRecord } from "react-table"; import "@kogito-tooling/boxed-expression-component"; import { ColumnsUpdateArgs, ExpressionProps, GroupOperations, RowsUpdateArgs, TableHeaderVisibility, TableOperation, } from "@kogito-tooling/boxed-expression-component/dist/api"; import { getColumnsAtLastLevel, Table } from "@kogito-tooling/boxed-expression-component/dist/components"; import "./DmnRunnerTable.css"; import { DmnRunnerClause, DmnRunnerRule } from "./DmnRunnerTableTypes"; import { useDmnAutoTableI18n } from "../i18n"; enum DecisionTableColumnType { InputClause = "input", OutputClause = "output", Annotation = "annotation", } const DASH_SYMBOL = "-"; const EMPTY_SYMBOL = ""; export interface DmnRunnerTableProps extends ExpressionProps { /** Input columns definition */ input?: DmnRunnerClause[]; /** Output columns definition */ output?: DmnRunnerClause[]; /** Rules represent rows values */ rules?: DmnRunnerRule[]; /** Callback to be called when row number is updated */ onRowNumberUpdated: (rowNumber: number, operation?: TableOperation, updatedRowIndex?: number) => void; onColumnsUpdate: (columns: Column[]) => void; } export function DmnRunnerTable(props: DmnRunnerTableProps) { const { i18n } = useDmnAutoTableI18n(); const getColumnPrefix = useCallback((groupType?: string) => { switch (groupType) { case DecisionTableColumnType.InputClause: return "input-"; case DecisionTableColumnType.OutputClause: return "output-"; default: return "column-"; } }, []); const generateHandlerConfigurationByColumn = useMemo( () => [ { group: i18n.decisionRule, items: [ { name: i18n.rowOperations.insertAbove, type: TableOperation.RowInsertAbove }, { name: i18n.rowOperations.insertBelow, type: TableOperation.RowInsertBelow }, { name: i18n.rowOperations.duplicate, type: TableOperation.RowDuplicate }, { name: i18n.rowOperations.clear, type: TableOperation.RowClear }, { name: i18n.rowOperations.delete, type: TableOperation.RowDelete }, ], }, ], [i18n] ); const getHandlerConfiguration = useMemo(() => { const configuration: { [columnGroupType: string]: GroupOperations[] } = {}; configuration[EMPTY_SYMBOL] = generateHandlerConfigurationByColumn; configuration[DecisionTableColumnType.InputClause] = generateHandlerConfigurationByColumn; configuration[DecisionTableColumnType.OutputClause] = generateHandlerConfigurationByColumn; return configuration; }, [generateHandlerConfigurationByColumn]); const getEditColumnLabel = useMemo(() => { const editColumnLabel: { [columnGroupType: string]: string } = {}; editColumnLabel[DecisionTableColumnType.InputClause] = i18n.editClause.input; editColumnLabel[DecisionTableColumnType.OutputClause] = i18n.editClause.output; return editColumnLabel; }, [i18n.editClause.input, i18n.editClause.output]); const columns = useMemo(() => { const inputSection = (props.input ?? []).map((inputClause) => { if (inputClause.insideProperties) { const insideProperties = inputClause.insideProperties.map((insideInputClauses) => { return { label: insideInputClauses.name, accessor: `input-${insideInputClauses.name}`, dataType: insideInputClauses.dataType, width: insideInputClauses.width, groupType: DecisionTableColumnType.InputClause, cellDelegate: insideInputClauses.cellDelegate, }; }); return { groupType: DecisionTableColumnType.InputClause, label: inputClause.name, accessor: `input-${inputClause.name}`, dataType: inputClause.dataType, width: inputClause.width, cssClasses: "decision-table--input", columns: insideProperties, appendColumnsOnChildren: true, }; } return { groupType: DecisionTableColumnType.InputClause, label: inputClause.name, accessor: `input-${inputClause.name}`, dataType: inputClause.dataType, width: inputClause.width, cssClasses: "decision-table--input", appendColumnsOnChildren: true, cellDelegate: inputClause.cellDelegate, }; }); let outputSection = undefined; if (props.output !== undefined) { outputSection = (props.rules?.[0]?.outputEntries ?? []).map((outputEntry, outputIndex) => { if (Array.isArray(outputEntry)) { return outputEntry.map((entry, entryIndex) => { const columns = Object.keys(entry).map((keys) => { return { groupType: DecisionTableColumnType.OutputClause, label: `${keys}`, accessor: `output-${keys}-${entryIndex}`, cssClasses: "decision-table--output", } as ColumnInstance; }); return { groupType: DecisionTableColumnType.OutputClause, label: `${props.output?.[outputIndex]?.name}[${entryIndex}]`, accessor: `output-${props.output?.[outputIndex]?.name}[${entryIndex}]`, cssClasses: "decision-table--output", columns: columns, appendColumnsOnChildren: true, dataType: props.output?.[outputIndex]?.dataType, } as ColumnInstance; }); } if (outputEntry !== null && typeof outputEntry === "object") { const columns = Object.keys(outputEntry).map((entryKey) => { const output = props.output?.[outputIndex]?.insideProperties?.find((property) => { return Object.values(property).find((value) => { return value === entryKey; }); }); return { groupType: DecisionTableColumnType.OutputClause, label: entryKey, width: output.width, accessor: `output-${entryKey}`, cssClasses: "decision-table--output", } as ColumnInstance; }); const width = columns.reduce((acc, column) => acc + (column.width as number), 0) + 2.22 * (columns.length - 1); return [ { groupType: DecisionTableColumnType.OutputClause, label: props.output?.[outputIndex]?.name, accessor: `output-${props.output?.[outputIndex]?.name}`, cssClasses: "decision-table--output", columns: columns, width, appendColumnsOnChildren: true, dataType: props.output?.[outputIndex]?.dataType, } as ColumnInstance, ]; } return [ { groupType: DecisionTableColumnType.OutputClause, label: props.output?.[outputIndex]?.name, accessor: `output-${props.output?.[outputIndex]?.name}`, dataType: props.output?.[outputIndex]?.dataType, width: props.output?.[outputIndex]?.width, cssClasses: "decision-table--output", appendColumnsOnChildren: true, }, ]; }); } const updatedColumns: ColumnInstance[] = []; if (inputSection) { updatedColumns.push(...(inputSection as any)); } if (outputSection) { const flattenOutput = outputSection.reduce((acc, outp) => [...acc, ...outp], []); updatedColumns.push(...(flattenOutput as any)); } return updatedColumns; }, [props.input, props.output, props.rules]); const rows = useMemo(() => { return (props.rules ?? []).map((rule) => { const rowArray = [...(rule?.inputEntries ?? []), ...(rule?.outputEntries ?? [])].reduce((acc, entry) => { if (Array.isArray(entry)) { return [ ...acc, ...entry.flatMap((entryElement) => typeof entryElement === "object" ? [...Object.values(entryElement)] : entryElement ), ]; } if (typeof entry === "object") { return [...acc, ...Object.values(entry)]; } return [...acc, entry]; }, []); return getColumnsAtLastLevel(columns).reduce((tableRow: any, column, columnIndex: number) => { tableRow[column.accessor] = rowArray[columnIndex] || EMPTY_SYMBOL; tableRow.rowDelegate = rule.rowDelegate; return tableRow; }, {}); }); }, [props.rules, columns]); const onRowsUpdate = useCallback( ({ rows, operation, rowIndex }: RowsUpdateArgs) => { const newRows = rows.map((row: any) => getColumnsAtLastLevel(columns).reduce((filledRow: DataRecord, column) => { if (row.rowDelegate) { filledRow[column.accessor] = row[column.accessor]; filledRow.rowDelegate = row.rowDelegate; } else if (row[column.accessor] === null || row[column.accessor] === undefined) { filledRow[column.accessor] = column.groupType === DecisionTableColumnType.InputClause ? DASH_SYMBOL : EMPTY_SYMBOL; } else { filledRow[column.accessor] = row[column.accessor]; } return filledRow; }, {}) ); props.onRowNumberUpdated?.(newRows.length, operation, rowIndex); }, [props.onRowNumberUpdated, columns] ); const onRowAdding = useCallback(() => { return getColumnsAtLastLevel(columns).reduce((tableRow: DataRecord, column) => { tableRow[column.accessor] = EMPTY_SYMBOL; return tableRow; }, {} as DataRecord); }, [columns]); const searchRecursively = useCallback((child: any) => { if (!child) { return; } if (child.tagName === "svg") { return; } if (child.style) { child.style.height = "60px"; } if (!child.childNodes) { return; } child.childNodes.forEach(searchRecursively); }, []); useLayoutEffect(() => { const tbody = document.getElementsByTagName("tbody")[0]; const inputsCells = Array.from(tbody.getElementsByTagName("td")); // remove id column inputsCells.shift(); inputsCells.forEach((inputCell) => { searchRecursively(inputCell.childNodes[0]); }); }, [columns, searchRecursively]); const onColumnsUpdate = useCallback( ({ columns }: ColumnsUpdateArgs) => { props.onColumnsUpdate(columns); }, [props.onColumnsUpdate] ); return ( <div className="expression-container"> <div className="expression-name-and-logic-type" /> <div className="expression-container-box" data-ouia-component-id="expression-container"> <div className={`dmn-runner-table ${props.id}`}> <div className={`logic-type-selector logic-type-selected`}> <Table editableHeader={false} headerLevels={1} headerVisibility={TableHeaderVisibility.Full} getColumnPrefix={getColumnPrefix} editColumnLabel={getEditColumnLabel} handlerConfiguration={getHandlerConfiguration} columns={columns} rows={rows} onColumnsUpdate={onColumnsUpdate} onRowsUpdate={onRowsUpdate} onRowAdding={onRowAdding} readOnlyCells={true} /> </div> </div> </div> </div> ); }
the_stack
import type { IconifyJSON } from '@iconify/types' // import { useConfig, useDebugger } from '@nbhr/utils' import type { UnoGenerator } from '@unocss/core' import { createGenerator } from '@unocss/core' import UnocssIcons from '@unocss/preset-icons' import fg from 'fast-glob' import { readFileSync } from 'fs' import { parse, preprocess } from 'svelte/compiler' import type { PreprocessorGroup, Processed, } from 'svelte/types/compiler/preprocess' import { Processor } from 'windicss/lib' // import type { FullConfig } from 'windicss/types/interfaces' import { CSSParser } from 'windicss/utils/parser' import { StyleSheet } from 'windicss/utils/style' import { globalStyleSheet, Magician, SetObject } from './utils' import { loadConfig } from 'unconfig' import { FullConfig } from 'windicss/types/interfaces' // const DEV = false // let windiConfig: FullConfig // let configMTime: number // let OPTIONS: BaseConfig let entryFileName = '' interface generatorObject { data: SetObject updatedAt: number writtenAt?: number } const raw = new Map<string, generatorObject>([ [ '__GLOBAL', { data: { inlineClasses: new Set(), inlineDirectives: new Set(), inlineExpressions: new Set(), inlineIcons: new Set(), inlineAttributify: new Map(), }, updatedAt: Date.now(), }, ], ]) async function generateCSS( key: string, attributes: Record<string, string | boolean> ) { const t = raw.get(key) // MARK: WINDI DEFAULT // const FILESHEET = CSS_STYLESHEETS.get(filename || '') || undefined // if (FILESHEET && attributes['windi:global']) { // INLINE_STYLE = globalStyleSheet(FILESHEET['code']).build() // } else if (FILESHEET) { // INLINE_STYLE = FILESHEET['code'].build() // } const defaultStyleSheet = generatorWindi.interpret( Array.from( new Set([ ...(t?.data.inlineClasses || new Set()), ...(t?.data.inlineDirectives || new Set()), ...(t?.data.inlineExpressions || new Set()), ]) ).join(' ') ).styleSheet let defaultStyles = '' if (attributes['windi:global'] || attributes['windi-inline-global']) { defaultStyles = globalStyleSheet(defaultStyleSheet).build() } else { defaultStyles = defaultStyleSheet.build() } // MARK: ATTRIBUTIFY const nObj: Record<string, string[]> = {} t?.data.inlineAttributify.forEach((v: Set<string>, k: string) => { nObj[k] = Array.from(v) }) const attributifyStyleSheet = generatorWindi.attributify(nObj).styleSheet let attributifyStyles = '' if (attributes['windi:global'] || attributes['windi-inline-global']) { attributifyStyles = globalStyleSheet(attributifyStyleSheet).build() } else { attributifyStyles = attributifyStyleSheet.build() } // MARK: ICONS (experimental) let iconStyles = '' if (generatorUno && configuration.experimental?.icons != undefined) { iconStyles = await generatorUno .generate(t?.data.inlineIcons || '') .then(resolve => resolve.css) } return { defaultStyles, attributifyStyles, iconStyles } } function agent(): PreprocessorGroup { let result: SetObject return { async markup({ content, filename }): Promise<Processed> { if (!filename) return { code: content } // console.log(filename, 'markup agent') let worker = new Magician(content, filename, configuration) worker = worker.prepare() worker = worker.setInject() worker = worker.extract() result = worker.getSets() raw.set(filename, { data: result, updatedAt: Date.now(), }) return { code: worker.getContent(), } }, } } function main(): PreprocessorGroup { if (configuration.experimental?.scan !== undefined) { const files = fg.sync(['src/**/*.svelte'], {}) for (const file of files) { const content = readFileSync(file).toString() const filename = file const ast = parse(content, { filename }) const hasGlobalInline = ast.css.attributes.some( el => el.name == 'windi-inline-global' ) console.log(filename, hasGlobalInline) let worker = new Magician(content, filename, configuration) worker = worker.prepare() worker = worker.extract() const result = worker.getSets() if (hasGlobalInline) { const global = raw.get('__GLOBAL')!.data raw.set('__GLOBAL', { data: { inlineClasses: new Set([ ...global.inlineClasses, ...result.inlineClasses, ]), inlineDirectives: new Set([ ...global.inlineDirectives, ...result.inlineDirectives, ]), inlineExpressions: new Set([ ...global.inlineExpressions, ...result.inlineExpressions, ]), inlineIcons: new Set([ ...global.inlineIcons, ...result.inlineIcons, ]), inlineAttributify: new Map([ ...global.inlineAttributify, ...result.inlineAttributify, ]), }, updatedAt: Date.now(), }) raw.set(filename, { data: { inlineClasses: new Set(), inlineDirectives: new Set(), inlineExpressions: new Set(), inlineIcons: new Set(), inlineAttributify: new Map(), }, updatedAt: Date.now(), }) } else { raw.set(filename, { data: result, updatedAt: Date.now(), }) } } } return { async style({ content, attributes, filename }): Promise<Processed> { if (!filename) return { code: content } // console.log(filename, 'style main') // // MARK: PREFLIGHTS // if (OPTIONS.preflights === true && attributes['windi:preflights:global']) { // const PREFLIGHTS = PROCESSOR.preflight() // PREFLIGHTS_STYLE = globalStyleSheet(PREFLIGHTS).build() // } else if (OPTIONS.preflights === true && attributes['windi:preflights']) { // const PREFLIGHTS = PROCESSOR.preflight() // PREFLIGHTS_STYLE = PREFLIGHTS.build() // } let preflightStyleSheet = new StyleSheet() if ( attributes['windi:preflights:global'] || attributes['windi-preflights-global'] ) { preflightStyleSheet = globalStyleSheet(generatorWindi.preflight()) } const preflightStyles = preflightStyleSheet.build() // // MARK: SAFELIST // if (OPTIONS.safeList && attributes['windi:safelist:global']) { // const SAFELIST = PROCESSOR.interpret(OPTIONS.safeList).styleSheet // SAFELIST_STYLE = globalStyleSheet(SAFELIST).build() // if (OPTIONS.experimental && OPTIONS.experimental.icons != undefined) { // let UNO_SAFELIST_STYLE = '' // const { css } = await UNO.generate(OPTIONS.safeList) // const UNO_SAFELIST_STYLESHEET = new CSSParser(css).parse() // UNO_SAFELIST_STYLE = globalStyleSheet(UNO_SAFELIST_STYLESHEET).build() // SAFELIST_STYLE += UNO_SAFELIST_STYLE // } // } else if (OPTIONS.safeList && attributes['windi:safelist']) { // const SAFELIST = PROCESSOR.interpret(OPTIONS.safeList).styleSheet // SAFELIST_STYLE = SAFELIST.build() // if (OPTIONS.experimental && OPTIONS.experimental.icons != undefined) { // let UNO_SAFELIST_STYLE = '' // const { css } = await UNO.generate(OPTIONS.safeList) // UNO_SAFELIST_STYLE = css // SAFELIST_STYLE += UNO_SAFELIST_STYLE // } // } let safelistStyleSheet = new StyleSheet() let safelistIconsStyleSheet = new StyleSheet() if ( attributes['windi:safelist:global'] || attributes['windi-safelist-global'] ) { safelistStyleSheet = globalStyleSheet( generatorWindi.interpret(configuration.safeList || '').styleSheet ) if (generatorUno && configuration.experimental?.icons != undefined) { const { css } = await generatorUno.generate( configuration.safeList || '' ) safelistIconsStyleSheet = globalStyleSheet(new CSSParser(css).parse()) } } let safelistStyles = safelistStyleSheet.build() safelistStyles += safelistIconsStyleSheet.build() let defaultStyles, attributifyStyles, iconStyles if (entryFileName.length > 0) { const result = await generateCSS(filename, attributes) defaultStyles = result.defaultStyles attributifyStyles = result.attributifyStyles iconStyles = result.iconStyles } else { entryFileName = filename const resultGlobal = await generateCSS('__GLOBAL', { 'windi-inline-global': true, }) defaultStyles = resultGlobal.defaultStyles attributifyStyles = resultGlobal.attributifyStyles iconStyles = resultGlobal.iconStyles const result = await generateCSS(filename, attributes) defaultStyles += result.defaultStyles attributifyStyles += result.attributifyStyles iconStyles += result.iconStyles } // MARK: CUSTOM CSS + WINDI @apply // let CSS: StyleSheet // CSS_SOURCE = content // if (CSS_SOURCE && attributes['global']) { // CSS = new CSSParser(CSS_SOURCE, PROCESSOR).parse() // CSS_STYLE = globalStyleSheet(CSS).build() // } else if (CSS_SOURCE) { // const tmpCSS = CSS_SOURCE // const rules = [...(tmpCSS.matchAll(/(?<selector>[^}]*){(?<css>[^}]*)}/gim) || [])] // rules.forEach(rule => { // if (rule.groups && rule.groups.selector.includes(':global')) { // const globalCSS = new CSSParser(rule[0], PROCESSOR).parse() // const buildGlobalCSS = globalStyleSheet(globalCSS).build() // if (buildGlobalCSS.length > 0) CSS_STYLE += buildGlobalCSS + '\n' // } else { // CSS = new CSSParser(rule[0], PROCESSOR).parse() // const buildLocalCSS = CSS.build() // if (buildLocalCSS.length > 0) CSS_STYLE += buildLocalCSS + '\n' // } // }) // } const cssStyleSheet = new CSSParser(content, generatorWindi).parse() || new StyleSheet() let cssStyles = '' if (attributes['global']) { cssStyles = globalStyleSheet(cssStyleSheet).build() } else { cssStyles = cssStyleSheet.build() } // // MARK: COMBINE // let newStyleCode = '\n' // if (PREFLIGHTS_STYLE.length > 0) newStyleCode += PREFLIGHTS_STYLE + '\n' // if (SAFELIST_STYLE.length > 0) newStyleCode += SAFELIST_STYLE + '\n' // if (CSS_STYLE.length > 0) newStyleCode += CSS_STYLE + '\n' // if (INLINE_STYLE.length > 0) newStyleCode += INLINE_STYLE + '\n' // if (UNO_STYLE.length > 0) newStyleCode += UNO_STYLE + '\n' let newCode = '' if (preflightStyles.length > 0) newCode += '\n' + preflightStyles if (safelistStyles.length > 0) newCode += '\n' + safelistStyles if (defaultStyles.length > 0) newCode += '\n' + defaultStyles if (attributifyStyles.length > 0) newCode += '\n' + attributifyStyles if (iconStyles.length > 0) newCode += '\n' + iconStyles if (cssStyles.length > 0) newCode += '\n' + cssStyles newCode += '\n' return { code: newCode, } }, } } export interface BaseConfig { silent?: boolean mode?: 'development' | 'production' configPath?: string disableFormat?: boolean devTools?: { enabled: boolean completions?: boolean } // safeList?: string preflights?: boolean // bundle?: string; // debug?: boolean; // compile?: boolean; // prefix?: string; // verbosity?: number; experimental?: { icons?: { prefix?: string collections?: Record<string, IconifyJSON> extraProperties?: Record<string, string> } scan?: boolean } } export type DefaultConfig = BaseConfig export type UserConfig = BaseConfig const defaultConfig: DefaultConfig = { silent: false, // mode // configPath disableFormat: false, devTools: { enabled: false, }, safeList: undefined, preflights: true, // bundle: undefined, // compile: false, // prefix: 'windi-', // verbosity: 1, // debug: false, } let configuration: BaseConfig let generatorWindi: Processor let generatorUno: UnoGenerator let windiConfiguration: FullConfig // if (windiConfig != undefined) { // if (OPTIONS.configPath) { // // get modified time of config file // const mTime = statSync(OPTIONS.configPath).mtimeMs // if (mTime > configMTime) { // const tmpConfigPath = `./${Date.now()}windi.config.js` // copyFileSync(OPTIONS.configPath, tmpConfigPath) // loadConfig(tmpConfigPath) // .catch(e => { // useDebugger.createLog('Unknown Error while loading the config') // console.error(e) // }) // .finally(() => { // rmSync(tmpConfigPath) // resolve({ // code: _preprocess(content, filename), // }) // }) // } else { // resolve({ // code: _preprocess(content, filename), // }) // } // } // } else { // if (OPTIONS.configPath) { // loadConfig(OPTIONS.configPath) // .catch(e => { // useDebugger.createLog('Unknown Error while loading the config') // console.error(e) // }) // .finally(() => { // resolve({ // code: _preprocess(content, filename), // }) // }) // } else { // PROCESSOR.loadConfig() // resolve({ // code: _preprocess(content, filename), // }) // } // } // function loadConfig(path: string): Promise<void> { // useDebugger.createLog('Trying to load windi configuration from ' + path) // return useConfig.load<FullConfig>(path).then(config => { // // write current unix timestamp to configMTime // configMTime = Date.now() // if (config.preflight === false) OPTIONS.preflights = false // if (config.safelist && typeof config.safelist == 'string') { // OPTIONS.safeList = config.safelist // } else if (config.safelist) { // const tmpSafelist = config.safelist as (string | string[])[] // OPTIONS.safeList = [...new Set(tmpSafelist.flat(Infinity))].join(' ') // } // console.log(config) // console.log(JSON.stringify(config.theme)) // PROCESSOR.loadConfig(config) // useDebugger.createLog('Configuration loaded successfully') // windiConfig = config // }) // } export function windi(userConfig: UserConfig = {}): PreprocessorGroup { configuration = { ...defaultConfig, ...userConfig } generatorWindi = new Processor() const steps: PreprocessorGroup[] = [] if (configuration.experimental?.icons != undefined) { generatorUno = createGenerator( { presets: [ UnocssIcons({ ...configuration.experimental.icons, }), ], }, {} ) } if (configuration.experimental?.scan == undefined) { steps.push(agent()) } steps.push(main()) return { async markup({ content, filename }): Promise<Processed> { if (!windiConfiguration) { const { config } = await loadConfig<FullConfig>({ merge: false, sources: [ { files: 'windi.config', // default extensions extensions: ['ts', 'mts', 'cts', 'js', 'mjs', 'cjs', 'json', ''], }, ], }) windiConfiguration = config if (typeof config?.safelist == 'string') { configuration.safeList = config.safelist } else if (config?.safelist) { configuration.safeList = [ ...new Set(config.safelist.flat(Infinity)), ].join(' ') } generatorWindi.loadConfig(config) } let currentContent = content for (const step of steps) { const code = (await preprocess(currentContent, step, { filename })).code currentContent = code } return { code: currentContent, } }, } } export default windi
the_stack
//JavaScript Image Resizer (c) 2012 - Grant Galitz export class Resize { constructor(widthOriginal, heightOriginal, targetWidth, targetHeight, blendAlpha, interpolationPass, useWebWorker, resizeCallback) { this.widthOriginal = Math.abs(parseInt(widthOriginal) || 0); this.heightOriginal = Math.abs(parseInt(heightOriginal) || 0); this.targetWidth = Math.abs(parseInt(targetWidth) || 0); this.targetHeight = Math.abs(parseInt(targetHeight) || 0); this.colorChannels = (!!blendAlpha) ? 4 : 3; this.interpolationPass = !!interpolationPass; this.useWebWorker = !!useWebWorker; this.resizeCallback = (typeof resizeCallback == "function") ? resizeCallback : function (returnedArray) { }; this.targetWidthMultipliedByChannels = this.targetWidth * this.colorChannels; this.originalWidthMultipliedByChannels = this.widthOriginal * this.colorChannels; this.originalHeightMultipliedByChannels = this.heightOriginal * this.colorChannels; this.widthPassResultSize = this.targetWidthMultipliedByChannels * this.heightOriginal; this.finalResultSize = this.targetWidthMultipliedByChannels * this.targetHeight; this.initialize(); } initialize() { //Perform some checks: if (this.widthOriginal > 0 && this.heightOriginal > 0 && this.targetWidth > 0 && this.targetHeight > 0) { if (this.useWebWorker) { this.useWebWorker = (this.widthOriginal != this.targetWidth || this.heightOriginal != this.targetHeight); if (this.useWebWorker) { this.configureWorker(); } } if (!this.useWebWorker) { this.configurePasses(); } } else { throw (new Error("Invalid settings specified for the resizer.")); } } configureWorker() { try { var parentObj = this; this.worker = new Worker('./resizeWorker.js'); this.worker.onmessage = function (event) { parentObj.heightBuffer = event.data; parentObj.resizeCallback(parentObj.heightBuffer); }; this.worker.postMessage(["setup", this.widthOriginal, this.heightOriginal, this.targetWidth, this.targetHeight, this.colorChannels, this.interpolationPass]); } catch (error) { this.useWebWorker = false; } } configurePasses() { if (this.widthOriginal == this.targetWidth) { //Bypass the width resizer pass: this.resizeWidth = this.bypassResizer; } else { //Setup the width resizer pass: this.ratioWeightWidthPass = this.widthOriginal / this.targetWidth; if (this.ratioWeightWidthPass < 1 && this.interpolationPass) { this.initializeFirstPassBuffers(true); this.resizeWidth = (this.colorChannels == 4) ? this.resizeWidthInterpolatedRGBA : this.resizeWidthInterpolatedRGB; } else { this.initializeFirstPassBuffers(false); this.resizeWidth = (this.colorChannels == 4) ? this.resizeWidthRGBA : this.resizeWidthRGB; } } if (this.heightOriginal == this.targetHeight) { //Bypass the height resizer pass: this.resizeHeight = this.bypassResizer; } else { //Setup the height resizer pass: this.ratioWeightHeightPass = this.heightOriginal / this.targetHeight; if (this.ratioWeightHeightPass < 1 && this.interpolationPass) { this.initializeSecondPassBuffers(true); this.resizeHeight = this.resizeHeightInterpolated; } else { this.initializeSecondPassBuffers(false); this.resizeHeight = (this.colorChannels == 4) ? this.resizeHeightRGBA : this.resizeHeightRGB; } } } resizeWidthRGB(buffer) { var ratioWeight = this.ratioWeightWidthPass; var ratioWeightDivisor = 1 / ratioWeight; var weight = 0; var amountToNext = 0; var actualPosition = 0; var currentPosition = 0; var line = 0; var pixelOffset = 0; var outputOffset = 0; var nextLineOffsetOriginalWidth = this.originalWidthMultipliedByChannels - 2; var nextLineOffsetTargetWidth = this.targetWidthMultipliedByChannels - 2; var output = this.outputWidthWorkBench; var outputBuffer = this.widthBuffer; do { for (line = 0; line < this.originalHeightMultipliedByChannels;) { output[line++] = 0; output[line++] = 0; output[line++] = 0; } weight = ratioWeight; do { amountToNext = 1 + actualPosition - currentPosition; if (weight >= amountToNext) { for (line = 0, pixelOffset = actualPosition; line < this.originalHeightMultipliedByChannels; pixelOffset += nextLineOffsetOriginalWidth) { output[line++] += buffer[pixelOffset++] * amountToNext; output[line++] += buffer[pixelOffset++] * amountToNext; output[line++] += buffer[pixelOffset] * amountToNext; } currentPosition = actualPosition = actualPosition + 3; weight -= amountToNext; } else { for (line = 0, pixelOffset = actualPosition; line < this.originalHeightMultipliedByChannels; pixelOffset += nextLineOffsetOriginalWidth) { output[line++] += buffer[pixelOffset++] * weight; output[line++] += buffer[pixelOffset++] * weight; output[line++] += buffer[pixelOffset] * weight; } currentPosition += weight; break; } } while (weight > 0 && actualPosition < this.originalWidthMultipliedByChannels); for (line = 0, pixelOffset = outputOffset; line < this.originalHeightMultipliedByChannels; pixelOffset += nextLineOffsetTargetWidth) { outputBuffer[pixelOffset++] = output[line++] * ratioWeightDivisor; outputBuffer[pixelOffset++] = output[line++] * ratioWeightDivisor; outputBuffer[pixelOffset] = output[line++] * ratioWeightDivisor; } outputOffset += 3; } while (outputOffset < this.targetWidthMultipliedByChannels); return outputBuffer; } resizeWidthInterpolatedRGB(buffer) { var ratioWeight = this.ratioWeightWidthPass; var weight = 0; var finalOffset = 0; var pixelOffset = 0; var firstWeight = 0; var secondWeight = 0; var outputBuffer = this.widthBuffer; //Handle for only one interpolation input being valid for start calculation: for (var targetPosition = 0; weight < 0.25; targetPosition += 3, weight += ratioWeight) { for (finalOffset = targetPosition, pixelOffset = 0; finalOffset < this.widthPassResultSize; pixelOffset += this.originalWidthMultipliedByChannels, finalOffset += this.targetWidthMultipliedByChannels) { outputBuffer[finalOffset] = buffer[pixelOffset]; outputBuffer[finalOffset + 1] = buffer[pixelOffset + 1]; outputBuffer[finalOffset + 2] = buffer[pixelOffset + 2]; } } weight -= 0.25; for (var interpolationWidthSourceReadStop = this.widthOriginal - 1; weight < interpolationWidthSourceReadStop; targetPosition += 3, weight += ratioWeight) { //Calculate weightings: secondWeight = weight % 1; firstWeight = 1 - secondWeight; //Interpolate: for (finalOffset = targetPosition, pixelOffset = Math.floor(weight) * 3; finalOffset < this.widthPassResultSize; pixelOffset += this.originalWidthMultipliedByChannels, finalOffset += this.targetWidthMultipliedByChannels) { outputBuffer[finalOffset] = (buffer[pixelOffset] * firstWeight) + (buffer[pixelOffset + 3] * secondWeight); outputBuffer[finalOffset + 1] = (buffer[pixelOffset + 1] * firstWeight) + (buffer[pixelOffset + 4] * secondWeight); outputBuffer[finalOffset + 2] = (buffer[pixelOffset + 2] * firstWeight) + (buffer[pixelOffset + 5] * secondWeight); } } //Handle for only one interpolation input being valid for end calculation: for (interpolationWidthSourceReadStop = this.originalWidthMultipliedByChannels - 3; targetPosition < this.targetWidthMultipliedByChannels; targetPosition += 3) { for (finalOffset = targetPosition, pixelOffset = interpolationWidthSourceReadStop; finalOffset < this.widthPassResultSize; pixelOffset += this.originalWidthMultipliedByChannels, finalOffset += this.targetWidthMultipliedByChannels) { outputBuffer[finalOffset] = buffer[pixelOffset]; outputBuffer[finalOffset + 1] = buffer[pixelOffset + 1]; outputBuffer[finalOffset + 2] = buffer[pixelOffset + 2]; } } return outputBuffer; } resizeWidthRGBA(buffer) { var ratioWeight = this.ratioWeightWidthPass; var ratioWeightDivisor = 1 / ratioWeight; var weight = 0; var amountToNext = 0; var actualPosition = 0; var currentPosition = 0; var line = 0; var pixelOffset = 0; var outputOffset = 0; var nextLineOffsetOriginalWidth = this.originalWidthMultipliedByChannels - 3; var nextLineOffsetTargetWidth = this.targetWidthMultipliedByChannels - 3; var output = this.outputWidthWorkBench; var outputBuffer = this.widthBuffer; do { for (line = 0; line < this.originalHeightMultipliedByChannels;) { output[line++] = 0; output[line++] = 0; output[line++] = 0; output[line++] = 0; } weight = ratioWeight; do { amountToNext = 1 + actualPosition - currentPosition; if (weight >= amountToNext) { for (line = 0, pixelOffset = actualPosition; line < this.originalHeightMultipliedByChannels; pixelOffset += nextLineOffsetOriginalWidth) { output[line++] += buffer[pixelOffset++] * amountToNext; output[line++] += buffer[pixelOffset++] * amountToNext; output[line++] += buffer[pixelOffset++] * amountToNext; output[line++] += buffer[pixelOffset] * amountToNext; } currentPosition = actualPosition = actualPosition + 4; weight -= amountToNext; } else { for (line = 0, pixelOffset = actualPosition; line < this.originalHeightMultipliedByChannels; pixelOffset += nextLineOffsetOriginalWidth) { output[line++] += buffer[pixelOffset++] * weight; output[line++] += buffer[pixelOffset++] * weight; output[line++] += buffer[pixelOffset++] * weight; output[line++] += buffer[pixelOffset] * weight; } currentPosition += weight; break; } } while (weight > 0 && actualPosition < this.originalWidthMultipliedByChannels); for (line = 0, pixelOffset = outputOffset; line < this.originalHeightMultipliedByChannels; pixelOffset += nextLineOffsetTargetWidth) { outputBuffer[pixelOffset++] = output[line++] * ratioWeightDivisor; outputBuffer[pixelOffset++] = output[line++] * ratioWeightDivisor; outputBuffer[pixelOffset++] = output[line++] * ratioWeightDivisor; outputBuffer[pixelOffset] = output[line++] * ratioWeightDivisor; } outputOffset += 4; } while (outputOffset < this.targetWidthMultipliedByChannels); return outputBuffer; } resizeWidthInterpolatedRGBA(buffer) { var ratioWeight = this.ratioWeightWidthPass; var weight = 0; var finalOffset = 0; var pixelOffset = 0; var firstWeight = 0; var secondWeight = 0; var outputBuffer = this.widthBuffer; //Handle for only one interpolation input being valid for start calculation: for (var targetPosition = 0; weight < 0.25; targetPosition += 4, weight += ratioWeight) { for (finalOffset = targetPosition, pixelOffset = 0; finalOffset < this.widthPassResultSize; pixelOffset += this.originalWidthMultipliedByChannels, finalOffset += this.targetWidthMultipliedByChannels) { outputBuffer[finalOffset] = buffer[pixelOffset]; outputBuffer[finalOffset + 1] = buffer[pixelOffset + 1]; outputBuffer[finalOffset + 2] = buffer[pixelOffset + 2]; outputBuffer[finalOffset + 3] = buffer[pixelOffset + 3]; } } weight -= 0.25; for (var interpolationWidthSourceReadStop = this.widthOriginal - 1; weight < interpolationWidthSourceReadStop; targetPosition += 4, weight += ratioWeight) { //Calculate weightings: secondWeight = weight % 1; firstWeight = 1 - secondWeight; //Interpolate: for (finalOffset = targetPosition, pixelOffset = Math.floor(weight) * 4; finalOffset < this.widthPassResultSize; pixelOffset += this.originalWidthMultipliedByChannels, finalOffset += this.targetWidthMultipliedByChannels) { outputBuffer[finalOffset] = (buffer[pixelOffset] * firstWeight) + (buffer[pixelOffset + 4] * secondWeight); outputBuffer[finalOffset + 1] = (buffer[pixelOffset + 1] * firstWeight) + (buffer[pixelOffset + 5] * secondWeight); outputBuffer[finalOffset + 2] = (buffer[pixelOffset + 2] * firstWeight) + (buffer[pixelOffset + 6] * secondWeight); outputBuffer[finalOffset + 3] = (buffer[pixelOffset + 3] * firstWeight) + (buffer[pixelOffset + 7] * secondWeight); } } //Handle for only one interpolation input being valid for end calculation: for (interpolationWidthSourceReadStop = this.originalWidthMultipliedByChannels - 4; targetPosition < this.targetWidthMultipliedByChannels; targetPosition += 4) { for (finalOffset = targetPosition, pixelOffset = interpolationWidthSourceReadStop; finalOffset < this.widthPassResultSize; pixelOffset += this.originalWidthMultipliedByChannels, finalOffset += this.targetWidthMultipliedByChannels) { outputBuffer[finalOffset] = buffer[pixelOffset]; outputBuffer[finalOffset + 1] = buffer[pixelOffset + 1]; outputBuffer[finalOffset + 2] = buffer[pixelOffset + 2]; outputBuffer[finalOffset + 3] = buffer[pixelOffset + 3]; } } return outputBuffer; } resizeHeightRGB(buffer) { var ratioWeight = this.ratioWeightHeightPass; var ratioWeightDivisor = 1 / ratioWeight; var weight = 0; var amountToNext = 0; var actualPosition = 0; var currentPosition = 0; var pixelOffset = 0; var outputOffset = 0; var output = this.outputHeightWorkBench; var outputBuffer = this.heightBuffer; do { for (pixelOffset = 0; pixelOffset < this.targetWidthMultipliedByChannels;) { output[pixelOffset++] = 0; output[pixelOffset++] = 0; output[pixelOffset++] = 0; } weight = ratioWeight; do { amountToNext = 1 + actualPosition - currentPosition; if (weight >= amountToNext) { for (pixelOffset = 0; pixelOffset < this.targetWidthMultipliedByChannels;) { output[pixelOffset++] += buffer[actualPosition++] * amountToNext; output[pixelOffset++] += buffer[actualPosition++] * amountToNext; output[pixelOffset++] += buffer[actualPosition++] * amountToNext; } currentPosition = actualPosition; weight -= amountToNext; } else { for (pixelOffset = 0, amountToNext = actualPosition; pixelOffset < this.targetWidthMultipliedByChannels;) { output[pixelOffset++] += buffer[amountToNext++] * weight; output[pixelOffset++] += buffer[amountToNext++] * weight; output[pixelOffset++] += buffer[amountToNext++] * weight; } currentPosition += weight; break; } } while (weight > 0 && actualPosition < this.widthPassResultSize); for (pixelOffset = 0; pixelOffset < this.targetWidthMultipliedByChannels;) { outputBuffer[outputOffset++] = Math.round(output[pixelOffset++] * ratioWeightDivisor); outputBuffer[outputOffset++] = Math.round(output[pixelOffset++] * ratioWeightDivisor); outputBuffer[outputOffset++] = Math.round(output[pixelOffset++] * ratioWeightDivisor); } } while (outputOffset < this.finalResultSize); return outputBuffer; } resizeHeightInterpolated(buffer) { var ratioWeight = this.ratioWeightHeightPass; var weight = 0; var finalOffset = 0; var pixelOffset = 0; var pixelOffsetAccumulated = 0; var pixelOffsetAccumulated2 = 0; var firstWeight = 0; var secondWeight = 0; var outputBuffer = this.heightBuffer; //Handle for only one interpolation input being valid for start calculation: for (; weight < 0.25; weight += ratioWeight) { for (pixelOffset = 0; pixelOffset < this.targetWidthMultipliedByChannels;) { outputBuffer[finalOffset++] = buffer[pixelOffset++]; } } weight -= 0.25; for (var interpolationHeightSourceReadStop = this.heightOriginal - 1; weight < interpolationHeightSourceReadStop; weight += ratioWeight) { //Calculate weightings: secondWeight = weight % 1; firstWeight = 1 - secondWeight; //Interpolate: pixelOffsetAccumulated = Math.floor(weight) * this.targetWidthMultipliedByChannels; pixelOffsetAccumulated2 = pixelOffsetAccumulated + this.targetWidthMultipliedByChannels; for (pixelOffset = 0; pixelOffset < this.targetWidthMultipliedByChannels; ++pixelOffset) { outputBuffer[finalOffset++] = (buffer[pixelOffsetAccumulated + pixelOffset] * firstWeight) + (buffer[pixelOffsetAccumulated2 + pixelOffset] * secondWeight); } } //Handle for only one interpolation input being valid for end calculation: while (finalOffset < this.finalResultSize) { for (pixelOffset = 0, pixelOffsetAccumulated = interpolationHeightSourceReadStop * this.targetWidthMultipliedByChannels; pixelOffset < this.targetWidthMultipliedByChannels; ++pixelOffset) { outputBuffer[finalOffset++] = buffer[pixelOffsetAccumulated++]; } } return outputBuffer; } resizeHeightRGBA(buffer) { var ratioWeight = this.ratioWeightHeightPass; var ratioWeightDivisor = 1 / ratioWeight; var weight = 0; var amountToNext = 0; var actualPosition = 0; var currentPosition = 0; var pixelOffset = 0; var outputOffset = 0; var output = this.outputHeightWorkBench; var outputBuffer = this.heightBuffer; do { for (pixelOffset = 0; pixelOffset < this.targetWidthMultipliedByChannels;) { output[pixelOffset++] = 0; output[pixelOffset++] = 0; output[pixelOffset++] = 0; output[pixelOffset++] = 0; } weight = ratioWeight; do { amountToNext = 1 + actualPosition - currentPosition; if (weight >= amountToNext) { for (pixelOffset = 0; pixelOffset < this.targetWidthMultipliedByChannels;) { output[pixelOffset++] += buffer[actualPosition++] * amountToNext; output[pixelOffset++] += buffer[actualPosition++] * amountToNext; output[pixelOffset++] += buffer[actualPosition++] * amountToNext; output[pixelOffset++] += buffer[actualPosition++] * amountToNext; } currentPosition = actualPosition; weight -= amountToNext; } else { for (pixelOffset = 0, amountToNext = actualPosition; pixelOffset < this.targetWidthMultipliedByChannels;) { output[pixelOffset++] += buffer[amountToNext++] * weight; output[pixelOffset++] += buffer[amountToNext++] * weight; output[pixelOffset++] += buffer[amountToNext++] * weight; output[pixelOffset++] += buffer[amountToNext++] * weight; } currentPosition += weight; break; } } while (weight > 0 && actualPosition < this.widthPassResultSize); for (pixelOffset = 0; pixelOffset < this.targetWidthMultipliedByChannels;) { outputBuffer[outputOffset++] = Math.round(output[pixelOffset++] * ratioWeightDivisor); outputBuffer[outputOffset++] = Math.round(output[pixelOffset++] * ratioWeightDivisor); outputBuffer[outputOffset++] = Math.round(output[pixelOffset++] * ratioWeightDivisor); outputBuffer[outputOffset++] = Math.round(output[pixelOffset++] * ratioWeightDivisor); } } while (outputOffset < this.finalResultSize); return outputBuffer; } resize(buffer) { if (this.useWebWorker) { this.worker.postMessage(["resize", buffer]); } else { this.resizeCallback(this.resizeHeight(this.resizeWidth(buffer))); } } bypassResizer(buffer) { //Just return the buffer passsed: return buffer; } initializeFirstPassBuffers(BILINEARAlgo) { //Initialize the internal width pass buffers: this.widthBuffer = this.generateFloatBuffer(this.widthPassResultSize); if (!BILINEARAlgo) { this.outputWidthWorkBench = this.generateFloatBuffer(this.originalHeightMultipliedByChannels); } } initializeSecondPassBuffers(BILINEARAlgo) { //Initialize the internal height pass buffers: this.heightBuffer = this.generateUint8Buffer(this.finalResultSize); if (!BILINEARAlgo) { this.outputHeightWorkBench = this.generateFloatBuffer(this.targetWidthMultipliedByChannels); } } generateFloatBuffer(bufferLength) { //Generate a float32 typed array buffer: try { return new Float32Array(bufferLength); } catch (error) { return []; } } generateUint8Buffer(bufferLength) { //Generate a uint8 typed array buffer: try { return new Uint8Array(bufferLength); } catch (error) { return []; } } }
the_stack
import { assert, Has, NotHas, IsAny, IsExact } from "conditional-type-checks"; import * as Comlink from "../src/comlink.js"; async function closureSoICanUseAwait() { { function simpleNumberFunction() { return 4; } const proxy = Comlink.wrap<typeof simpleNumberFunction>(0 as any); assert<IsAny<typeof proxy>>(false); const v = proxy(); assert<Has<typeof v, Promise<number>>>(true); } { function simpleObjectFunction() { return { a: 3 }; } const proxy = Comlink.wrap<typeof simpleObjectFunction>(0 as any); const v = await proxy(); assert<Has<typeof v, { a: number }>>(true); } { async function simpleAsyncFunction() { return { a: 3 }; } const proxy = Comlink.wrap<typeof simpleAsyncFunction>(0 as any); const v = await proxy(); assert<Has<typeof v, { a: number }>>(true); } { function functionWithProxy() { return Comlink.proxy({ a: 3 }); } const proxy = Comlink.wrap<typeof functionWithProxy>(0 as any); const subproxy = await proxy(); const prop = subproxy.a; assert<Has<typeof prop, Promise<number>>>(true); } { class X { static staticFunc() { return 4; } private f = 4; public g = 9; sayHi() { return "hi"; } } const proxy = Comlink.wrap<typeof X>(0 as any); assert<Has<typeof proxy, { staticFunc: () => Promise<number> }>>(true); const instance = await new proxy(); assert<Has<typeof instance, { sayHi: () => Promise<string> }>>(true); assert<Has<typeof instance, { g: Promise<number> }>>(true); assert<NotHas<typeof instance, { f: Promise<number> }>>(true); assert<IsAny<typeof instance>>(false); } { const x = { a: 4, b() { return 9; }, c: { d: 3, }, }; const proxy = Comlink.wrap<typeof x>(0 as any); assert<IsAny<typeof proxy>>(false); const a = proxy.a; assert<Has<typeof a, Promise<number>>>(true); assert<IsAny<typeof a>>(false); const b = proxy.b; assert<Has<typeof b, () => Promise<number>>>(true); assert<IsAny<typeof b>>(false); const subproxy = proxy.c; assert<Has<typeof subproxy, Promise<{ d: number }>>>(true); assert<IsAny<typeof subproxy>>(false); const copy = await proxy.c; assert<Has<typeof copy, { d: number }>>(true); } { Comlink.wrap(new MessageChannel().port1); Comlink.expose({}, new MessageChannel().port2); interface Baz { baz: number; method(): number; } class Foo { constructor(cParam: string) { const self = this; assert<IsExact<typeof self.proxyProp, Bar & Comlink.ProxyMarked>>(true); } prop1: string = "abc"; proxyProp = Comlink.proxy(new Bar()); methodWithTupleParams(...args: [string] | [number, string]): number { return 123; } methodWithProxiedReturnValue(): Baz & Comlink.ProxyMarked { return Comlink.proxy({ baz: 123, method: () => 123 }); } methodWithProxyParameter(param: Baz & Comlink.ProxyMarked): void {} } class Bar { prop2: string | number = "abc"; method(param: string): number { return 123; } methodWithProxiedReturnValue(): Baz & Comlink.ProxyMarked { return Comlink.proxy({ baz: 123, method: () => 123 }); } } const proxy = Comlink.wrap<Foo>(Comlink.windowEndpoint(self)); assert<IsExact<typeof proxy, Comlink.Remote<Foo>>>(true); proxy[Comlink.releaseProxy](); const endp = proxy[Comlink.createEndpoint](); assert<IsExact<typeof endp, Promise<MessagePort>>>(true); assert<IsAny<typeof proxy.prop1>>(false); assert<Has<typeof proxy.prop1, Promise<string>>>(true); const r1 = proxy.methodWithTupleParams(123, "abc"); assert<IsExact<typeof r1, Promise<number>>>(true); const r2 = proxy.methodWithTupleParams("abc"); assert<IsExact<typeof r2, Promise<number>>>(true); assert< IsExact<typeof proxy.proxyProp, Comlink.Remote<Bar & Comlink.ProxyMarked>> >(true); assert<IsAny<typeof proxy.proxyProp.prop2>>(false); assert<Has<typeof proxy.proxyProp.prop2, Promise<string>>>(true); assert<Has<typeof proxy.proxyProp.prop2, Promise<number>>>(true); const r3 = proxy.proxyProp.method("param"); assert<IsAny<typeof r3>>(false); assert<Has<typeof r3, Promise<number>>>(true); // @ts-expect-error proxy.proxyProp.method(123); // @ts-expect-error proxy.proxyProp.method(); const r4 = proxy.methodWithProxiedReturnValue(); assert<IsAny<typeof r4>>(false); assert< IsExact<typeof r4, Promise<Comlink.Remote<Baz & Comlink.ProxyMarked>>> >(true); const r5 = proxy.proxyProp.methodWithProxiedReturnValue(); assert< IsExact<typeof r5, Promise<Comlink.Remote<Baz & Comlink.ProxyMarked>>> >(true); const r6 = (await proxy.methodWithProxiedReturnValue()).baz; assert<IsAny<typeof r6>>(false); assert<Has<typeof r6, Promise<number>>>(true); const r7 = (await proxy.methodWithProxiedReturnValue()).method(); assert<IsAny<typeof r7>>(false); assert<Has<typeof r7, Promise<number>>>(true); const ProxiedFooClass = Comlink.wrap<typeof Foo>( Comlink.windowEndpoint(self) ); const inst1 = await new ProxiedFooClass("test"); assert<IsExact<typeof inst1, Comlink.Remote<Foo>>>(true); inst1[Comlink.releaseProxy](); inst1[Comlink.createEndpoint](); // @ts-expect-error await new ProxiedFooClass(123); // @ts-expect-error await new ProxiedFooClass(); // // Tests for advanced proxy use cases // // Type round trips // This tests that Local is the exact inverse of Remote for objects: assert< IsExact< Comlink.Local<Comlink.Remote<Comlink.ProxyMarked>>, Comlink.ProxyMarked > >(true); // This tests that Local is the exact inverse of Remote for functions, with one difference: // The local version of a remote function can be either implemented as a sync or async function, // because Remote<T> always makes the function async. assert< IsExact< Comlink.Local<Comlink.Remote<(a: number) => string>>, (a: number) => string | Promise<string> > >(true); interface Subscriber<T> { closed?: boolean; next?: (value: T) => void; } interface Unsubscribable { unsubscribe(): void; } /** A Subscribable that can get proxied by Comlink */ interface ProxyableSubscribable<T> extends Comlink.ProxyMarked { subscribe( subscriber: Comlink.Remote<Subscriber<T> & Comlink.ProxyMarked> ): Unsubscribable & Comlink.ProxyMarked; } /** Simple parameter object that gets cloned (not proxied) */ interface Params { textDocument: string; } class Registry { async registerProvider( provider: Comlink.Remote< ((params: Params) => ProxyableSubscribable<string>) & Comlink.ProxyMarked > ) { const resultPromise = provider({ textDocument: "foo" }); assert< IsExact< typeof resultPromise, Promise<Comlink.Remote<ProxyableSubscribable<string>>> > >(true); const result = await resultPromise; const subscriptionPromise = result.subscribe({ [Comlink.proxyMarker]: true, next: (value) => { assert<IsExact<typeof value, string>>(true); }, }); assert< IsExact< typeof subscriptionPromise, Promise<Comlink.Remote<Unsubscribable & Comlink.ProxyMarked>> > >(true); const subscriber = Comlink.proxy({ next: (value: string) => console.log(value), }); result.subscribe(subscriber); const r1 = (await subscriptionPromise).unsubscribe(); assert<IsExact<typeof r1, Promise<void>>>(true); } } const proxy2 = Comlink.wrap<Registry>(Comlink.windowEndpoint(self)); proxy2.registerProvider( // Synchronous callback Comlink.proxy(({ textDocument }: Params) => { const subscribable = Comlink.proxy({ subscribe( subscriber: Comlink.Remote<Subscriber<string> & Comlink.ProxyMarked> ): Unsubscribable & Comlink.ProxyMarked { // Important to test here is that union types (such as Function | undefined) distribute properly // when wrapped in Promises/proxied assert<IsAny<typeof subscriber.closed>>(false); assert< IsExact< typeof subscriber.closed, Promise<true> | Promise<false> | Promise<undefined> | undefined > >(true); assert<IsAny<typeof subscriber.next>>(false); assert< IsExact< typeof subscriber.next, | Comlink.Remote<(value: string) => void> | Promise<undefined> | undefined > >(true); // @ts-expect-error subscriber.next(); if (subscriber.next) { // Only checking for presence is not enough, since it could be a Promise // @ts-expect-error subscriber.next(); } if (typeof subscriber.next === "function") { subscriber.next("abc"); } return Comlink.proxy({ unsubscribe() {} }); }, }); assert<Has<typeof subscribable, Comlink.ProxyMarked>>(true); return subscribable; }) ); proxy2.registerProvider( // Async callback Comlink.proxy(async ({ textDocument }: Params) => { const subscribable = Comlink.proxy({ subscribe( subscriber: Comlink.Remote<Subscriber<string> & Comlink.ProxyMarked> ): Unsubscribable & Comlink.ProxyMarked { assert<IsAny<typeof subscriber.next>>(false); assert< IsExact< typeof subscriber.next, | Comlink.Remote<(value: string) => void> | Promise<undefined> | undefined > >(true); // Only checking for presence is not enough, since it could be a Promise if (typeof subscriber.next === "function") { subscriber.next("abc"); } return Comlink.proxy({ unsubscribe() {} }); }, }); return subscribable; }) ); } // Transfer handlers { const urlTransferHandler: Comlink.TransferHandler<URL, string> = { canHandle: (val): val is URL => { assert<IsExact<typeof val, unknown>>(true); return val instanceof URL; }, serialize: (url) => { assert<IsExact<typeof url, URL>>(true); return [url.href, []]; }, deserialize: (str) => { assert<IsExact<typeof str, string>>(true); return new URL(str); }, }; Comlink.transferHandlers.set("URL", urlTransferHandler); } }
the_stack
import { Identity } from '@textile/crypto' import { CopyAuthOptions, GrpcAuthentication, WithKeyInfoOptions, WithUserAuthOptions, } from '@textile/grpc-authentication' import { Client } from '@textile/hub-threads-client' import { KeyInfo, UserAuth } from '@textile/security' import { ThreadID } from '@textile/threads-id' import log from 'loglevel' import { bucketsArchive, bucketsArchives, bucketsArchiveWatch, bucketsCreate, bucketsDefaultArchiveConfig, bucketsLinks, bucketsList, bucketsListIpfsPath, bucketsMovePath, bucketsPullIpfsPath, bucketsPullPath, bucketsPullPathAccessRoles, bucketsPushPath, bucketsPushPathAccessRoles, bucketsPushPaths, bucketsRemove, bucketsRemovePath, bucketsRoot, bucketsSetDefaultArchiveConfig, bucketsSetPath, CHUNK_SIZE, } from './api' import { ArchiveConfig, ArchiveOptions, Archives, CreateOptions, CreateResponse, GetOrCreateOptions, GetOrCreateResponse, Links, Path, PathAccessRole, PathItem, PushOptions, PushPathResult, PushPathsResult, RemovePathOptions, RemovePathResponse, Root, } from './types' import { listPathFlat, listPathRecursive } from './utils' const logger = log.getLogger('buckets') /** * Buckets a client wrapper for interacting with the Textile Buckets API. * @example * Initialize the Bucket API and open an existing bucket (or create if new). * ```typescript * import { Buckets, UserAuth } from '@textile/hub' * * const getOrCreate = async (auth: UserAuth, bucketName: string) => { * const buckets = Buckets.withUserAuth(auth) * // Automatically scopes future calls on `buckets` to the Thread containing the bucket * const { root, threadID } = await buckets.getOrCreate(bucketName) * if (!root) throw new Error('bucket not created') * const bucketKey = root.key * return { buckets, bucketKey } * } * ``` * * @example * Print the links for the bucket * ```typescript * import { Buckets } from '@textile/hub' * * // This method requires that you run "getOrCreate" or have specified "withThread" * async function logLinks (buckets: Buckets, bucketKey: string) { * const links = await buckets.links(bucketKey) * console.log(links) * } * ``` * * @example * Find an existing Bucket * ```typescript * import { Buckets } from '@textile/hub' * * // This method requires that you already specify the Thread containing * // the bucket with buckets.withThread(<thread name>). * const exists = async (buckets: Buckets, bucketName: string) => { * const roots = await buckets.list(); * return roots.find((bucket) => bucket.name === bucketName) * } * ``` * * @example * Push an folder in node.js * ```typescript * import fs from 'fs' * import util from 'util' * import glob from 'glob' * import { Buckets } from '@textile/hub' * * const globDir = util.promisify(glob) * * // expects an already setup buckets session using getOrCreate or withThread * const exists = async (buckets: Buckets, bucketKey: string, dir: string) => { * const files = await globDir('<dir glob options>') * return await Promise.all(files.map(async (file) => { * const filePath = dir + '/' + file * var content = fs.createReadStream(filePath, { highWaterMark: 1024 * 1024 * 3 }); * const upload = { * path: file, * content * } * return await buckets.pushPath(bucketKey, file, upload) * })) * } * ``` */ export class Buckets extends GrpcAuthentication { /** * {@inheritDoc @textile/hub#GrpcAuthentication.copyAuth} * * @example * Copy an authenticated Users api instance to Buckets. * ```typescript * import { Buckets, Users } from '@textile/hub' * * const usersToBuckets = async (user: Users) => { * const buckets = Buckets.copyAuth(user) * return buckets * } * ``` * * @example * Copy an authenticated Buckets api instance to Users. * ```typescript * import { Buckets, Users } from '@textile/hub' * * const bucketsToUsers = async (buckets: Buckets) => { * const user = Users.copyAuth(buckets) * return user * } * ``` */ static copyAuth( auth: GrpcAuthentication, options?: CopyAuthOptions, ): Buckets { return new Buckets(auth.context, options?.debug) } /** * {@inheritDoc @textile/hub#GrpcAuthentication.withUserAuth} * * @example * ```@typescript * import { Buckets, UserAuth } from '@textile/hub' * * async function example (userAuth: UserAuth) { * const buckets = await Buckets.withUserAuth(userAuth) * } * ``` */ static withUserAuth( auth: UserAuth | (() => Promise<UserAuth>), options?: WithUserAuthOptions, ): Buckets { const res = super.withUserAuth(auth, options) return this.copyAuth(res, options) } /** * {@inheritDoc @textile/hub#GrpcAuthentication.withKeyInfo} * * @example * ```@typescript * import { Buckets, KeyInfo } from '@textile/hub' * * async function start () { * const keyInfo: KeyInfo = { * key: '<api key>', * secret: '<api secret>' * } * const buckets = await Buckets.withKeyInfo(keyInfo) * } * ``` */ static async withKeyInfo( key: KeyInfo, options?: WithKeyInfoOptions, ): Promise<Buckets> { const auth = await super.withKeyInfo(key, options) return this.copyAuth(auth, options) } /** * {@inheritDoc @textile/hub#GrpcAuthentication.withThread} * * @example * ```@typescript * import { Buckets, ThreadID } from '@textile/hub' * * async function example (threadID: ThreadID) { * const id = threadID.toString() * const buckets = await Buckets.withThread(id) * } * ``` */ withThread(threadID?: string): void { return super.withThread(threadID) } /** * {@inheritDoc @textile/hub#GrpcAuthentication.getToken} * * @example * ```@typescript * import { Buckets, PrivateKey } from '@textile/hub' * * async function example (buckets: Buckets, identity: PrivateKey) { * const token = await buckets.getToken(identity) * return token // already added to `buckets` scope * } * ``` */ async getToken(identity: Identity): Promise<string> { return super.getToken(identity) } /** * {@inheritDoc @textile/hub#GrpcAuthentication.getToken} */ setToken(token: string): Promise<void> { return super.setToken(token) } /** * {@inheritDoc @textile/hub#GrpcAuthentication.getTokenChallenge} * * @example * ```typescript * import { Buckets, PrivateKey } from '@textile/hub' * * async function example (buckets: Buckets, identity: PrivateKey) { * const token = await buckets.getTokenChallenge( * identity.public.toString(), * (challenge: Uint8Array) => { * return new Promise((resolve, reject) => { * // This is where you should program PrivateKey to respond to challenge * // Read more here: https://docs.textile.io/tutorials/hub/production-auth/ * }) * } * ) * return token * } * ``` */ async getTokenChallenge( publicKey: string, callback: (challenge: Uint8Array) => Uint8Array | Promise<Uint8Array>, ): Promise<string> { return super.getTokenChallenge(publicKey, callback) } /** * (Deprecated) Open a new / existing bucket by bucket name and ThreadID (create not required) * @param name name of bucket * @param threadName the name of the thread where the bucket is stored (default `buckets`) * @param encrypted encrypt the bucket contents (default `false`) * @param threadID id of thread where bucket is stored * @deprecated Open has been replaced with getOrCreate */ async open( name: string, threadName = 'buckets', encrypted = false, threadID?: string, ): Promise<{ root?: Root; threadID?: string }> { const options: GetOrCreateOptions = { threadName: threadName && threadName !== '' ? threadName : 'buckets', encrypted: !!encrypted, threadID, } return this.getOrCreate(name, options) } /** * (Deprecated) Open a new / existing bucket by bucket name and ThreadID (create not required) * @param name name of bucket * @param threadName the name of the thread where the bucket is stored (default `buckets`) * @param encrypted encrypt the bucket contents (default `false`) * @param threadID id of thread where bucket is stored * @deprecated getOrInit has been replaced with getOrCreate */ async getOrInit( name: string, threadName = 'buckets', encrypted = false, threadID?: string, ): Promise<{ root?: Root; threadID?: string }> { const options: GetOrCreateOptions = { threadName: threadName && threadName !== '' ? threadName : 'buckets', encrypted: !!encrypted, threadID, } return this.getOrCreate(name, options) } /** * Open a new / existing bucket by bucket name and ThreadID (create not required) * Replaces `open` command in older versions. * @param name name of bucket * @param threadName (optional) the name of the thread where the bucket is stored (default `buckets`) * @param encrypted (optional) encrypt the bucket contents (default `false`) * @param cid (optional) Bootstrap the bucket with a UnixFS Cid from the IPFS network * @param threadID (optional) id of thread where bucket is stored * * @remarks * The IPFS protocol and its implementations are still in heavy * development. By using Textile, you are acknowledging that you * understand there may be risks to storing your content on or * using decentralized storage services. * * @example * Create a Bucket called "app-name-files" * ```typescript * import { Buckets, UserAuth } from '@textile/hub' * * const open = async (auth: UserAuth, name: string) => { * const buckets = Buckets.withUserAuth(auth) * const { root, threadID } = await buckets.getOrCreate(name) * return { buckets, root, threadID } * } * ``` */ async getOrCreate( name: string, options?: GetOrCreateOptions, ): Promise<GetOrCreateResponse> async getOrCreate( name: string, options?: string | GetOrCreateOptions, encrypted?: boolean, cid?: string, threadID?: string, ): Promise<{ root?: Root; threadID?: string }> { if (!options && (encrypted || cid || threadID)) { // Case where threadName passed as undefined using old signature console.warn( 'Update Buckets.getOrCreate to use GetOrCreateOptions input.', ) return this._getOrCreate(name, 'buckets', !!encrypted, cid, threadID) } else if (!options) { return this._getOrCreate(name) } else if (typeof options !== 'object') { // Case where using old signature console.warn( 'Update Buckets.getOrCreate to use GetOrCreateOptions input.', ) return this._getOrCreate(name, options, !!encrypted, cid, threadID) } else { // Using new signature const threadName = options.threadName && options.threadName !== '' ? options.threadName : 'buckets' const encrypted = !!options.encrypted return this._getOrCreate( name, threadName, encrypted, options.cid, options.threadID, ) } } /** * @internal */ private async _getOrCreate( name: string, threadName = 'buckets', encrypted = false, cid?: string, threadID?: string, ): Promise<{ root?: Root; threadID?: string }> { const client = new Client(this.context) if (threadID) { const id = threadID const res = await client.listThreads() const exists = res.find((thread: any) => thread.id === id) if (!exists) { const id = ThreadID.fromString(threadID) await client.newDB(id, threadName) } this.withThread(threadID) } else { try { const res = await client.getThread(threadName) threadID = typeof res.id === 'string' ? res.id : ThreadID.fromBytes(res.id).toString() this.withThread(threadID) } catch (error) { if ( error.message !== 'Thread not found' && !error.message.includes('mongo: no documents in result') ) { throw new Error(error.message) } const newId = ThreadID.fromRandom() await client.newDB(newId, threadName) threadID = newId.toString() this.withThread(threadID) } } const roots = await this.list() const existing = roots.find((bucket) => bucket.name === name) if (existing) { return { root: existing, threadID } } const created = await this.create(name, { encrypted, cid }) return { root: created.root, threadID } } /** * Existing lists all remote buckets in the thread or in all threads. * @param threadID (optional) if threadID is not defined, this will return buckets from all threads. */ async existing(threadID?: string): Promise<Root[]> { const client = new Client(this.context) const threads = [] if (threadID) { threads.push(threadID) } else { const res = await client.listThreads() for (const thread of res) { if (thread.id) threads.push(thread.id) } } const bucketList: Root[] = [] for (const id of threads) { this.withThread(id) for (const root of await this.list()) { bucketList.push(root) } } // Clear the currently used thread this.withThread(undefined) return bucketList } /** * (Deprecated) Creates a new bucket. * @param name Human-readable bucket name. It is only meant to help identify a bucket in a UI and is not unique. * @param encrypted encrypt the bucket contents (default `false`) * @deprecated Init has been replaced by create */ async init(name: string, encrypted = false): Promise<CreateResponse> { return this.create(name, { encrypted }) } /** * Creates a new bucket. * @public * @param name Human-readable bucket name. It is only meant to help identify a bucket in a UI and is not unique. * @param encrypted encrypt the bucket contents (default `false`) * @param cid (optional) Bootstrap the bucket with a UnixFS Cid from the IPFS network * @example * Create a Bucket called "app-name-files" * ```typescript * import { Buckets } from '@textile/hub' * * const create = async (buckets: Buckets) => { * return buckets.create("app-name-files") * } * ``` */ async create(name: string, options?: CreateOptions): Promise<CreateResponse> async create( name: string, options?: boolean | CreateOptions, cid?: string, ): Promise<CreateResponse> { logger.debug('create request') if (typeof options == 'object') { return bucketsCreate(this, name, !!options.encrypted, options.cid) } else { if (options !== undefined || cid !== undefined) { console.warn('Update Buckets.create to use CreateOptions input.') } const encrypted = !!options return bucketsCreate(this, name, encrypted, cid) } } /** * Returns the bucket root CID * @param key Unique (IPNS compatible) identifier key for a bucket. */ async root(key: string): Promise<Root | undefined> { logger.debug('root request') return bucketsRoot(this, key) } /** * Returns a list of bucket links. * @param key Unique (IPNS compatible) identifier key for a bucket. * @param path path within the bucket for links (default '/'). * @example * Generate the HTTP, IPNS, and IPFS links for a Bucket * ```typescript * import { Buckets } from '@textile/hub' * * const getIpnsLink = async (buckets: Buckets, bucketKey: string) => { * const links = await buckets.links(bucketKey) * return links.ipns * } * * const getWwwLink = async (buckets: Buckets, bucketKey: string) => { * const links = await buckets.links(bucketKey) * return links.www * } * ``` */ async links(key: string, path = '/'): Promise<Links> { logger.debug('link request') return bucketsLinks(this, key, path) } /** * Returns a list of all bucket roots. * @example * Find an existing Bucket named "app-name-files" * ```typescript * import { Buckets } from '@textile/hub' * * const exists = async (buckets: Buckets) => { * const roots = await buckets.list(); * return roots.find((bucket) => bucket.name === "app-name-files") * } * ```` */ async list(): Promise<Root[]> { logger.debug('list request') return bucketsList(this) } /** * Returns information about a bucket path. * @param key Unique (IPNS compatible) identifier key for a bucket. * @param path A file/object (sub)-path within a bucket. * @param depth (optional) will walk the entire bucket to target depth (default = 1) */ async listPath(key: string, path: string, depth = 1): Promise<Path> { logger.debug('list path request') return await listPathRecursive(this, key, path, depth) } /** * listPathRecursive returns a nested object of all paths (and info) in a bucket * @param key Unique (IPNS compatible) identifier key for a bucket. * @param path A file/object (sub)-path within a bucket. * @param dirs (optional) if false will include only file paths * @param depth (optional) will walk the entire bucket to target depth (default = 1) * * @example * ```typescript * import { Buckets } from '@textile/hub' * * async function printPaths(buckets: Buckets, bucketKey: string) { * const list = await buckets.listPathFlat(bucketKey, '') * console.log(list) * } * // [ * // '.textileseed', * // 'dir1', * // 'dir1/file1.jpg', * // 'path', * // 'path/to', * // 'path/to/file2.jpg' * // ] * ``` */ async listPathFlat( key: string, path: string, dirs = true, depth = 5, ): Promise<Array<string>> { logger.debug('list path recursive request') return await listPathFlat(this, key, path, dirs, depth) } /** * listIpfsPath returns items at a particular path in a UnixFS path living in the IPFS network. * @param path UnixFS path */ async listIpfsPath(path: string): Promise<PathItem | undefined> { logger.debug('list path request') return bucketsListIpfsPath(this, path) } /** * Move a file or subpath to a new path. * @param key Unique (IPNS compatible) identifier key for a bucket. * @param fromPath A file/object or subpath within a bucket. * @param toPath The path within a bucket to move fromPath to. * * @example * Push a file to the root of a bucket * ```typescript * import { Buckets } from '@textile/hub' * * const moveToRoot = async (buckets: Buckets, key: string, fromPath: string) => { * return await buckets.movePath(key, fromPath, "") * } * ``` */ async movePath(key: string, fromPath: string, toPath: string): Promise<void> { return bucketsMovePath(this, key, fromPath, toPath) } /** * Pushes a file to a bucket path. * @param key Unique (IPNS compatible) identifier key for a bucket. * @param path A file/object (sub)-path within a bucket. * @param input The input file/stream/object. * @param opts Options to control response stream. * @remarks * - This will return the resolved path and the bucket's new root path. * - If pushing NodeJS streams, ensure you set your highwatermark to an appropriate size * (i.e., ~1024 bytes) for optimal behavior on slow or intermittent connections. See example * below or use `utils.createReadStream`. * @example * Push a file to the root of a bucket * ```typescript * import { Buckets } from '@textile/hub' * * const pushFile = async (buckets: Buckets, content: string, bucketKey: string) => { * const file = { path: '/index.html', content: Buffer.from(content) } * return await buckets.pushPath(bucketKey!, 'index.html', file) * } * ``` * * @example * Push an folder in node.js * ```typescript * import fs from 'fs' * import util from 'util' * import glob from 'glob' * import { Buckets } from '@textile/hub' * * const globDir = util.promisify(glob) * * // expects an already setup buckets session using getOrCreate or withThread * const exists = async (buckets: Buckets, bucketKey: string, dir: string) => { * const files = await globDir('<dir glob options>') * return await Promise.all(files.map(async (file) => { * const filePath = dir + '/' + file * var content = fs.createReadStream(filePath, { highWaterMark: 1024 }); * const upload = { * path: file, * content * } * return await buckets.pushPath(bucketKey, file, upload) * })) * } * ``` */ async pushPath( key: string, path: string, input: any, options?: PushOptions, ): Promise<PushPathResult> { return bucketsPushPath(this, key, path, input, options) } /** * Pushes an iterable of files to a bucket. * @param key Unique (IPNS compatible) identifier key for a bucket. * @param input The input array of file/stream/objects. * @param options PushOptions to control response stream. * @example * Push all files in a directory to the root of a bucket * ```typescript * import fs from 'fs' * import path from 'path' * import util from 'util' * import glob from 'glob' * import { Buckets } from '@textile/hub' * * const globDir = util.promisify(glob) * * const pushMultipleFiles = async (buckets: Buckets, bucketKey: string, directory: string, globPattern: string) => { * const options = { * directory, * nodir: true, * } * const files = await globDir(globPattern, options) * if (files.length === 0) { * throw Error(`No files found: ${directory}`) * } * * let streams = [] * for (const file of files) { * const stream = fs.createReadStream( * path.join(directory, file), { * highWaterMark: 1024, * } * ) * streams.push({ * path: file, * content: stream, * }) * } * return await buckets.pushPaths(bucketKey, streams) * } * ``` */ pushPaths( key: string, input: any, options?: PushOptions, ): AsyncIterableIterator<PushPathsResult> { return bucketsPushPaths(this, key, input, options) } /** * Pulls the bucket path, returning the bytes of the given file. * @param key Unique (IPNS compatible) identifier key for a bucket. * @param path A file/object (sub)-path within a bucket. * @param opts Options to control response stream. Currently only supports a progress function. * * @example * Pull a file by its relative path and console.log the progress. * ```typescript * import { Buckets } from '@textile/hub' * * const pullFile = async (buckets: Buckets, key: string, path: string) => { * const display = (num?: number) => { * console.log('Progress:', num) * } * buckets.pullPath(key, path, {progress: display}) * } * ``` */ pullPath( key: string, path: string, options?: { progress?: (num?: number) => void }, ): AsyncIterableIterator<Uint8Array> { return bucketsPullPath(this, key, path, options) } /** * Pushes a file to a bucket path. * @param key Unique (IPNS compatible) identifier key for a bucket. * @param path A file/object (sub)-path within a bucket. * @param cid The IPFS cid of the dag to set at the path. * * @example * Push a file to the root of a bucket * ```typescript * import { Buckets } from '@textile/hub' * * const pushRoot = async (buckets: Buckets, key: string, cid: string) => { * return await buckets.setPath(key, '/', cid) * } * ``` */ async setPath(key: string, path: string, cid: string): Promise<void> { return bucketsSetPath(this, key, path, cid) } /** * pullIpfsPath pulls the path from a remote UnixFS dag, writing it to writer if it's a file. * @param path A file/object (sub)-path within a bucket. * @param opts Options to control response stream. Currently only supports a progress function. * * @example * Pull a file by its IPFS path and console.log the progress. * ```typescript * import { Buckets } from '@textile/hub' * * const pullFile = async (buckets: Buckets, path: string) => { * const display = (num?: number) => { * console.log('Progress:', num) * } * buckets.pullIpfsPath(path, {progress: display}) * } * ``` */ pullIpfsPath( path: string, options?: { progress?: (num?: number) => void }, ): AsyncIterableIterator<Uint8Array> { return bucketsPullIpfsPath(this, path, options) } /** * Removes an entire bucket. Files and directories will be unpinned (cannot be undone). * @param key Unique (IPNS compatible) identifier key for a bucket. * * @example * Remove a Bucket * ```typescript * import { Buckets } from '@textile/hub' * * const remove = async (buckets: Buckets, key: string) => { * buckets.remove(key) * } * ``` */ async remove(key: string): Promise<void> { logger.debug('remove request') return bucketsRemove(this, key) } /** * Returns information about a bucket path (cannot be undone). * * @param key Unique (IPNS compatible) identifier key for a bucket. * @param path A relative path within a bucket. * @param root optional to specify a root. * * @example * Remove a file by its relative path * ```typescript * import { Buckets } from '@textile/hub' * * const remove = async (buckets: Buckets, key: string) => { * buckets.remove(key) * } * ``` */ async removePath( key: string, path: string, options?: RemovePathOptions, ): Promise<RemovePathResponse> { logger.debug('remove path request') return bucketsRemovePath(this, key, path, options) } /** * Push new access roles per path in a Bucket * * @param key Unique (IPNS compatible) identifier key for a bucket. * @param path A relative path within a bucket. * @param roles Each user public key and the roles they will receive. * * @example * ```typescript * import { Buckets, PublicKey } from '@textile/hub' * * const grant = async (buckets: Buckets, key: string, peer: PublicKey) => { * const roles = new Map() * // NA = 0, Reader = 1, Writer = 2, Admin = 3 * roles.set(peer.toString(), 2) * buckets.pushPathAccessRoles(key, '/', roles) * } * ``` * @example * Grant read access to everyone at a path (in an encrypted bucket) * ```typescript * import { Buckets } from '@textile/hub' * * const grant = async (buckets: Buckets, key: string) => { * const roles = new Map() * // NA = 0, Reader = 1, Writer = 2, Admin = 3 * roles.set('*', 1) * buckets.pushPathAccessRoles(key, '/folder/containing/shared/things', roles) * } * ``` */ async pushPathAccessRoles( key: string, path: string, roles: Map<string, PathAccessRole>, ): Promise<void> { logger.debug('push path access roles request') return bucketsPushPathAccessRoles(this, key, path, roles) } /** * List the access roles per path in a Bucket * * @param key Unique (IPNS compatible) identifier key for a bucket. * @param path A relative path within a bucket. * * @example * ```typescript * import { Buckets } from '@textile/hub' * * const viewRoot = async (buckets: Buckets, key: string) => { * const list = buckets.pullPathAccessRoles(key, '/') * console.log(list) * } * ``` */ async pullPathAccessRoles( key: string, path?: string, ): Promise<Map<string, 0 | 1 | 2 | 3>> { logger.debug('pull path access roles request') return bucketsPullPathAccessRoles(this, key, path) } /** * (Experimental) Get the current default ArchiveConfig for the specified Bucket. * * @beta * @param key Unique (IPNS compatible) identifier key for a bucket. * @returns The default ArchiveConfig for the specified Bucket. * * @example * Get the default ArchiveConfig * ```typescript * import { Buckets } from '@textile/hub' * * async function getDefaultConfig (buckets: Buckets, key: string) { * const defaultConfig = await buckets.defaultArchiveConfig(key) * } * ``` */ async defaultArchiveConfig(key: string): Promise<ArchiveConfig> { logger.debug('default archive config request') return bucketsDefaultArchiveConfig(this, key) } /** * (Experimental) Set the default ArchiveConfig for the specified Bucket. * * @beta * @param key Unique (IPNS compatible) identifier key for a bucket. * @param config The ArchiveConfig to set as the new default. * * @example * Set the default ArchiveConfig * ```typescript * import { Buckets, ArchiveConfig } from '@textile/hub' * * async function setDefaultConfig (buckets: Buckets, key: string, config: ArchiveConfig) { * await buckets.setDefaultArchiveConfig(key, config) * } * ``` */ async setDefaultArchiveConfig( key: string, config: ArchiveConfig, ): Promise<void> { logger.debug('set default archive config request') return bucketsSetDefaultArchiveConfig(this, key, config) } /** * (Experimental) Store a snapshot of the bucket on Filecoin. * @remarks * Filecoin support is experimental. By using Textile, you * are acknowledging that you understand there may be risks to * storing your content on or using decentralized storage * services. * * @beta * @param key Unique (IPNS compatible) identifier key for a bucket. * @param options An object to set options that control the behavor of archive. * @param skipAutomaticVerifiedDeal skips logic that automatically uses available datacap to make a verified deal for the archive. * * @example * Archive a Bucket. * ```typescript * import { Buckets } from '@textile/hub' * * async function archive (buckets: Buckets, key: string) { * await buckets.archive(key) * } * ``` */ async archive(key: string, options?: ArchiveOptions, skipAutomaticVerifiedDeal?: boolean): Promise<void> { logger.debug('archive request') return bucketsArchive(this, key, options, skipAutomaticVerifiedDeal) } /** * archives returns the curent and historical archives for a Bucket. * @beta * @param key Unique (IPNS compatible) identifier key for a bucket. * * @example * Get current and historical archives * ```typescript * import { Buckets } from '@textile/hub' * * async function status (buckets: Buckets, key: string) { * const { current, history } = await buckets.archives(key) * } * ``` */ async archives(key: string): Promise<Archives> { logger.debug('archives request') return bucketsArchives(this, key) } /** * archiveWatch watches status events from a Filecoin bucket archive. * @beta * @param key Unique (IPNS compatible) identifier key for a bucket. * * @example * Watch deal state changes for a active bucket archive request. * ```typescript * import { Buckets } from '@textile/hub' * * async function logChanges (buckets: Buckets, key: string) { * const log = (reply?: {id?: string, msg: string}, err?: Error | undefined) => { * if (err || !reply) return console.log(err) * console.log(reply.id, reply.msg) * } * buckets.archiveWatch(key, log) * } * ``` */ async archiveWatch( key: string, callback: ( reply?: { id: string | undefined; msg: string }, err?: Error, ) => void, ): Promise<() => void> { logger.debug('archive watch request') return bucketsArchiveWatch(this, key, callback) } }
the_stack
import "./helpers/dotenv_helper"; import { getTestId, dispatch, getState } from "./helpers/test_helper"; import { envkeyFetch } from "./helpers/fetch_helper"; import { graphTypes } from "@core/lib/graph"; import { getAuth } from "@core/lib/client"; import * as R from "ramda"; import { createBlock } from "./helpers/blocks_helper"; import { registerWithEmail, loadAccount } from "./helpers/auth_helper"; import { createApp } from "./helpers/apps_helper"; import { Api, Model, Logs, Client } from "@core/types"; import { updateEnvs, updateLocals, getEnvironments, } from "./helpers/envs_helper"; import { acceptInvite } from "./helpers/invites_helper"; import { acceptDeviceGrant } from "./helpers/device_grants_helper"; import { log } from "@core/lib/utils/logger"; describe("fetching logs", () => { let ownerId: string, ownerDeviceId: string, orgId: string, appId: string, appToDeleteId: string, blockId: string, inviteeId: string, inviteeOriginalDeviceId: string, inviteeNewDeviceId: string, development: Model.Environment, staging: Model.Environment, localEnvkeyIdPart: string, localEncryptionKey: string, developmentEnvkeyIdPart: string, developmentEncryptionKey: string, stagingEnvkeyIdPart: string, stagingEncryptionKey: string, testStart: number, time1: number, time2: number; beforeEach(async () => { testStart = Date.now(); const email = `success+${getTestId()}@simulator.amazonses.com`; ({ orgId, userId: ownerId, deviceId: ownerDeviceId, } = await registerWithEmail(email)); let state = getState(ownerId); // to test deleted graph const { id: toDeleteId } = await createApp(ownerId); await dispatch( { type: Api.ActionType.DELETE_APP, payload: { id: toDeleteId, }, }, ownerId ); ({ id: appId } = await createApp(ownerId)); ({ id: blockId } = await createBlock(ownerId)); await updateEnvs(ownerId, appId); await updateLocals(ownerId, appId); await updateEnvs(ownerId, blockId); await updateLocals(ownerId, blockId); time1 = Date.now(); const { orgRoles } = graphTypes(state.graph), adminRole = R.indexBy(R.prop("name"), orgRoles)["Org Admin"]; await dispatch<Client.Action.ClientActions["InviteUsers"]>( { type: Client.ActionType.INVITE_USERS, payload: [ { user: { firstName: "Invited", lastName: "User", email: `success+invited-user-${getTestId()}@simulator.amazonses.com`, provider: <const>"email", uid: `success+invited-user-${getTestId()}@simulator.amazonses.com`, orgRoleId: adminRole.id, }, }, ], }, ownerId ); state = getState(ownerId); const inviteParams = state.generatedInvites[0]; inviteeId = inviteParams.user.id; await acceptInvite(inviteParams); state = getState(inviteeId); inviteeOriginalDeviceId = getAuth<Client.ClientUserAuth>( state, inviteeId )!.deviceId; [development, staging] = getEnvironments(inviteeId, appId); await dispatch( { type: Client.ActionType.CREATE_LOCAL_KEY, payload: { appId, name: "Development Key", environmentId: development.id, }, }, inviteeId ); await dispatch<Client.Action.ClientActions["CreateServer"]>( { type: Client.ActionType.CREATE_SERVER, payload: { appId, name: "Development Server", environmentId: development.id, }, }, inviteeId ); await dispatch<Client.Action.ClientActions["CreateServer"]>( { type: Client.ActionType.CREATE_SERVER, payload: { appId, name: "Staging Server", environmentId: staging.id, }, }, inviteeId ); state = getState(inviteeId); [ { envkeyIdPart: localEnvkeyIdPart, encryptionKey: localEncryptionKey }, { envkeyIdPart: developmentEnvkeyIdPart, encryptionKey: developmentEncryptionKey, }, { envkeyIdPart: stagingEnvkeyIdPart, encryptionKey: stagingEncryptionKey, }, ] = Object.values(state.generatedEnvkeys); state = getState(ownerId); await dispatch( { type: Client.ActionType.FORGET_DEVICE, payload: { accountId: inviteeId, }, }, inviteeId ); await loadAccount(ownerId); await dispatch( { type: Client.ActionType.APPROVE_DEVICES, payload: [{ granteeId: inviteeId }], }, ownerId ); state = getState(ownerId); const generatedDeviceGrant = state.generatedDeviceGrants[0]; await acceptDeviceGrant(inviteeId, generatedDeviceGrant); state = getState(inviteeId); inviteeNewDeviceId = getAuth<Client.ClientUserAuth>( state, inviteeId )!.deviceId; await updateEnvs(inviteeId, appId); await updateEnvs(inviteeId, blockId); ({ id: appToDeleteId } = await createApp(ownerId)); await dispatch( { type: Api.ActionType.DELETE_APP, payload: { id: appToDeleteId }, }, ownerId ); time2 = Date.now(); await Promise.all([ envkeyFetch(developmentEnvkeyIdPart, developmentEncryptionKey), envkeyFetch(stagingEnvkeyIdPart, stagingEncryptionKey), ]); }); test("paging, filtering, sorting, clearing", async () => { await loadAccount(ownerId); let state = getState(ownerId); const firstPagePromise = dispatch( { type: Api.ActionType.FETCH_LOGS, payload: { pageNum: 0, pageSize: 9, scope: <const>"org", loggableTypes: Logs.ORG_LOGGABLE_TYPES, }, }, ownerId ); state = getState(ownerId); expect(state.isFetchingLogs).toBeTrue(); expect(state.fetchLogParams).toBeUndefined(); const firstPageRes = await firstPagePromise; expect(firstPageRes.success).toBe(true); state = getState(ownerId); expect(state.isFetchingLogs).toBeUndefined(); expect(state.fetchLogParams).toEqual({ pageSize: 9, scope: <const>"org", loggableTypes: Logs.ORG_LOGGABLE_TYPES, }); expect(state.loggedActionsWithTransactionIds.length).toBe(9); expect(state.logsTotalCount).toBeNumber(); expect(Object.keys(state.deletedGraph).length).toBeGreaterThan(0); expect( state.loggedActionsWithTransactionIds.flatMap(([, actions]) => actions.map(R.prop("actionType")) ) ).toEqual([ Api.ActionType.REGISTER, Api.ActionType.CREATE_DEVICE_GRANT, Api.ActionType.LOAD_DEVICE_GRANT, Api.ActionType.ACCEPT_DEVICE_GRANT, Api.ActionType.CREATE_APP, Api.ActionType.DELETE_APP, Api.ActionType.CREATE_APP, Api.ActionType.CREATE_BLOCK, Api.ActionType.UPDATE_ENVS, ]); const secondPagePromise = dispatch( { type: Api.ActionType.FETCH_LOGS, payload: { pageNum: 1, pageSize: 9, scope: <const>"org", loggableTypes: Logs.ORG_LOGGABLE_TYPES, }, }, ownerId ); state = getState(ownerId); expect(state.isFetchingLogs).toBeTrue(); expect(state.logsTotalCount).toBeNumber(); expect(state.fetchLogParams).toEqual({ pageSize: 9, scope: <const>"org", loggableTypes: Logs.ORG_LOGGABLE_TYPES, }); expect( state.loggedActionsWithTransactionIds.flatMap(([, actions]) => actions.map(R.prop("actionType")) ) ).toEqual([ Api.ActionType.REGISTER, Api.ActionType.CREATE_DEVICE_GRANT, Api.ActionType.LOAD_DEVICE_GRANT, Api.ActionType.ACCEPT_DEVICE_GRANT, Api.ActionType.CREATE_APP, Api.ActionType.DELETE_APP, Api.ActionType.CREATE_APP, Api.ActionType.CREATE_BLOCK, Api.ActionType.UPDATE_ENVS, ]); const secondPageRes = await secondPagePromise; expect(secondPageRes.success).toBe(true); state = getState(ownerId); expect(state.isFetchingLogs).toBeUndefined(); expect(state.loggedActionsWithTransactionIds.length).toBe(18); expect( state.loggedActionsWithTransactionIds.flatMap(([, actions]) => actions.map(R.prop("actionType")) ) ).toEqual([ Api.ActionType.REGISTER, Api.ActionType.CREATE_DEVICE_GRANT, Api.ActionType.LOAD_DEVICE_GRANT, Api.ActionType.ACCEPT_DEVICE_GRANT, Api.ActionType.CREATE_APP, Api.ActionType.DELETE_APP, Api.ActionType.CREATE_APP, Api.ActionType.CREATE_BLOCK, Api.ActionType.UPDATE_ENVS, Api.ActionType.UPDATE_ENVS, Api.ActionType.UPDATE_ENVS, Api.ActionType.UPDATE_ENVS, Api.ActionType.FETCH_ENVS, Api.ActionType.CREATE_INVITE, Api.ActionType.LOAD_INVITE, Api.ActionType.ACCEPT_INVITE, Api.ActionType.CREATE_LOCAL_KEY, Api.ActionType.GENERATE_KEY, ]); // update filters - ensure that logs get cleared const updateFiltersPromise = dispatch( { type: Api.ActionType.FETCH_LOGS, payload: { pageNum: 0, pageSize: 2, scope: <const>"org", loggableTypes: ["orgAction"], }, }, ownerId ); state = getState(ownerId); expect(state.isFetchingLogs).toBeTrue(); expect(state.deletedGraph).toBeObject(); expect(state.logsTotalCount).toBeUndefined(); expect(state.loggedActionsWithTransactionIds).toEqual([]); const updateFiltersRes = await updateFiltersPromise; expect(updateFiltersRes.success).toBe(true); state = getState(ownerId); expect(state.isFetchingLogs).toBeUndefined(); expect(state.logsTotalCount).toBeNumber(); expect(state.loggedActionsWithTransactionIds.length).toBeGreaterThan(0); expect( state.loggedActionsWithTransactionIds.flatMap(([, actions]) => actions.map(R.prop("actionType")) ) ).toEqual([ Api.ActionType.CREATE_DEVICE_GRANT, Api.ActionType.ACCEPT_DEVICE_GRANT, ]); // clear logs await dispatch({ type: Client.ActionType.CLEAR_LOGS }, ownerId); state = getState(ownerId); expect(state.fetchLogParams).toBeUndefined(); expect(state.loggedActionsWithTransactionIds).toEqual([]); expect(state.deletedGraph).toEqual({}); expect(state.logsTotalCount).toBeUndefined(); // sort descending await dispatch( { type: Api.ActionType.FETCH_LOGS, payload: { pageNum: 0, pageSize: 5, scope: <const>"org", loggableTypes: Logs.ORG_LOGGABLE_TYPES, sortDesc: true, }, }, ownerId ); state = getState(ownerId); expect( state.loggedActionsWithTransactionIds.flatMap(([, actions]) => actions.map(R.prop("actionType")) ) ).toIncludeAllMembers([ Api.ActionType.FETCH_LOGS, Api.ActionType.FETCH_LOGS, Api.ActionType.FETCH_LOGS, ]); // time range await dispatch( { type: Api.ActionType.FETCH_LOGS, payload: { pageNum: 0, pageSize: 6, scope: <const>"org", loggableTypes: Logs.ORG_LOGGABLE_TYPES, startsAt: time1, endsAt: time2, }, }, ownerId ); state = getState(ownerId); expect( state.loggedActionsWithTransactionIds.flatMap(([, actions]) => actions.map(R.prop("actionType")) ) ).toEqual([ Api.ActionType.FETCH_ENVS, Api.ActionType.CREATE_INVITE, Api.ActionType.LOAD_INVITE, Api.ActionType.ACCEPT_INVITE, Api.ActionType.CREATE_LOCAL_KEY, Api.ActionType.GENERATE_KEY, ]); // time range deleted graph await dispatch( { type: Api.ActionType.FETCH_LOGS, payload: { pageNum: 0, pageSize: 100, scope: <const>"org", loggableTypes: Logs.ORG_LOGGABLE_TYPES, startsAt: time1, endsAt: time2, }, }, ownerId ); state = getState(ownerId); // user logs await dispatch( { type: Api.ActionType.FETCH_LOGS, payload: { pageNum: 0, pageSize: 3, scope: <const>"org", loggableTypes: Logs.ORG_LOGGABLE_TYPES, userIds: [inviteeId], }, }, ownerId ); state = getState(ownerId); expect( state.loggedActionsWithTransactionIds.flatMap(([, actions]) => actions.map(R.prop("actionType")) ) ).toEqual([ Api.ActionType.CREATE_INVITE, Api.ActionType.LOAD_INVITE, Api.ActionType.ACCEPT_INVITE, ]); await dispatch( { type: Api.ActionType.FETCH_LOGS, payload: { pageNum: 0, pageSize: 4, scope: <const>"org", loggableTypes: ["fetchMetaAction"], userIds: [ownerId, inviteeId], }, }, ownerId ); state = getState(ownerId); expect( state.loggedActionsWithTransactionIds.flatMap(([, actions]) => actions.map(R.prop("actionType")) ) ).toEqual([ Api.ActionType.LOAD_DEVICE_GRANT, Api.ActionType.FETCH_ENVS, Api.ActionType.LOAD_INVITE, Api.ActionType.GET_SESSION, ]); // device await dispatch( { type: Api.ActionType.FETCH_LOGS, payload: { pageNum: 0, pageSize: 3, scope: <const>"org", loggableTypes: ["orgAction"], deviceIds: [inviteeNewDeviceId], }, }, ownerId ); state = getState(ownerId); expect( state.loggedActionsWithTransactionIds.flatMap(([, actions]) => actions.map(R.prop("actionType")) ) ).toEqual([ Api.ActionType.ACCEPT_DEVICE_GRANT, Api.ActionType.UPDATE_ENVS, Api.ActionType.UPDATE_ENVS, ]); await dispatch( { type: Api.ActionType.FETCH_LOGS, payload: { pageNum: 0, pageSize: 3, scope: <const>"org", loggableTypes: ["fetchMetaAction"], actionTypes: [Api.ActionType.LOAD_INVITE, Api.ActionType.GET_SESSION], deviceIds: [ownerDeviceId, inviteeOriginalDeviceId], }, }, ownerId ); state = getState(ownerId); expect( state.loggedActionsWithTransactionIds.flatMap(([, actions]) => actions.map(R.prop("actionType")) ) ).toEqual([ Api.ActionType.LOAD_INVITE, Api.ActionType.GET_SESSION, Api.ActionType.GET_SESSION, ]); // targets await dispatch( { type: Api.ActionType.FETCH_LOGS, payload: { pageNum: 0, pageSize: 3, scope: <const>"org", loggableTypes: Logs.ORG_LOGGABLE_TYPES, targetIds: [appId], }, }, ownerId ); state = getState(ownerId); expect( state.loggedActionsWithTransactionIds.flatMap(([, actions]) => actions.map(R.prop("actionType")) ) ).toEqual([ Api.ActionType.CREATE_APP, Api.ActionType.UPDATE_ENVS, Api.ActionType.UPDATE_ENVS, ]); await dispatch( { type: Api.ActionType.FETCH_LOGS, payload: { pageNum: 0, pageSize: 3, scope: <const>"org", loggableTypes: ["fetchEnvkeyAction"], targetIds: [development.id], }, }, ownerId ); state = getState(ownerId); expect( state.loggedActionsWithTransactionIds.flatMap(([, actions]) => actions.map(R.prop("actionType")) ) ).toEqual([Api.ActionType.FETCH_ENVKEY]); // host logs - this doesn't play nice with parallel tests :-/ // await dispatch( // { // type: Api.ActionType.FETCH_LOGS, // payload: { // pageNum: 0, // pageSize: 3, // scope: <const>"host", // orgIds: [orgId], // startsAt: testStart, // }, // }, // ownerId // ); // state = getState(ownerId); // expect(state.loggedActionsWithTransactionIds.flatMap(([,actions])=> actions.map(R.prop("actionType")))).toEqual([ // Api.ActionType.CREATE_EMAIL_VERIFICATION, // Api.ActionType.REGISTER, // ]); }); test("fetch deleted graph", async () => { await loadAccount(ownerId); let state = getState(ownerId); const promise = dispatch( { type: Api.ActionType.FETCH_DELETED_GRAPH, payload: {}, }, ownerId ); state = getState(ownerId); expect(state.isFetchingDeletedGraph).toBeTrue(); const res = await promise; expect(res.success).toBe(true); state = getState(ownerId); expect(state.isFetchingDeletedGraph).toBeUndefined(); expect(Object.keys(state.deletedGraph).length).toBeGreaterThan(0); }); });
the_stack
import { Tagged } from "../../Case" import * as Clock from "../../Clock" import * as ClockId from "../../Clock/id" import * as Chunk from "../../Collections/Immutable/Chunk" import * as HashMap from "../../Collections/Immutable/HashMap" import * as List from "../../Collections/Immutable/List" import * as SortedSet from "../../Collections/Immutable/SortedSet" import * as Tuple from "../../Collections/Immutable/Tuple" import * as T from "../../Effect" import * as Fiber from "../../Fiber" import { identity, pipe } from "../../Function" import type { Has } from "../../Has" import { tag } from "../../Has" import * as L from "../../Layer" import * as M from "../../Managed" import * as O from "../../Option" import * as Ord from "../../Ord" import * as Promise from "../../Promise" import * as Ref from "../../Ref" import * as RefM from "../../RefM" import * as St from "../../Structural" import { Annotations } from "../Annotations" import { fiberSet } from "../FiberSet" import { Live } from "../Live" import type { Restorable } from "../Restorable" import { fibers } from "../TestAnnotation" export interface DurationBrand { readonly DurationBrand: unique symbol } export type Duration = number & DurationBrand export function Duration(n: number): Duration { return n as Duration } /** * `TestClock` makes it easy to deterministically and efficiently test * effects involving the passage of time. * * Instead of waiting for actual time to pass, `sleep` and methods * implemented in terms of it schedule effects to take place at a given clock * time. Users can adjust the clock time using the `adjust` and `setTime` * methods, and all effects scheduled to take place on or before that time * will automatically be run in order. * * For example, here is how we can test `ZIO#timeout` using `TestClock: * * {{{ * import zio.ZIO * import zio.duration._ * import zio.test.environment.TestClock * * for { * fiber <- ZIO.sleep(5.minutes).timeout(1.minute).fork * _ <- TestClock.adjust(1.minute) * result <- fiber.join * } yield result == None * }}} * * Note how we forked the fiber that `sleep` was invoked on. Calls to `sleep` * and methods derived from it will semantically block until the time is set * to on or after the time they are scheduled to run. If we didn't fork the * fiber on which we called sleep we would never get to set the time on the * line below. Thus, a useful pattern when using `TestClock` is to fork the * effect being tested, then adjust the clock time, and finally verify that * the expected effects have been performed. * * For example, here is how we can test an effect that recurs with a fixed * delay: * * {{{ * import zio.Queue * import zio.duration._ * import zio.test.environment.TestClock * * for { * q <- Queue.unbounded[Unit] * _ <- q.offer(()).delay(60.minutes).forever.fork * a <- q.poll.map(_.isEmpty) * _ <- TestClock.adjust(60.minutes) * b <- q.take.as(true) * c <- q.poll.map(_.isEmpty) * _ <- TestClock.adjust(60.minutes) * d <- q.take.as(true) * e <- q.poll.map(_.isEmpty) * } yield a && b && c && d && e * }}} * * Here we verify that no effect is performed before the recurrence period, * that an effect is performed after the recurrence period, and that the * effect is performed exactly once. The key thing to note here is that after * each recurrence the next recurrence is scheduled to occur at the * appropriate time in the future, so when we adjust the clock by 60 minutes * exactly one value is placed in the queue, and when we adjust the clock by * another 60 minutes exactly one more value is placed in the queue. */ export interface TestClock extends Restorable { readonly serviceId: Clock.ClockId readonly adjust: (duration: number) => T.UIO<void> readonly setTime: (duration: number) => T.UIO<void> readonly sleeps: T.UIO<List.List<Duration>> } export const TestClock = tag<TestClock>(Clock.ClockId) /** * `Data` represents the state of the `TestClock`, including the clock time */ export class Data extends Tagged("Data")<{ readonly duration: Duration readonly sleeps: List.List<Tuple.Tuple<[Duration, Promise.Promise<never, void>]>> }> {} /** * `WarningData` describes the state of the warning message that is * displayed if a test is using time by is not advancing the `TestClock`. * The possible states are `Start` if a test has not used time, `Pending` * if a test has used time but has not adjusted the `TestClock`, and `Done` * if a test has adjusted the `TestClock` or the warning message has * already been displayed. */ export type WarningData = Start | Done | Pending export class Start extends Tagged("Start")<{}> { static of: WarningData = new Start() } export class Done extends Tagged("Done")<{}> { static of: WarningData = new Done() } export class Pending extends Tagged("Pending")<{ readonly fiber: Fiber.Fiber<never, void> }> { static of = (fiber: Fiber.Fiber<never, void>): WarningData => new Pending({ fiber }) } export class Test implements TestClock { readonly serviceId: Clock.ClockId = ClockId.ClockId constructor( readonly clockState: Ref.Ref<Data>, readonly live: Live, readonly annotations: Annotations, readonly warningState: RefM.RefM<WarningData> ) {} /** * Increments the current clock time by the specified duration. Any * effects that were scheduled to occur on or before the new time will be * run in order. */ readonly adjust: (duration: number) => T.UIO<void> = (duration) => { return T.zipRight_( this.warningDone, this.run((_) => Duration(_ + duration)) ) } /** * Returns the current clock time. */ readonly currentTime: T.UIO<Duration> = pipe( Ref.get(this.clockState), T.map((d) => d.duration) ) /** * Saves the `TestClock`'s current state in an effect which, when run, * will restore the `TestClock` state to the saved state */ readonly save: T.UIO<T.UIO<void>> = pipe( T.do, T.bind("clockData", () => Ref.get(this.clockState)), T.map(({ clockData }) => Ref.set_(this.clockState, clockData)) ) /** * Sets the current clock time to the specified time in terms of duration * since the epoch. Any effects that were scheduled to occur on or before * the new time will immediately be run in order. */ readonly setTime: (duration: number) => T.UIO<void> = (dateTime) => pipe(this.warningDone, T.zipRight(this.run(() => Duration(dateTime)))) /** * Semantically blocks the current fiber until the clock time is equal * to or greater than the specified duration. Once the clock time is * adjusted to on or after the duration, the fiber will automatically be * resumed. */ readonly sleep: (duration: Duration) => T.UIO<void> = (duration) => pipe( T.do, T.bind("promise", () => Promise.make<never, void>()), T.bind("shouldAwait", ({ promise }) => pipe( this.clockState, Ref.modify((data) => { const end = Duration(data.duration + duration) if (end > data.duration) { return Tuple.tuple( true, data.copy({ sleeps: pipe(data.sleeps, List.prepend(Tuple.tuple(end, promise))) }) ) } else { return Tuple.tuple(false, data) } }) ) ), T.tap(({ promise, shouldAwait }) => shouldAwait ? pipe(this.warningStart, T.zipRight(Promise.await(promise))) : Promise.succeed_(promise, void 0) ), T.map(() => void 0) ) /** * Returns a list of the times at which all queued effects are scheduled * to resume. */ readonly sleeps: T.UIO<List.List<Duration>> = pipe( this.clockState, Ref.get, T.map((d) => pipe( d.sleeps, List.map((_) => _.get(0)) ) ) ) /** * The warning message that will be displayed if a test is using time but * is not advancing the `TestClock`. */ private warning = "Warning: A test is using time, but is not advancing the test clock, " + "which may result in the test hanging. Use TestClock.adjust to " + "manually advance the time." /** * Forks a fiber that will display a warning message if a test is using * time but is not advancing the `TestClock`. */ private warningStart: T.UIO<void> = pipe( this.warningState, RefM.updateSome((_) => { switch (_._tag) { case "Start": { return pipe( T.do, T.bind("fiber", () => this.live.provide( pipe( T.succeedWith(() => { console.log(this.warning) }), T.delay(5_000), T.interruptible, T.fork ) ) ), T.map(({ fiber }) => Pending.of(fiber)), O.some ) } default: return O.none } }) ) /** * Cancels the warning message that is displayed if a test is using time * but is not advancing the `TestClock`. */ readonly warningDone: T.UIO<void> = pipe( this.warningState, RefM.updateSome((_) => { switch (_._tag) { case "Start": { return O.some(T.succeed(Done.of)) } case "Pending": { return pipe(_.fiber, Fiber.interrupt, T.as(Done.of), O.some) } default: return O.none } }) ) /** * Returns a set of all fibers in this test. */ readonly supervisedFibers: T.UIO< SortedSet.SortedSet<Fiber.Runtime<unknown, unknown>> > = T.descriptorWith((d) => pipe( this.annotations.get(fibers), T.chain((fa) => { switch (fa._tag) { case "Left": { return T.succeed(fiberSet) } case "Right": { return pipe( fa.right, T.forEach((ref) => T.succeedWith(() => ref.get)), T.map(Chunk.reduce(fiberSet, SortedSet.union_)), T.map(SortedSet.filter((_) => !St.equals(_.id, d.id))) ) } } }) ) ) /** * Captures a "snapshot" of the identifier and status of all fibers in * this test other than the current fiber. Fails with the `Unit` value if * any of these fibers are not done or suspended. Note that because we * cannot synchronize on the status of multiple fibers at the same time * this snapshot may not be fully consistent. */ readonly freeze: T.IO<void, HashMap.HashMap<Fiber.FiberID, Fiber.Status>> = pipe( this.supervisedFibers, T.chain( T.reduce(HashMap.make<Fiber.FiberID, Fiber.Status>(), (map, fiber) => pipe( fiber.status, T.chain((status) => { switch (status._tag) { case "Done": { return T.succeed(HashMap.set_(map, fiber.id, status)) } case "Suspended": { return T.succeed(HashMap.set_(map, fiber.id, status)) } default: return T.fail(void 0) } }) ) ) ) ) /** * Delays for a short period of time. */ readonly delay = this.live.provide(T.sleep(5)) /** * Returns whether all descendants of this fiber are done or suspended. */ readonly suspended: T.IO<void, HashMap.HashMap<Fiber.FiberID, Fiber.Status>> = pipe( this.freeze, T.zip(pipe(this.delay, T.zipRight(this.freeze))), T.chain(({ tuple: [first, last] }) => St.equals(first, last) ? T.succeed(first) : T.fail<void>(void 0) ) ) /** * Polls until all descendants of this fiber are done or suspended. */ readonly awaitSuspended: T.UIO<void> = pipe( this.suspended, T.zipWith( pipe(this.live.provide(T.sleep(10)), T.zipRight(this.suspended)), St.equals ), T.filterOrFail(identity, () => void 0 as void), T.eventually, T.asUnit ) /** * Runs all effects scheduled to occur on or before the specified * duration, which may depend on the current time, in order. */ private run: (f: (d: Duration) => Duration) => T.UIO<void> = (f) => pipe( this.awaitSuspended, T.zipRight( pipe( this.clockState, Ref.modify((data) => { const end = f(data.duration) const sorted = List.sortWith_( data.sleeps, Ord.contramap_(Ord.number, (_) => _.get(0)) ) if (!List.isEmpty(sorted)) { const { tuple: [duration, promise] } = List.unsafeFirst(sorted)! const sleeps = List.tail(sorted) if (duration <= end) { return Tuple.tuple( O.some(Tuple.tuple(end, promise)), new Data({ duration, sleeps }) ) } } return Tuple.tuple(O.none, new Data({ duration: end, sleeps: data.sleeps })) }), T.chain((o) => { switch (o._tag) { case "None": { return T.unit } case "Some": { return pipe( Promise.succeed_(o.value.get(1), void 0), T.zipRight(T.yieldNow), T.zipRight(this.run(() => o.value.get(0))) ) } } }) ) ) ) } export function live(data: Data) { return M.gen(function* (_) { const live = yield* _(Live) const annotations = yield* _(Annotations) const ref = yield* _(Ref.makeRef(data)) const refM = yield* _(RefM.makeRefM(Start.of)) const test = yield* _( T.succeedWith(() => new Test(ref, live, annotations, refM))["|>"]( M.make((_) => _.warningDone) ) ) const testClock = TestClock.has(test) return testClock as Has<Clock.Clock> & Has<TestClock> })["|>"](L.fromRawManaged) } export const defaultTestClock = live( new Data({ duration: Duration(0), sleeps: List.empty() }) )
the_stack
import { Component, OnInit, ViewChild, OnDestroy, AfterViewInit } from '@angular/core'; import { CalendarOptions, EventInput } from '@fullcalendar/core'; import { FullCalendarComponent } from '@fullcalendar/angular'; import dayGridPlugin from '@fullcalendar/daygrid'; import timeGrigPlugin from '@fullcalendar/timegrid'; import interactionPlugin from '@fullcalendar/interaction'; import bootstrapPlugin from '@fullcalendar/bootstrap'; import * as moment from 'moment'; import { IAvailabilitySlotsCreateInput, ITimeOff, IAvailabilitySlotsView, IOrganization, IRolePermission, AvailabilitySlotType, ISelectedEmployee, StatusTypesEnum, WeekDaysEnum } from '@gauzy/contracts'; import { first, filter, tap, debounceTime } from 'rxjs/operators'; import { combineLatest, Subject } from 'rxjs'; import { ActivatedRoute } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy'; import { NgxPermissionsService } from 'ngx-permissions'; import { distinctUntilChange, isEmpty, isNotEmpty } from '@gauzy/common-angular'; import { TranslationBaseComponent } from '../../../../@shared/language-base/translation-base.component'; import { AvailabilitySlotsService, ErrorHandlingService, Store, TimeOffService, ToastrService } from './../../../../@core/services'; @UntilDestroy({ checkProperties: true }) @Component({ selector: 'ngx-availability-slots', templateUrl: './availability-slots.component.html' }) export class AvailabilitySlotsComponent extends TranslationBaseComponent implements AfterViewInit, OnInit, OnDestroy { @ViewChild('calendar', { static: false }) calendar: FullCalendarComponent; calendarComponent: FullCalendarComponent; calendarEvents: EventInput[] = []; calendarOptions: CalendarOptions; headerToolbarOptions: { left: string; center: string; right: string; } = { left: 'next', center: 'title', right: 'dayGridMonth,timeGridWeek' }; recurringAvailabilityMode: boolean; dateSelected: boolean; hiddenDays: number[] = []; removedEvents: EventInput[] = []; timeOffs: ITimeOff[] = []; public loading: boolean = true; selectedEmployee: ISelectedEmployee; organization: IOrganization; availableSlots$: Subject<any> = new Subject(); createForm = { startTime: '00:00', endTime: '00:00' }; weekDaysEnum = WeekDaysEnum; constructor( private readonly store: Store, private readonly route: ActivatedRoute, private readonly errorHandler: ErrorHandlingService, private readonly toastrService: ToastrService, private readonly availabilitySlotsService: AvailabilitySlotsService, private readonly timeOffService: TimeOffService, readonly translateService: TranslateService, private readonly ngxPermissionsService: NgxPermissionsService ) { super(translateService); } ngOnInit() { this.getCalendarOption(); this.route.data .pipe(untilDestroyed(this)) .subscribe(({ page }) => { this.recurringAvailabilityMode = (page === 'recurring'); if (page === 'recurring') { delete this.calendarOptions.selectAllow; this.calendarOptions.hiddenDays = []; this.calendarOptions.dayHeaderFormat = { weekday: 'long' }; this.calendarOptions.headerToolbar = { center: '', right: '', left: '' }; } }); this.store.userRolePermissions$ .pipe( filter( (permissions: IRolePermission[]) => isNotEmpty(permissions) ), untilDestroyed(this) ) .subscribe((data) => { const permissions = data.map(({ permission }) => permission); this.ngxPermissionsService.loadPermissions(permissions); }); const storeOrganization$ = this.store.selectedOrganization$; const storeEmployee$ = this.store.selectedEmployee$; combineLatest([storeOrganization$, storeEmployee$]) .pipe( debounceTime(300), filter(([organization]) => !!organization), tap(([organization]) => ( this.organization = organization as IOrganization )), distinctUntilChange(), tap(([organization, employee]) => { const { defaultStartTime, defaultEndTime } = organization; if (defaultStartTime) { this.createForm.startTime = defaultStartTime; } if (defaultEndTime) { this.createForm.endTime = defaultEndTime; } if (employee && employee.id) { this.selectedEmployee = employee; } else { this.selectedEmployee = null; } }), tap(() => this.availableSlots$.next(true)), untilDestroyed(this) ) .subscribe(); } ngAfterViewInit() { this.availableSlots$ .pipe( debounceTime(500), tap(() => this.fetchAvailableSlots()), untilDestroyed(this) ) .subscribe(); } /* * Get calendar option */ getCalendarOption() { let currentDay = moment().day(); while (currentDay > 0) { this.hiddenDays.push(currentDay--); } this.calendarOptions = { initialView: 'timeGridWeek', headerToolbar: this.headerToolbarOptions, themeSystem: 'bootstrap', plugins: [ dayGridPlugin, timeGrigPlugin, interactionPlugin, bootstrapPlugin ], weekends: true, selectable: true, height: 'auto', selectOverlap: false, events: this.getEvents.bind(this), editable: true, eventOverlap: false, hiddenDays: this.hiddenDays, dayHeaderDidMount: this.headerMount.bind(this), eventClick: this.unSelectEvent.bind(this), selectAllow: (select) => moment().diff(select.start) <= 0, select: this.handleSelectRange.bind(this), eventDrop: this.dragDropEvent.bind(this) }; } /* * Schedule Drag & Drop Event Calendar */ async dragDropEvent($event) { const event = $event.event; const { id } = event.extendedProps; const { tenantId } = this.store.user; const { id: organizationId } = this.organization; const input = { startTime: event.start, endTime: event.end, type: this.recurringAvailabilityMode ? AvailabilitySlotType.RECURRING : AvailabilitySlotType.DEFAULT, allDay: event.allDay, organizationId, tenantId }; if (this.selectedEmployee) { input['employeeId'] = this.selectedEmployee.id; } if (event.allDay) { input['endTime'] = new Date( moment(event.start).endOf('day').format('YYYY-MM-DD hh:mm:ss') ); } await this.availabilitySlotsService.update(id, { ...input }); } headerMount(config: any) { if (this.calendar && !this.recurringAvailabilityMode) { const currentStart = this.calendar.getApi().view.currentStart; const currentEnd = this.calendar.getApi().view.currentEnd; const hideDays = moment().isBetween( currentStart, currentEnd, 'day', '[]' ) ? this.hiddenDays : []; this.calendar.getApi().setOption('hiddenDays', hideDays); this.headerToolbarOptions.left = moment(currentStart).isSameOrBefore(moment(),'day') ? 'next' : 'prev,next'; this.calendar .getApi() .setOption('headerToolbar', this.headerToolbarOptions); this.renderTimeOff(config.date); } } renderTimeOff(date) { if (isEmpty(this.timeOffs)) { return; } const isDayOff = this.timeOffs.find( (off: ITimeOff) => off.status === StatusTypesEnum.APPROVED && moment(date).isBetween(off.start, off.end, 'date', '[]') ); if (isDayOff) { this._prepareEvent( { startTime: date, endTime: date, allDay: true }, isDayOff ); } } getEvents(arg, callback) { if (!this.organization) { return null; } callback(this.calendarEvents); } unSelectEvent(o) { if (o.event.extendedProps && o.event.extendedProps.isDayOff) return; if (o.event.extendedProps && o.event.extendedProps.id) { this.removedEvents.push(o.event); this.dateSelected = true; this.saveSelectedDateRange(); } this.calendarEvents = this.calendarEvents.filter( (e) => !moment(e.start).isSame(moment(o.event.start)) ); this.calendar.getApi().refetchEvents(); } handleSelectRange(o) { this.dateSelected = true; this._prepareEvent({ startTime: o.start, endTime: o.end, allDay: o.allDay }); this.saveSelectedDateRange(); } async setSchedule() { if (!this.selectedEmployee) { this.toastrService.danger('SCHEDULE.SELECT_EMPLOYEE'); return; } const { tenantId } = this.store.user; const { id: organizationId, startWeekOn } = this.organization; const { id: employeeId } = this.selectedEmployee; const payload: IAvailabilitySlotsCreateInput[] = []; const calender = this.calendar.getApi(); const range = calender.getCurrentData().dateProfile.currentRange; let start = range.start; while (start < range.end) { const date = moment(start).format('YYYY-MM-DD'); let days = []; if (startWeekOn === WeekDaysEnum.MONDAY) { days = [0, 1, 2, 3, 4]; } else { days = [6, 0, 1, 2, 3]; } if (days.indexOf(moment(start).weekday()) >= 0) { payload.push({ startTime: moment(date + " " + this.createForm.startTime).toDate(), endTime: moment(date + " " + this.createForm.endTime).toDate(), employeeId, organizationId, tenantId, type: this.recurringAvailabilityMode ? AvailabilitySlotType.RECURRING : AvailabilitySlotType.DEFAULT, allDay: false }); } start = moment(start).add(1, 'day').toDate(); } await this.availabilitySlotsService.createBulk(payload); this.availableSlots$.next(true); } async saveSelectedDateRange() { if (!this.selectedEmployee) { this.toastrService.danger('SCHEDULE.SELECT_EMPLOYEE'); return; } try { const { tenantId } = this.store.user; const { id: organizationId } = this.organization; const { id: employeeId } = this.selectedEmployee; const payload: IAvailabilitySlotsCreateInput[] = []; for (const e of this.calendarEvents) { if (!e.extendedProps['id']) { payload.push({ startTime: new Date(e.start.toString()), endTime: new Date(e.end.toString()), employeeId, organizationId, tenantId, type: this.recurringAvailabilityMode ? AvailabilitySlotType.RECURRING : AvailabilitySlotType.DEFAULT, allDay: e.allDay }); } } if (isNotEmpty(payload)) { await this.availabilitySlotsService.createBulk(payload); } for (const e of this.removedEvents) { await this.availabilitySlotsService.delete( e.extendedProps['id'] ); } this.toastrService.success('NOTES.AVAILABILITY_SLOTS.SAVE'); this.removedEvents = []; this.availableSlots$.next(true) this.dateSelected = false; } catch (error) { this.errorHandler.handleError(error); } } async fetchTimeOff() { const { tenantId } = this.store.user; const { id: organizationId } = this.organization; let request: any = { organizationId, tenantId } if (this.selectedEmployee) { const { id: employeeId } = this.selectedEmployee; request = { ...request, employeeId } } const { items = [] } = await this.timeOffService .getAllTimeOffRecords(['employees', 'employees.user'], { ...request }) .pipe(first()) .toPromise(); this.timeOffs = items; } async fetchAvailableSlots() { this.calendarEvents = []; const { tenantId } = this.store.user; const { id: organizationId } = this.organization; let findObj: any = { type: this.recurringAvailabilityMode ? AvailabilitySlotType.RECURRING : AvailabilitySlotType.DEFAULT, organizationId, tenantId }; if (this.selectedEmployee) { findObj = { ...findObj, employeeId: this.selectedEmployee.id } } try { this.loading = false; if (!this.recurringAvailabilityMode) { await this.fetchTimeOff(); } const slots = await this.availabilitySlotsService.getAll( [], findObj ); const start = this.calendar.getApi().view.currentStart; const end = this.calendar.getApi().view.currentEnd; let date = moment(start); if (!this.recurringAvailabilityMode) { while (moment(end).diff(date, 'day') > 0) { this.renderTimeOff(new Date(date.format())); date = date.add(1, 'day'); } } for (const item of slots.items) { if (this.recurringAvailabilityMode) { // Convert recurring events to current date range of full calendar const startDay = moment(item.startTime).day(); const startHours = moment(item.startTime).hours(); const startMinutes = moment(item.startTime).minutes(); const endDay = moment(item.endTime).day(); const endHours = moment(item.endTime).hours(); const endMinutes = moment(item.endTime).minutes(); const eventStartDate = moment(start) .add(startDay, 'days') .set('hours', startHours) .set('minutes', startMinutes); const eventEndDate = moment(start) .add(endDay, 'days') .set('hours', endHours) .set('minutes', endMinutes); item.startTime = new Date(eventStartDate.format()); item.endTime = new Date(eventEndDate.format()); } this._prepareEvent(item); } this.calendar.getApi().refetchEvents(); } catch (error) { this.toastrService.danger('NOTES.AVAILABILITY_SLOTS.ERROR', null, { error: error.message || error.error.message }); } } private _prepareEvent( slot: IAvailabilitySlotsView, isDayOff: ITimeOff = null ) { const eventStartTime = slot.startTime; const eventEndTime = slot.endTime; const find = this.calendarEvents.find( (event) => moment(event.start).format() === moment(slot.startTime).format() ); if (!!find) return; this.calendarEvents.push({ start: eventStartTime, end: eventEndTime, allDay: slot.allDay, color: isDayOff ? 'red' : 'seablue', extendedProps: { id: slot.id, isDayOff: isDayOff ? true : false } }); this.calendar.getApi().refetchEvents(); } ngOnDestroy() {} }
the_stack
import * as vscode from 'vscode'; import * as cp from 'child_process'; import * as http from 'http'; import * as net from 'net'; import * as url from 'url'; import * as path from 'path'; import * as fs from 'fs'; import * as websockets from 'ws'; import { getConfig } from './config'; import compileDocs, { draftRoot } from './compile'; import { fileList, draftsObject} from './compile'; import {CharacterCounter, CharacterCounterController} from './charactorcount'; import { editorText, OriginEditor } from './editor' import { urlToOptions } from 'vscode-test/out/util'; import { eventNames } from 'process'; import { EventEmitter } from 'stream'; const output = vscode.window.createOutputChannel("Novel"); //リソースとなるhtmlファイル let html: Buffer; let documentRoot: vscode.Uri; let WebViewPanel = false; let servicePort = 8080; emptyPort(function(port:number) { servicePort = port; console.log('真の空きポート',port); }); //コマンド登録 export function activate(context: vscode.ExtensionContext): void { context.subscriptions.push(vscode.commands.registerCommand('Novel.compile-draft', compileDocs)); context.subscriptions.push(vscode.commands.registerCommand('Novel.vertical-preview', verticalpreview)); context.subscriptions.push(vscode.commands.registerCommand('Novel.export-pdf', exportpdf)); context.subscriptions.push(vscode.commands.registerCommand('Novel.launch-preview-server', launchserver)); const characterCounter = new CharacterCounter(); const controller = new CharacterCounterController(characterCounter); context.subscriptions.push(controller); context.subscriptions.push(characterCounter); context.subscriptions.push(vscode.commands.registerCommand('Novel.set-counter', async (e) => { const path = e.fsPath; let currentLength = 0 draftsObject(path).forEach(element =>{ currentLength += element.length; }); // InputBoxを呼び出す。awaitで完了を待つ。 let result = await vscode.window.showInputBox({ prompt: '目標となる文字数を入力してください', placeHolder: `現在の文字数:${currentLength}` }); // ここで入力を処理する if (result) { try{ parseInt(result); // 入力が正常に行われている vscode.window.showInformationMessage(`目標の文字数を: ${result}文字に設定しました`); } catch (error){ vscode.window.showWarningMessage(`数字を入力してください`); result = '0'; } } else { // 入力がキャンセルされた vscode.window.showWarningMessage(`目標文字数は設定しません`); result = '0'; } characterCounter._setCounterToFolder(path, parseInt(result!)); })); documentRoot = vscode.Uri.joinPath(context.extensionUri, 'htdocs'); } function launchserver(originEditor: OriginEditor){ //もしサーバーが動いていたらポートの番号をずらす //Webサーバの起動。ドキュメントルートはnode_modules/novel-writer/htdocsになる。 const viewerServer = http.createServer(function(request, response) { const Response = { "200":function(file: Buffer, filename:string){ //const extname = path.extname(filename); const header = { "Access-Control-Allow-Origin":"*", "Pragma": "no-cache", "Cache-Control" : "no-cache" } response.writeHead(200, header); response.write(file, "binary"); response.end(); }, "404":function(){ response.writeHead(404, {"Content-Type": "text/plain"}); response.write("404 Not Found\n"); response.end(); }, "500":function(err:unknown){ response.writeHead(500, {"Content-Type": "text/plain"}); response.write(err + "\n"); response.end(); } } const uri = request.url; let filename = path.join(documentRoot.fsPath, uri!); fs.stat(filename, (err, stats) => { console.log(filename+" "+stats); if (err) { Response["404"](); return ; } if (fs.statSync(filename).isDirectory()) { filename += '/index.html'; } fs.readFile(filename, function(err, file){ if (err) { Response["500"](err); return ; } Response["200"](file, filename); }); }); }) viewerServer.listen( servicePort ); // Node Websockets Serverを起動する const wsServer = websockets.Server; const s = new wsServer({ port: servicePort + 1 }); s.on("connection", ws => { //console.log(previewvariables()); ws.on("message", message => { console.log("Received: " + message); if (message === "hello") { ws.send( JSON.stringify(getConfig())); //ws.send( editorText()); } else if (message === "givemedata"){ console.log("sending body"); ws.send( editorText(originEditor)); } else if (message === "giveMeObject"){ const sendingObjects = draftsObject(draftRoot()); console.log('send:',sendingObjects); ws.send( JSON.stringify(sendingObjects)); } }); }); vscode.workspace.onDidChangeTextDocument((e) => { let _a; if (e.document == ((_a = vscode.window.activeTextEditor) === null || _a === void 0 ? void 0 : _a.document)) { const editor = vscode.window.activeTextEditor; if (editor?.document.languageId == "novel" || editor?.document.languageId == "markdown" || editor?.document.languageId == "plaintext") { publishWebsocketsDelay.presskey(s); } } }); vscode.window.onDidChangeTextEditorSelection((e) => { if (e.textEditor == vscode.window.activeTextEditor) { const editor = vscode.window.activeTextEditor; if (editor?.document.languageId == "novel" || editor?.document.languageId == "markdown" || editor?.document.languageId == "plaintext") { publishWebsocketsDelay.presskey(s); } } }); vscode.workspace.onDidChangeConfiguration(() => { //設定変更 console.log('setting changed'); sendsettingwebsockets(s); }); vscode.window.onDidChangeVisibleTextEditors((e) => { //ウインドウの状態変更 //プレビューが閉じたかどうか console.log('WindowState Changed:',e); }); publishWebsocketsDelay.presskey(s); if(WebViewPanel){ // vscode.window.showInformationMessage('Hello, world!'); const panel = vscode.window.createWebviewPanel( 'preview', // Identifies the type of the webview. Used internally '原稿プレビュー', // Title of the panel displayed to the user vscode.ViewColumn.Two, // Editor column to show the new webview panel in. { enableScripts: true, } // Webview options. More on these later. ); panel.webview.html = `<!DOCTYPE html> <html> <head> <style> body{ width:100vw; height:100vh; overflor:hidden; } </style> </head> <body> <iframe src="http://localhost:${servicePort}" frameBorder="0" style="min-width: 100%; min-height: 100%" /> </body> </html>`; return s; } } function emptyPort(callback: any) { let port = 8080; const socket = new net.Socket(); const server = new net.Server(); socket.on('error', function(e) { try { console.log('try:', port); server.listen(port, '127.0.0.1'); server.close(); callback(port); } catch(e) { loop(); } }); function loop() { port = port + 2; if (port >= 20000) { callback(new Error('empty port not found')); return; } socket.connect(port, '127.0.0.1', function() { socket.destroy(); loop(); }); } loop(); } function publishwebsockets(socketServer: websockets.Server){ socketServer.clients.forEach((client: websockets) => { client.send(editorText("active")); }); } function sendsettingwebsockets(socketServer: websockets.Server){ socketServer.clients.forEach((client: websockets) => { client.send(( JSON.stringify(getConfig()))); }); } let keyPressFlag = false; const publishWebsocketsDelay: any = { publish: function(socketServer: websockets.Server) { publishwebsockets(socketServer); keyPressFlag = false; delete this.timeoutID; }, presskey: function(s: websockets.Server) { //this.cancel(); if (!keyPressFlag){ const currentEditor = vscode.window.activeTextEditor; if (currentEditor) { const updateCounter = Math.min( Math.ceil(currentEditor.document.getText().length / 50), 1500 ); this.timeoutID = setTimeout(socketServer => { this.publish(socketServer); }, updateCounter, s); keyPressFlag = true; } } }, cancel: function() { if(typeof this.timeoutID == "number") { this.clearTimeout(this.timeoutID); delete this.timeoutID; } } }; function verticalpreview(){ const originEditor = vscode.window.activeTextEditor; WebViewPanel = true; launchserver(originEditor); /* // vscode.window.showInformationMessage('Hello, world!'); const panel = vscode.window.createWebviewPanel( 'preview', // Identifies the type of the webview. Used internally '原稿プレビュー', // Title of the panel displayed to the user vscode.ViewColumn.Two, // Editor column to show the new webview panel in. { enableScripts: true, } // Webview options. More on these later. ); panel.webview.html = `<!DOCTYPE html> <html> <head> <style> body{ width:100vw; height:100vh; overflor:hidden; } </style> </head> <body> <iframe src="http://localhost:8080" frameBorder="0" style="min-width: 100%; min-height: 100%" /> </body> </html>`; panel.onDidDispose(() =>{ console.log('closed'); }); */ } function exportpdf(): void { const myHtml = getWebviewContent(); if (!vscode.workspace.workspaceFolders) { output.appendLine(`not found workspace folders to publish.`); return; } else { const folderUri = vscode.workspace.workspaceFolders[0].uri; const myPath = vscode.Uri.joinPath(folderUri, 'publish.html'); const myWorkingDirectory = folderUri; const vivlioCommand = 'vivliostyle'; const vivlioSubCommand = 'build'; output.appendLine(`starting to publish: ${myPath}`); const vivlioParams = [vivlioSubCommand, myPath.fsPath, '-o', vscode.Uri.joinPath(myWorkingDirectory, "output.pdf").fsPath]; output.appendLine(`starting to publish: ${vivlioCommand} ${vivlioParams}`); const myHtmlBinary = Buffer.from(myHtml, 'utf8'); vscode.workspace.fs.writeFile(myPath, myHtmlBinary).then(() => { output.appendLine(`saving pdf to ${vivlioCommand}`); cp.execFile(vivlioCommand, vivlioParams, (err, stdout, stderr) => { if (err) { console.log(`stderr: ${stderr}`); output.appendLine(`stderr: ${stderr}`); return } output.appendLine(`stdout: ${stdout}`); output.appendLine('PDFの保存が終わりました'); }) output.appendLine('HTMLの書き込みが完了しました'); }); } } function deactivate() { return undefined; } module.exports = { activate, deactivate }; function getWebviewContent() { //configuration 読み込み const previewSettings = getConfig(); /* const config = vscode.workspace.getConfiguration('Novel'); let lineheightrate = 1.75; let fontfamily = config.get('preview.font-family'); let fontsize = config.get('preview.fontsize'); let numfontsize = parseInt(/(\d+)(\D+)/.exec(fontsize)[1]); let unitoffontsize = /(\d+)(\D+)/.exec(fontsize)[2]; let linelength = config.get('preview.linelength'); let linesperpage = config.get('preview.linesperpage'); let pagewidth = ( linesperpage * numfontsize * lineheightrate * 1.003) + unitoffontsize; let pageheight = (linelength * numfontsize) + unitoffontsize; let lineheight = ( numfontsize * lineheightrate) + unitoffontsize; */ //console.log(lineheight); const myText = editorText("active"); return `<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Cat Coding</title> <style> @charset "UTF-8"; html { /* 組み方向 */ -epub-writing-mode: vertical-rl; -ms-writing-mode: tb-rl; writing-mode: vertical-rl; orphans: 1; widows: 1; } * { margin: 0; padding: 0; } @page { size: 105mm 148mm; width: 88mm; /* width: calc(84mm - 1q); */ height: 110mm; margin-top: 20mm; margin-bottom: auto; margin-left: auto; margin-right: auto; /* 以下、マージンボックスに継承される */ font-size: 6pt; font-family: "游明朝", "YuMincho", serif; /* 本来不要(<span class="smaller"><span class="smaller">ルート要素の指定が継承される</span></span>)だが、現時点のvivliostyle.jsの制限により必要 */ vertical-align: top; } @page :left { margin-right: 10mm; @top-left { content: counter(page) " <$projecttitle>"; margin-left: 12q; margin-top: 135mm; writing-mode: horizontal-tb; /* CSS仕様上は@pageルール内に書けばよいが、現時点のvivliostyle.jsの制限によりここに書く */ } } @page :right { margin-right: 14mm; /* border-bottom: 1pt solid black; */ /* 右下ノンブル */ @top-right { content: "<$fullname> "counter(page); margin-right: 12q; margin-top: 135mm; writing-mode: horizontal-tb; /* CSS仕様上は@pageルール内に書けばよいが、現時点のvivliostyle.jsの制限によりここに書く */ } } html { font-family: "游明朝", "YuMincho", serif; font-weight: Medium; text-align: justify; } body{ } h1 { /* フォント */ font-weight: Extrabold; /* フォントサイズ */ font-size: 24q; /* 字下げ */ text-indent: 0; /* 直後の改ページ・改段禁止 */ page-break-before: always; page-break-after: always; line-height: 42q; letter-spacing: 0.25em; display: flex; align-items: center; } h2 { /* フォント */ font-weight: Demibold; /* フォントサイズ */ font-size: 16q; /* 字下げ */ text-indent: 3em; /* 直後の改ページ・改段禁止 */ page-break-before: always; page-break-after: avoid; line-height: 42q; margin-left: 2em; } h2.part { width: 80mm; padding: 0mm 35mm; font-weight: bold; font-size: 16q; page-break-before: always; page-break-after: always; margin-left: 4em; } h1 + h2 { margin-right: 16pt; } ruby > rt { font-size: 6.5q; } p { font-size: calc(110mm / ${previewSettings.lineLength}); line-height: 1.65; text-indent: 0em; hanging-punctuation: force-end; line-break:strict; page-break-inside: auto; } div.indent-1 p:first-of-type, div.indent-2 p:first-of-type, div.indent-3 p:first-of-type{ padding-block-start: calc( ${previewSettings.fontSize} * ${previewSettings.lineHeightRate}); } div.indent-1 p:last-of-type, div.indent-2 p:last-of-type, div.indent-3 p:last-of-type{ padding-block-end: calc( ${previewSettings.fontSize} * ${previewSettings.lineHeightRate}); } div.indent-1 p{ height: calc( 110mm - (${previewSettings.fontSize})); padding-top: ${previewSettings.fontSize}; } div.indent-2 p{ height: calc( 110mm - (${previewSettings.fontSize} * 2)); padding-top: calc(${previewSettings.fontSize} * 2); } div.indent-3 p{ height: calc( 110mm - (${previewSettings.fontSize} * 3)); padding-top: calc(${previewSettings.fontSize} * 3); } p.goth { margin-top: 3em; font-family: "游ゴシック", "YuGothic", san-serif; margin-block-start: 1em; margin-block-end: 1em; } p.align-rb { text-align: right; } p.goth + p.goth { margin-block-start: -1em; } div.codes { display: inline-block; margin: 3em 1em; writing-mode: horizontal-tb; padding: 1em; font-family: "Courier", monospace; font-size: 0.8em; } div.codes p { text-orientation: sideways; } p.star { text-indent: 3em; margin-right: 16pt; margin-left: 16pt; } hr { border: none; border-right: 1pt solid black; height: 6em; margin: auto 8.5pt; } /* 縦中横 */ .tcy { -webkit-text-combine: horizontal; text-combine: horizontal; -ms-text-combine-horizontal: all; text-combine-horizontal: digit 2; text-combine-upright: digit 2; } /* 圏点(<span class="smaller">ゴマ</span>) */ em.side-dot, em.sesame_dot { font-style: normal; -webkit-text-emphasis-style: sesame; text-emphasis-style: sesame; } /*著作者*/ .author { position: absolute; bottom: 0; font-size: 8.5pt; margin-top: 50pt; letter-spacing: normal; } /*画像+キャプション*/ figure { display: block; width: 236pt; -ms-writing-mode: lr-tb; -webkit-writing-mode: horizontal-tb; writing-mode: horizontal-tb; } figure img { width: 100%; height: auto; vertical-align: bottom; } figcaption { text-align: left; font-size: 7pt; } /*奥付*/ .colophon { font-size: 7pt; margin-right: 48pt; } /* 級さげ */ span.smaller{ font-size:6.5pt } div.comment { display:none; } p.blank { color:transparent; } @media screen{ body { writing-mode: vertical-rl; font-family: ${previewSettings.fontFamily}; height: ${previewSettings.pageHeight}; overflow-y:hidden; padding:0; } #cursor { background-color: rgb(125,125,125,); animation-duration: 0.5s; animation-name: cursorAnimation; animation-iteration-count: infinite; } p { height: ${previewSettings.pageHeight}; font-family: ${previewSettings.fontFamily}; font-size: ${previewSettings.fontSize}; margin:0 0 0 0; vertical-align: middle; } em.side-dot { font-style: normal; text-emphasis: filled sesame rgb(128,128,128); -webkit-text-emphasis: filled sesame rgb(128,128,128); } span.tcy { text-combine: horizontal; -webkit-text-combine:horizontal; } @keyframes cursorAnimation { from { background-color: rgba(66,66,66,0); } to { background-color: rgba(125,125,125,0.7); } } body{ background-image: linear-gradient(to right, rgba(50, 50, 50, 0.5) 0.5pt, rgba(0, 0, 50, 0.05) 10em); background-size: ${previewSettings.pageWidth} ${previewSettings.pageHeight}; background-repeat: repeat-x; background-position: right 0px; } p{ background-image: linear-gradient( rgba(50, 50, 50, 1) 0.5pt, transparent 1pt), linear-gradient(to right, rgba(50, 50, 50, 1) 0.5pt, rgba(0, 0, 50, 0.05) 1pt); background-size: ${previewSettings.lineHeight} ${previewSettings.fontSize}, ${previewSettings.lineHeight} ${previewSettings.fontSize}; background-repeat: repeat, repeat; background-position: right 0px, right 0px; } div.indent-1 p{ height: calc( ${previewSettings.pageHeight} - (${previewSettings.fontSize})); padding-top: ${previewSettings.fontSize}; } div.indent-2 p{ height: calc( ${previewSettings.pageHeight} - (${previewSettings.fontSize} * 2)); padding-top: calc(${previewSettings.fontSize} * 2); } div.indent-3 p{ height: calc( ${previewSettings.pageHeight} - (${previewSettings.fontSize} * 3)); padding-top: calc(${previewSettings.fontSize} * 3); } span.comment{ display:block; border-radius:1em; border:1.5pt solid rgba(70,70,00,0.9); padding:0.25em 0.25em; position:absolute; margin-right: -3em; margin-top: 0.5em; top: ${previewSettings.pageHeight}; background-color:rgba(50,50,00,0.5); max-width: 20em; } span.comment::before{ content: ''; position: absolute; right: 1em; top: -15px; display: block; width: 0; height: 0; border-right: 15px solid transparent; border-bottom: 15px solid rgba(70,70,00,0.9); border-left: 15px solid transparent; } span.commentbody{ margin:0.5em 1em; writing-mode:lr-tb; font-family:sans-serif; font-size:0.8em; line-height:1; } } </style> <link rel="stylesheet" href=""> </head> <body> ${myText} <script> setTimeout( (function(){ var width = document.body.clientWidth; var cursor = document.getElementById('cursor'); var panelWidth = window.innerWidth; var scrollEnd = cursor.offsetLeft - width + (panelWidth / 2); window.scrollTo( scrollEnd , scrollEnd); console.log(width, cursor, panelWidth, scrollEnd); }), 1); </script> </body> </html>`; }
the_stack
import { TypeAssertion, TypeAssertionMap } from '../../types'; import * as JsonSchema from '../../types/json-schema-types'; function addMetaInfo(a: JsonSchema.JsonSchemaAssertion, ty: TypeAssertion) { const a2 = {...a}; let changed = false; if (ty.docComment) { a2.description = ty.docComment; changed = true; } switch (ty.kind) { case 'repeated': if (typeof ty.min === 'number') { (a2 as JsonSchema.JsonSchemaArrayAssertion).minItems = ty.min; changed = true; } if (typeof ty.max === 'number') { (a2 as JsonSchema.JsonSchemaArrayAssertion).maxItems = ty.max; changed = true; } break; case 'primitive': if (typeof ty.minValue === 'number') { (a2 as JsonSchema.JsonSchemaNumberAssertion).minimum = ty.minValue; changed = true; } if (typeof ty.maxValue === 'number') { (a2 as JsonSchema.JsonSchemaNumberAssertion).maximum = ty.maxValue; changed = true; } if (typeof ty.greaterThanValue === 'number') { (a2 as JsonSchema.JsonSchemaNumberAssertion).exclusiveMinimum = ty.greaterThanValue; changed = true; } if (typeof ty.lessThanValue === 'number') { (a2 as JsonSchema.JsonSchemaNumberAssertion).exclusiveMaximum = ty.lessThanValue; changed = true; } if (typeof ty.minLength === 'number') { (a2 as JsonSchema.JsonSchemaStringAssertion).minLength = ty.minLength; changed = true; } if (typeof ty.maxLength === 'number') { (a2 as JsonSchema.JsonSchemaStringAssertion).maxLength = ty.maxLength; changed = true; } if (ty.pattern) { (a2 as JsonSchema.JsonSchemaStringAssertion).pattern = ty.pattern.source; changed = true; } break; } return (changed ? a2 : a); } function generateJsonSchemaInner(schema: TypeAssertionMap, ty: TypeAssertion, nestLevel: number): JsonSchema.JsonSchemaAssertion { if (0 < nestLevel && ty.typeName) { const ret: JsonSchema.JsonSchemaRefAssertion = { $ref: `#/definitions/${ty.typeName.replace(/\./g, '/properties/')}`, }; const r2 = addMetaInfo(ret, ty); if (ret !== r2) { // NOTE: `$ref` cannot have value constraints. return generateJsonSchemaInner(schema, ty, 0); } else { return ret; } } switch (ty.kind) { case 'symlink': { const ret: JsonSchema.JsonSchemaRefAssertion = { $ref: `#/definitions/${ty.symlinkTargetName}`, }; const r2 = addMetaInfo(ret, ty); if (ret !== r2) { // NOTE: `$ref` cannot have value constraints. const t2 = schema.get(ty.symlinkTargetName)?.ty; if (t2) { return generateJsonSchemaInner(schema, t2, 0); } else { // Drop constraints. return ret; } } else { return ret; } } case 'repeated': { const ret: JsonSchema.JsonSchemaArrayAssertion = { type: 'array', items: generateJsonSchemaInner(schema, ty.repeated, nestLevel + 1), }; if (typeof ty.min === 'number') { ret.minItems = ty.min; } if (typeof ty.max === 'number') { ret.maxItems = ty.max; } return addMetaInfo(ret, ty); } case 'sequence': { const ret: JsonSchema.JsonSchemaArrayAssertion = { type: 'array', items: { anyOf: ty.sequence.map(x => generateJsonSchemaInner(schema, x, nestLevel + 1)) }, }; return addMetaInfo(ret, ty); } case 'spread': { return generateJsonSchemaInner(schema, ty.spread, nestLevel + 1); } case 'one-of': { const ret: JsonSchema.JsonSchemaAnyOfAssertion = { anyOf: ty.oneOf.map(x => generateJsonSchemaInner(schema, x, nestLevel + 1)), }; return addMetaInfo(ret, ty); } case 'optional': { const ret: JsonSchema.JsonSchemaOneOfAssertion = { oneOf: [ generateJsonSchemaInner(schema, ty.optional, nestLevel + 1), {type: 'null'}, ], }; return addMetaInfo(ret, ty); } case 'enum': { const ret: JsonSchema.JsonSchemaTsEnumAssertion = { type: ['string', 'number'], enum: ty.values.map(x => x[1]), }; return addMetaInfo(ret, ty); } case 'object': { const properties: JsonSchema.JsonSchemaObjectPropertyAssertion = {}; const patternProperties: JsonSchema.JsonSchemaObjectPropertyAssertion = {}; let patternPropsCount = 0; const required: string[] = []; for (const m of ty.members) { const z = generateJsonSchemaInner(schema, m[1].kind === 'optional' ? m[1].optional : m[1], nestLevel + 1); if (m[3]) { z.description = m[3]; } else { delete z.description; } properties[m[0]] = z; if (m[1].kind !== 'optional') { required.push(m[0]); } } for (const m of ty.additionalProps || []) { const z = generateJsonSchemaInner(schema, m[1], nestLevel + 1); if (m[3]) { z.description = m[3]; } else { delete z.description; } for (const k of m[0]) { patternPropsCount++; switch (k) { case 'number': patternProperties['^[0-9]+$'] = z; break; case 'string': patternProperties['^.*$'] = z; break; default: patternProperties[k.source] = z; break; } } } const ret: JsonSchema.JsonSchemaObjectAssertion = { type: 'object', properties, ...(0 < patternPropsCount ? {patternProperties} : {}), ...(0 < required.length ? {required} : {}), additionalProperties: false, }; return addMetaInfo(ret, ty); } case 'primitive': { switch (ty.primitiveName) { case 'null': case 'undefined': { const ret: JsonSchema.JsonSchemaNullAssertion = { type: 'null', }; return addMetaInfo(ret, ty); } case 'number': { const ret: JsonSchema.JsonSchemaNumberAssertion = { type: 'number', }; return addMetaInfo(ret, ty); } case 'bigint': { const ret: JsonSchema.JsonSchemaBigIntAssertion = { type: ['integer', 'string'], }; return addMetaInfo(ret, ty); } case 'integer': { const ret: JsonSchema.JsonSchemaNumberAssertion = { type: 'integer', }; return addMetaInfo(ret, ty); } case 'string': { const ret: JsonSchema.JsonSchemaStringAssertion = { type: 'string', }; return addMetaInfo(ret, ty); } case 'boolean': { const ret: JsonSchema.JsonSchemaBooleanAssertion = { type: 'boolean', }; return addMetaInfo(ret, ty); } } // TODO: Function, DateStr, DateTimeStr } case 'primitive-value': { switch (typeof ty.value) { case 'number': { const ret: JsonSchema.JsonSchemaNumberValueAssertion = { type: 'number', enum: [ty.value], }; return addMetaInfo(ret, ty); } case 'bigint': { const ret: JsonSchema.JsonSchemaBigIntNumberValueAssertion = { type: ['integer', 'string'], enum: [ty.value.toString()], }; if (BigInt(Number.MIN_SAFE_INTEGER) <= ty.value && ty.value <= BigInt(Number.MAX_SAFE_INTEGER)) { ret.enum.push(Number(ty.value)); } return addMetaInfo(ret, ty); } case 'string': { const ret: JsonSchema.JsonSchemaStringValueAssertion = { type: 'string', enum: [ty.value], }; return addMetaInfo(ret, ty); } case 'boolean': { const ret: JsonSchema.JsonSchemaBooleanValueAssertion = { type: 'boolean', enum: [ty.value], }; return addMetaInfo(ret, ty); } default: throw new Error(`Unknown primitive-value assertion: ${typeof ty.value}`); } } case 'never': { const ret: JsonSchema.JsonSchemaNullAssertion = { type: 'null', }; return addMetaInfo(ret, ty); } case 'any': case 'unknown': { const ret: JsonSchema.JsonSchemaAnyAssertion = { type: ['null', 'integer', 'number', 'string', 'boolean', 'array', 'object'], }; return addMetaInfo(ret, ty); } case 'operator': throw new Error(`Unexpected type assertion: ${(ty as any).kind}`); default: throw new Error(`Unknown type assertion: ${(ty as any).kind}`); } } export function generateJsonSchemaObject(schema: TypeAssertionMap) { const ret: JsonSchema.JsonSchemaRootAssertion = { $schema: 'http://json-schema.org/draft-06/schema#', definitions: {}, }; for (const ty of schema.entries()) { if (ty[1].ty.kind === 'never' && ty[1].ty.passThruCodeBlock) { continue; } (ret.definitions as object)[ty[0]] = generateJsonSchemaInner(schema, ty[1].ty, 0); } return ret; } export function generateJsonSchema(schema: TypeAssertionMap, asTs?: boolean): string { const ret = generateJsonSchemaObject(schema); if (asTs) { return ( `\n// tslint:disable: object-literal-key-quotes\n` + `const schema = ${JSON.stringify(ret, null, 2)};\nexport default schema;` + `\n// tslint:enable: object-literal-key-quotes\n` ); } else { return JSON.stringify(ret, null, 2); } }
the_stack
import { getVoidLogger } from '@backstage/backend-common'; import { Entity, DEFAULT_NAMESPACE } from '@backstage/catalog-model'; import { ConfigReader } from '@backstage/config'; import express from 'express'; import request from 'supertest'; import mockFs from 'mock-fs'; import path from 'path'; import fs from 'fs-extra'; import { AzureBlobStoragePublish } from './azureBlobStorage'; import { EventEmitter } from 'events'; import { BlobUploadCommonResponse, ContainerGetPropertiesResponse, } from '@azure/storage-blob'; import { storageRootDir, StorageFilesMock, } from '../../testUtils/StorageFilesMock'; jest.mock('@azure/identity', () => ({ __esModule: true, DefaultAzureCredential: class {}, })); jest.mock('@azure/storage-blob', () => { class BlockBlobClient { constructor( private readonly blobName: string, private readonly storage: StorageFilesMock, ) {} uploadFile(source: string): Promise<BlobUploadCommonResponse> { this.storage.writeFile(this.blobName, source); return Promise.resolve({ _response: { request: { url: `https://example.blob.core.windows.net`, } as any, status: 200, headers: {} as any, }, }); } exists() { return this.storage.fileExists(this.blobName); } download() { const emitter = new EventEmitter(); setTimeout(() => { if (this.storage.fileExists(this.blobName)) { emitter.emit('data', this.storage.readFile(this.blobName)); emitter.emit('end'); } else { emitter.emit( 'error', new Error(`The file ${this.blobName} does not exist!`), ); } }, 0); return Promise.resolve({ readableStreamBody: emitter, }); } } class BlockBlobClientFailUpload extends BlockBlobClient { uploadFile(): Promise<BlobUploadCommonResponse> { return Promise.resolve({ _response: { request: { url: `https://example.blob.core.windows.net`, } as any, status: 500, headers: {} as any, }, }); } } class ContainerClientIterator { private containerName: string; constructor(containerName: string) { this.containerName = containerName; } async next() { if ( this.containerName === 'delete_stale_files_success' || this.containerName === 'delete_stale_files_error' ) { return { value: { segment: { blobItems: [{ name: `stale_file.png` }], }, }, }; } return { value: { segment: { blobItems: [], }, }, }; } } class ContainerClient { constructor( private readonly containerName: string, protected readonly storage: StorageFilesMock, ) {} getProperties(): Promise<ContainerGetPropertiesResponse> { return Promise.resolve({ _response: { request: { url: `https://example.blob.core.windows.net`, } as any, status: 200, headers: {} as any, parsedHeaders: {}, }, }); } getBlockBlobClient(blobName: string) { return new BlockBlobClient(blobName, this.storage); } listBlobsFlat() { return { byPage: () => { return new ContainerClientIterator(this.containerName); }, }; } deleteBlob() { if (this.containerName === 'delete_stale_files_error') { throw new Error('Message'); } } } class ContainerClientFailGetProperties extends ContainerClient { getProperties(): Promise<ContainerGetPropertiesResponse> { return Promise.resolve({ _response: { request: { url: `https://example.blob.core.windows.net`, } as any, status: 404, headers: {} as any, parsedHeaders: {}, }, }); } } class ContainerClientFailUpload extends ContainerClient { getBlockBlobClient(blobName: string) { return new BlockBlobClientFailUpload(blobName, this.storage); } } class BlobServiceClient { storage = new StorageFilesMock(); constructor( public readonly url: string, private readonly credential?: StorageSharedKeyCredential, ) { this.storage.emptyFiles(); } getContainerClient(containerName: string) { if (containerName === 'bad_container') { return new ContainerClientFailGetProperties( containerName, this.storage, ); } if (this.credential?.accountName === 'bad_account_credentials') { return new ContainerClientFailUpload(containerName, this.storage); } return new ContainerClient(containerName, this.storage); } } class StorageSharedKeyCredential { readonly accountName; readonly accountKey; constructor(accountName: string, accountKey: string) { this.accountName = accountName; this.accountKey = accountKey; } } return { __esModule: true, BlobServiceClient, StorageSharedKeyCredential, }; }); const getEntityRootDir = (entity: Entity) => { const { kind, metadata: { namespace, name }, } = entity; return path.join(storageRootDir, namespace || DEFAULT_NAMESPACE, kind, name); }; const logger = getVoidLogger(); jest.spyOn(logger, 'error').mockReturnValue(logger); const createPublisherFromConfig = ({ accountName = 'accountName', containerName = 'containerName', legacyUseCaseSensitiveTripletPaths = false, }: { accountName?: string; containerName?: string; legacyUseCaseSensitiveTripletPaths?: boolean; } = {}) => { const config = new ConfigReader({ techdocs: { publisher: { type: 'azureBlobStorage', azureBlobStorage: { credentials: { accountName, accountKey: 'accountKey', }, containerName, }, }, legacyUseCaseSensitiveTripletPaths, }, }); return AzureBlobStoragePublish.fromConfig(config, logger); }; describe('AzureBlobStoragePublish', () => { const entity = { apiVersion: '1', kind: 'Component', metadata: { name: 'backstage', namespace: 'default', annotations: {}, }, }; const entityName = { kind: 'Component', name: 'backstage', namespace: 'default', }; const techdocsMetadata = { site_name: 'backstage', site_description: 'site_content', etag: 'etag', build_timestamp: 612741599, }; const directory = getEntityRootDir(entity); beforeEach(() => { (logger.error as jest.Mock).mockClear(); }); const files = { 'index.html': '', '404.html': '', 'techdocs_metadata.json': JSON.stringify(techdocsMetadata), assets: { 'main.css': '', }, html: { 'unsafe.html': '<html></html>', }, img: { 'with spaces.png': 'found it', 'unsafe.svg': '<svg></svg>', }, 'some folder': { 'also with spaces.js': 'found it too', }, }; beforeEach(async () => { mockFs({ [directory]: files, }); }); afterEach(() => { mockFs.restore(); }); describe('getReadiness', () => { it('should validate correct config', async () => { const publisher = createPublisherFromConfig(); expect(await publisher.getReadiness()).toEqual({ isAvailable: true, }); }); it('should reject incorrect config', async () => { const errorPublisher = createPublisherFromConfig({ containerName: 'bad_container', }); expect(await errorPublisher.getReadiness()).toEqual({ isAvailable: false, }); expect(logger.error).toHaveBeenCalledWith( expect.stringContaining( `Could not retrieve metadata about the Azure Blob Storage container bad_container.`, ), ); }); }); describe('publish', () => { it('should publish a directory', async () => { const publisher = createPublisherFromConfig(); expect(await publisher.publish({ entity, directory })).toMatchObject({ objects: expect.arrayContaining([ 'default/component/backstage/404.html', `default/component/backstage/index.html`, `default/component/backstage/assets/main.css`, ]), }); }); it('should publish a directory as well when legacy casing is used', async () => { const publisher = createPublisherFromConfig({ legacyUseCaseSensitiveTripletPaths: true, }); expect(await publisher.publish({ entity, directory })).toMatchObject({ objects: expect.arrayContaining([ 'default/Component/backstage/404.html', `default/Component/backstage/index.html`, `default/Component/backstage/assets/main.css`, ]), }); }); it('should fail to publish a directory', async () => { const wrongPathToGeneratedDirectory = path.join( storageRootDir, 'wrong', 'path', 'to', 'generatedDirectory', ); const publisher = createPublisherFromConfig({ containerName: 'bad_container', }); const fails = publisher.publish({ entity, directory: wrongPathToGeneratedDirectory, }); await expect(fails).rejects.toMatchObject({ message: expect.stringContaining( 'Unable to upload file(s) to Azure. Error: Failed to read template directory: ENOENT, no such file or directory', ), }); await expect(fails).rejects.toMatchObject({ message: expect.stringContaining(wrongPathToGeneratedDirectory), }); }); it('reports an error when bad account credentials', async () => { const publisher = createPublisherFromConfig({ accountName: 'bad_account_credentials', }); let error; try { await publisher.publish({ entity, directory }); } catch (e: any) { error = e; } expect(error.message).toContain(`Unable to upload file(s) to Azure`); expect(logger.error).toHaveBeenCalledWith( expect.stringContaining( `Unable to upload file(s) to Azure. Error: Upload failed for ${path.join( directory, '404.html', )} with status code 500`, ), ); }); }); describe('hasDocsBeenGenerated', () => { it('should check expected file', async () => { const publisher = createPublisherFromConfig(); await publisher.publish({ entity, directory }); expect(await publisher.hasDocsBeenGenerated(entity)).toBe(true); }); it('should check expected file when legacy case flag is passed', async () => { const publisher = createPublisherFromConfig({ legacyUseCaseSensitiveTripletPaths: true, }); await publisher.publish({ entity, directory }); expect(await publisher.hasDocsBeenGenerated(entity)).toBe(true); }); it('should return false if docs has not been generated', async () => { const publisher = createPublisherFromConfig(); expect( await publisher.hasDocsBeenGenerated({ kind: 'triplet', metadata: { namespace: 'invalid', name: 'path', }, } as Entity), ).toBe(false); }); }); describe('fetchTechDocsMetadata', () => { it('should return tech docs metadata', async () => { const publisher = createPublisherFromConfig(); await publisher.publish({ entity, directory }); expect(await publisher.fetchTechDocsMetadata(entityName)).toStrictEqual( techdocsMetadata, ); }); it('should return tech docs metadata even if the legacy case is enabled', async () => { const publisher = createPublisherFromConfig({ legacyUseCaseSensitiveTripletPaths: true, }); await publisher.publish({ entity, directory }); expect(await publisher.fetchTechDocsMetadata(entityName)).toStrictEqual( techdocsMetadata, ); }); it('should return tech docs metadata when json encoded with single quotes', async () => { const techdocsMetadataPath = path.join( directory, 'techdocs_metadata.json', ); const techdocsMetadataContent = files['techdocs_metadata.json']; fs.writeFileSync( techdocsMetadataPath, techdocsMetadataContent.replace(/"/g, "'"), ); const publisher = createPublisherFromConfig(); await publisher.publish({ entity, directory }); expect(await publisher.fetchTechDocsMetadata(entityName)).toStrictEqual( techdocsMetadata, ); fs.writeFileSync(techdocsMetadataPath, techdocsMetadataContent); }); it('should return an error if the techdocs_metadata.json file is not present', async () => { const publisher = createPublisherFromConfig(); const invalidEntityName = { namespace: 'invalid', kind: 'triplet', name: 'path', }; const techDocsMetadaFilePath = path.posix.join( ...Object.values(invalidEntityName), 'techdocs_metadata.json', ); const fails = publisher.fetchTechDocsMetadata(invalidEntityName); await expect(fails).rejects.toMatchObject({ message: `TechDocs metadata fetch failed; caused by Error: The file ${techDocsMetadaFilePath} does not exist!`, }); }); }); describe('docsRouter', () => { const entityTripletPath = `${entity.metadata.namespace}/${entity.kind}/${entity.metadata.name}`; let app: express.Express; beforeEach(async () => { const publisher = createPublisherFromConfig(); await publisher.publish({ entity, directory }); app = express().use(publisher.docsRouter()); }); afterEach(() => { mockFs.restore(); }); it('should pass expected object path to bucket', async () => { // Ensures leading slash is trimmed and encoded path is decoded. const pngResponse = await request(app).get( `/${entityTripletPath}/img/with%20spaces.png`, ); expect(Buffer.from(pngResponse.body).toString('utf8')).toEqual( 'found it', ); const jsResponse = await request(app).get( `/${entityTripletPath}/some%20folder/also%20with%20spaces.js`, ); expect(jsResponse.text).toEqual('found it too'); }); it('should pass expected object path to bucket even if the legacy case is enabled', async () => { const publisher = createPublisherFromConfig({ legacyUseCaseSensitiveTripletPaths: true, }); await publisher.publish({ entity, directory }); app = express().use(publisher.docsRouter()); // Ensures leading slash is trimmed and encoded path is decoded. const pngResponse = await request(app).get( `/${entityTripletPath}/img/with%20spaces.png`, ); expect(Buffer.from(pngResponse.body).toString('utf8')).toEqual( 'found it', ); const jsResponse = await request(app).get( `/${entityTripletPath}/some%20folder/also%20with%20spaces.js`, ); expect(jsResponse.text).toEqual('found it too'); }); it('should pass text/plain content-type for html', async () => { const htmlResponse = await request(app).get( `/${entityTripletPath}/html/unsafe.html`, ); expect(htmlResponse.text).toEqual('<html></html>'); expect(htmlResponse.header).toMatchObject({ 'content-type': 'text/plain; charset=utf-8', }); const svgResponse = await request(app).get( `/${entityTripletPath}/img/unsafe.svg`, ); expect(svgResponse.text).toEqual('<svg></svg>'); expect(svgResponse.header).toMatchObject({ 'content-type': 'text/plain; charset=utf-8', }); }); it('should return 404 if file is not found', async () => { const response = await request(app).get( `/${entityTripletPath}/not-found.html`, ); expect(response.status).toBe(404); expect(Buffer.from(response.text).toString('utf8')).toEqual( 'File Not Found', ); }); }); });
the_stack
import { POSITION_UNKNOWN, SourceLocation, SourcePosition, isSourcePosition, } from "@opticss/element-analysis"; import { SerializedTemplateInfo, TemplateAnalysis as OptimizationTemplateAnalysis, TemplateInfoFactory, TemplateTypes, } from "@opticss/template-api"; import { ObjectDictionary, objectValues } from "@opticss/util"; import { IdentGenerator } from "opticss"; import { BlockFactory } from "../BlockParser"; import { AttrValue, Block, BlockClass, Style } from "../BlockTree"; import { ResolvedConfiguration } from "../configuration"; import { allDone } from "../util"; import { Analyzer } from "./Analyzer"; import { ElementAnalysis, SerializedElementAnalysis, SerializedElementSourceAnalysis } from "./ElementAnalysis"; import { TemplateValidator, TemplateValidatorOptions } from "./validations"; /** * This interface defines a JSON friendly serialization * of an {Analysis}. */ export interface SerializedAnalysis<K extends keyof TemplateTypes> { template: SerializedTemplateInfo<K>; blocks: ObjectDictionary<string>; stylesFound: string[]; // The numbers stored in each element are an index into a stylesFound; elements: ObjectDictionary<SerializedElementAnalysis>; } /** * This interface defines a JSON friendly serialization * of an {Analysis}. */ export interface SerializedSourceAnalysis<K extends keyof TemplateTypes> { template: SerializedTemplateInfo<K>; blocks: ObjectDictionary<string>; stylesFound: string[]; // The numbers stored in each element are an index into a stylesFound; elements: ObjectDictionary<SerializedElementSourceAnalysis>; } // tslint:disable-next-line:prefer-unknown-to-any type ElementAnalyzedCallback<BooleanExpression, StringExpression, TernaryExpression> = (element: ElementAnalysis<BooleanExpression, StringExpression, TernaryExpression>) => void; /** * An Analysis performs book keeping and ensures internal consistency of the block objects referenced * within a single template. It is designed to be used as part of an AST walk over a template. * * 1. Call [[startElement startElement()]] at the beginning of an new html element. * 2. Call [[addStyle addStyle(style, isDynamic)]] for all the styles used on the current html element. * 2. Call [[addExclusiveStyle addExclusiveStyle(alwaysPresent, ...style)]] for all the styles used that are mutually exclusive on the current html element. * 3. Call [[endElement endElement()]] when done adding styles for the current element. */ export class Analysis<K extends keyof TemplateTypes> { idGenerator: IdentGenerator; template: TemplateTypes[K]; /** * A per-element correlation of styles used. The current correlation is added * to this list when [[endElement]] is called. */ // tslint:disable-next-line:prefer-unknown-to-any elements: Map<string, ElementAnalysis<any, any, any>>; /** * A map from a local name for the block to the [[Block]]. * The local name must be a legal CSS ident/class name but this is not validated here. * See [[CLASS_NAME_IDENT]] for help validating a legal class name. */ private blocks: ObjectDictionary<Block>; /** * The current element, created when calling [[startElement]]. * The current element is unset after calling [[endElement]]. */ // tslint:disable-next-line:prefer-unknown-to-any private currentElement: ElementAnalysis<any, any, any> | undefined; /** * Template validator instance to verify blocks applied to an element. */ private validator: TemplateValidator; /** * Callback when an element is done being analyzed. * The element analysis will be sealed. */ // tslint:disable-next-line:prefer-unknown-to-any onElementAnalyzed?: ElementAnalyzedCallback<any, any, any>; /** * @param template The template being analyzed. */ // tslint:disable-next-line:prefer-unknown-to-any constructor(template: TemplateTypes[K], options?: TemplateValidatorOptions, onElementAnalyzed?: ElementAnalyzedCallback<any, any, any>) { this.idGenerator = new IdentGenerator(); this.template = template; this.blocks = {}; this.elements = new Map(); this.validator = new TemplateValidator(options); this.onElementAnalyzed = onElementAnalyzed; } /** * Return the number of blocks discovered in this Template. */ blockCount(): number { return Object.keys(this.blocks).length; } /** * Convenience setter for adding a block to the template scope. */ addBlock(name: string, block: Block): Block { return this.blocks[name] = block; } /** * Convenience getter for fetching a block from the template scope. */ getBlock(name: string): Block | undefined { return this.blocks[name]; } /** * Return the number of elements discovered in this Analysis. */ elementCount(): number { return this.elements.size; } /** * Get the nth element discovered in this Analysis. */ getElement<BooleanExpression, StringExpression, TernaryExpression>(idx: number): ElementAnalysis<BooleanExpression, StringExpression, TernaryExpression> { let mapIter = this.elements.entries(); let el = mapIter.next().value; for (let i = 0; i < idx; i++) { el = mapIter.next().value; } return el[1]; } /** * Return the number of styles discovered in this Analysis' Template. * TODO: This is slow. We can pre-compute this as elements are added. */ styleCount(): number { let c = 0; for (let el of this.elements.values()) { for (let _s of el.attributesFound()) { c++; } for (let _s of el.classesFound()) { c++; } } return c; } /** * Get an Element by ID. */ getElementById<BooleanExpression, StringExpression, TernaryExpression>(id: string): ElementAnalysis<BooleanExpression, StringExpression, TernaryExpression> | undefined { return this.elements.get(id); } /** * Returns the local name of the provided in this Analysis' template. * @param block The block for which the local name should be returned. * @return The local name of the given block. */ getBlockName(block: Block): string | null { for (let name of Object.keys(this.blocks)) { let searchBlock = this.blocks[name]; let blockName = this._searchForBlock(block, searchBlock, name); if (blockName !== null) { return blockName; } } return null; } _searchForBlock(blockToFind: Block, block: Block, parentPath: string): string | null { if (block === blockToFind) { return parentPath; } // we collect these name/block pairs first, so we can early exit the next loop. let blockRefs = new Array<[string, Block]>(); block.eachBlockReference((name, refBlock) => { blockRefs.push([name, refBlock]); }); for (let [name, refBlock] of blockRefs) { let currentSearchPath = `${parentPath}>${name}`; let rv = this._searchForBlock(blockToFind, refBlock, currentSearchPath); if (rv !== null) { return rv; } } return null; } /** * Get a new {ElementAnalysis} object to track an individual element's {Style} * consumption in this {Analysis}' template. Every {ElementAnalysis} returned from * `Analysis.startElement` must be passed to `Analysis.endElement` before startElement * is called again. * @param location The {SourceLocation} of this element in the template. * @param tagName Optional. The tag name of the element being represented by this {ElementAnalysis}. * @returns A new {ElementAnalysis}. */ startElement<BooleanExpression, StringExpression, TernaryExpression>(location: SourceLocation | SourcePosition, tagName?: string): ElementAnalysis<BooleanExpression, StringExpression, TernaryExpression> { if (isSourcePosition(location)) { location = {start: location}; } if (this.currentElement) { throw new Error("Internal Error: failure to call endElement before previous call to startElement."); } this.currentElement = new ElementAnalysis<BooleanExpression, StringExpression, TernaryExpression>(location, this.reservedClassNames(), tagName, this.idGenerator.nextIdent()); return this.currentElement; } /** * Finish an {ElementAnalysis} object returned from `Analysis.startElement` to * the end location in source and save {Style} usage on the parent {Analysis}. * @param element The {ElementAnalysis} we are finishing. * @param endPosition Optional. The location in code where this element tag is closed.. */ endElement<BooleanExpression, StringExpression, TernaryExpression>(element: ElementAnalysis<BooleanExpression, StringExpression, TernaryExpression>, endPosition?: SourcePosition): void { if (this.currentElement !== element) { throw new Error("Element is not the current element."); } if (endPosition) { element.sourceLocation.end = endPosition; } if (!element.id) { element.id = this.idGenerator.nextIdent(); } if (this.elements.get(element.id)) { throw new Error(`Internal Error: an element with id = ${element.id} already exists in this analysis`); } this.ensureFilename(element.sourceLocation.start); this.ensureFilename(element.sourceLocation.end); if (!element.sealed) { element.seal(); } this.validator.validate(this, element); this.elements.set(element.id, element); if (this.onElementAnalyzed) { this.onElementAnalyzed(element); } this.currentElement = undefined; } /** * Given a {SourcePosition}, ensure that the file name is present. If not, * add the template identifier. * @param post The {SourcePosition} we are validating. */ private ensureFilename(pos: SourcePosition | undefined) { if (pos && !pos.filename) { pos.filename = this.template.identifier; } } /** * @return The local name for the block object using the local prefix for the block. */ serializedName(o: Style): string { let blockName = this.getBlockName(o.block); if (blockName === null) { throw new Error(`Block ${o.block.identifier} is not registered in the dependency graph for this analysis.`); } return `${blockName}${o.asSource()}`; } /** * All the blocks referenced by this analysis. */ referencedBlocks(): Block[] { return objectValues(this.blocks); } /** * For now, returns all aliases referenced by this block and all the blocks they * reference recursively. We can add more to this set in future */ reservedClassNames(): Set<string> { let aliases = new Set<string>(); let blocks = this.transitiveBlockDependencies(); blocks.forEach(block => { block.getAllStyleAliases().forEach(alias => aliases.add(alias)); }); return aliases; } /** * All the blocks referenced by this block and all the blocks they reference recursively. */ transitiveBlockDependencies(): Set<Block> { let deps = new Set<Block>(); this.referencedBlocks().forEach((block) => { deps.add(block); let moreDeps = block.transitiveBlockDependencies(); if (moreDeps.size > 0) { deps = new Set([...deps, ...moreDeps]); } }); return deps; } /** * All bhe blocks this block depends on. Same as referenced blocks except for the return type. */ blockDependencies(): Set<Block> { return new Set<Block>(this.referencedBlocks()); } *stylesFound(dynamic?: boolean): IterableIterator<Style> { let found = new Set<Style>(); for (let el of this.elements.values()) { for (let s of el.classesFound(dynamic)) { if (found.has(s)) continue; found.add(s); yield s; } for (let s of el.attributesFound(dynamic)) { if (found.has(s)) continue; found.add(s); yield s; } } } serializeSource(blockPaths?: Map<Block, string>): SerializedSourceAnalysis<K> { let elements: ObjectDictionary<SerializedElementSourceAnalysis> = {}; let { template, blocks, stylesFound, styleIndexes } = this._serializeSetup(blockPaths); // Serialize all discovered Elements. this.elements.forEach((el, key) => { elements[key] = el.serializeSourceAnalysis(styleIndexes); }); // Return serialized Analysis object. return { template, blocks, stylesFound, elements }; } /** * Generates a [[SerializedTemplateAnalysis]] for this analysis. */ serialize(blockPaths?: Map<Block, string>): SerializedAnalysis<K> { let elements: ObjectDictionary<SerializedElementAnalysis> = {}; let { template, blocks, stylesFound, styleIndexes } = this._serializeSetup(blockPaths); // Serialize all discovered Elements. this.elements.forEach((el, key) => { elements[key] = el.serialize(styleIndexes); }); // Return serialized Analysis object. return { template, blocks, stylesFound, elements }; } _serializeSetup(blockPaths?: Map<Block, string>) { let blocks = {}; let stylesFound: string[] = []; let template = this.template.serialize() as SerializedTemplateInfo<K>; let styleNameMap = new Map<Style, string>(); let styleIndexes = new Map<Style, number>(); let blocksUsed = new Set<Block>(); let styles = [...this.stylesFound()]; for (let found of styles) { blocksUsed.add(found.block); styleNameMap.set(found, this.serializedName(found)); } // Sort our found styles into an array. styles.sort((a, b) => { return styleNameMap.get(a)! > styleNameMap.get(b)! ? 1 : -1; }); styles.forEach((s, idx) => { stylesFound.push(styleNameMap.get(s)!); styleIndexes.set(s, idx); }); // Serialize our blocks to a map of their local names. Object.keys(this.blocks).forEach((localName) => { let block = this.blocks[localName]; if (blocksUsed.has(block)) { blocks[localName] = blockPaths && blockPaths.get(block) || block.identifier; } }); return { template, blocks, stylesFound, styleIndexes }; } /** * Creates a TemplateAnalysis from its serialized form. * @param serializedAnalysis The analysis to be recreated. * @param blockFactory for loading blocks referenced in the serialization. * @param parent The analyzer this analysis will belong to. */ static async deserializeSource ( serializedAnalysis: SerializedSourceAnalysis<keyof TemplateTypes>, blockFactory: BlockFactory, parent: Analyzer<keyof TemplateTypes>, ): Promise<Analysis<keyof TemplateTypes>> { let blockNames = Object.keys(serializedAnalysis.blocks); let info = TemplateInfoFactory.deserialize<keyof TemplateTypes>(serializedAnalysis.template); let analysis = parent.newAnalysis(info); let blockPromises = new Array<Promise<{name: string; block: Block}>>(); blockNames.forEach(n => { let blockIdentifier = serializedAnalysis.blocks[n]; let promise = blockFactory.getBlock(blockIdentifier).then(block => { return {name: n, block: block}; }); blockPromises.push(promise); }); let values = await allDone(blockPromises); // Create a temporary block so we can take advantage of `Block.lookup` // to easily resolve all BlockPaths referenced in the serialized analysis. // TODO: We may want to abstract this so we're not making a temporary block. let localScope = new Block("analysis-block", "tmp", "analysis-block"); values.forEach(o => { analysis.blocks[o.name] = o.block; localScope.addBlockReference(o.name, o.block); }); // We lookup each style by its serialized reference. // The index into the array is used elsewhere in this // serialized form to reference these styles. let styles = new Array<Style>(); serializedAnalysis.stylesFound.forEach(s => { let style = localScope.find(s); if (style) { styles.push(style); } else { throw new Error(`Cannot resolve ${s} to a block style.`); } }); // These are convenience accessors into the styles array that perform // bounds and type checking assertions. let styleRef = (index: number) => { let s = styles[index]; if (!s) { throw new Error("[internal error] Style index out of bounds!"); } return s; }; let classRef = (index: number) => { let s = styleRef(index); if (!(s instanceof BlockClass)) { throw new Error("[internal error] Block class expected."); } return s; }; let attrValueRef = (index: number) => { let s = styleRef(index); if (!(s instanceof AttrValue)) { throw new Error("[internal error] attribute value expected."); } return s; }; let elementNames = Object.keys(serializedAnalysis.elements); elementNames.forEach((elID) => { let data = serializedAnalysis.elements[elID]; let element = new ElementAnalysis<null, null, null>(data.sourceLocation || {start: POSITION_UNKNOWN}, parent.reservedClassNames(), data.tagName, elID); for (let analyzedStyle of data.analyzedStyles) { ElementAnalysis.deserializeAnalyzedStyle(element, analyzedStyle, styleRef, classRef, attrValueRef); } element.seal(); analysis.elements.set(elID, element); if (analysis.onElementAnalyzed) analysis.onElementAnalyzed(element); }); return analysis; } // XXX `deserialize` doesn't actually deserialize the elements in the // XXX serialized form. Thankfully, this method is never used. // TODO: Get rid of this serialized form and use the "source serialization" // TODO: as the only serialization because it's a better format for serializing // TODO: this data. /** * Creates a TemplateAnalysis from its serialized form. * * **DO NOT USE THIS METHOD, ITS NOT FULLY IMPLEMENTED.** * @param serializedAnalysis The analysis to be recreated. * @param blockFactory for loading blocks referenced in the serialization. * @param parent The analyzer this analysis will belong to. */ static async deserialize ( serializedAnalysis: SerializedAnalysis<keyof TemplateTypes>, blockFactory: BlockFactory, parent: Analyzer<keyof TemplateTypes>, ): Promise<Analysis<keyof TemplateTypes>> { let blockNames = Object.keys(serializedAnalysis.blocks); let info = TemplateInfoFactory.deserialize<keyof TemplateTypes>(serializedAnalysis.template); let analysis = parent.newAnalysis(info); let blockPromises = new Array<Promise<{name: string; block: Block}>>(); blockNames.forEach(n => { let blockIdentifier = serializedAnalysis.blocks[n]; let promise = blockFactory.getBlock(blockIdentifier).then(block => { return {name: n, block: block}; }); blockPromises.push(promise); }); let values = await allDone(blockPromises); // Create a temporary block so we can take advantage of `Block.lookup` // to easily resolve all BlockPaths referenced in the serialized analysis. // TODO: We may want to abstract this so we're not making a temporary block. let localScope = new Block("analysis-block", "tmp", "analysis-block"); values.forEach(o => { analysis.blocks[o.name] = o.block; localScope.addBlockReference(o.name, o.block); }); let objects = new Array<Style>(); serializedAnalysis.stylesFound.forEach(s => { let style = localScope.find(s); if (style) { objects.push(style); } else { throw new Error(`Cannot resolve ${s} to a block style.`); } }); let elementNames = Object.keys(serializedAnalysis.elements); elementNames.forEach((elID) => { let data = serializedAnalysis.elements[elID]; let element = new ElementAnalysis<null, null, null>(data.sourceLocation || {start: POSITION_UNKNOWN}, parent.reservedClassNames(), data.tagName, elID); element.seal(); analysis.elements.set(elID, element); }); return analysis; } forOptimizer(config: ResolvedConfiguration): OptimizationTemplateAnalysis<K> { let optAnalysis = new OptimizationTemplateAnalysis<K>(this.template); for (let element of this.elements.values()) { let result = element.forOptimizer(config); optAnalysis.elements.push(result[0]); } return optAnalysis; } } export interface IAnalysis<K extends keyof TemplateTypes> extends Analysis<K> {}
the_stack
import { DecorationRenderOptions } from 'vscode'; import { TheTask } from './TheTask'; /** * Object describing items for Tree View Provider */ export interface ItemForProvider { title: string; tasks: TheTask[]; } /** * Due date possible values */ export const enum DueState { notDue, due, overdue, invalid, } /** * tags Tree View sorting options */ export const enum TreeItemSortType { alphabetic = 'alphabetic', count = 'count', } export const enum SortNestedTasks { default = 'default', none = 'none', } /** * Advanced decorations allowing to change any available editor decoration options (borders, outline, background, foreground, before, after...) * * https://code.visualstudio.com/api/references/vscode-api#DecorationRenderOptions */ const enum AdvancedDecorations { project = 'project', context = 'context', tag = 'tag', comment = 'comment', notDue = 'notDue', due = 'due', overdue = 'overdue', invalidDue = 'invalidDue', priorityAForeground = 'priorityAForeground', priorityBForeground = 'priorityBForeground', priorityCForeground = 'priorityCForeground', priorityDForeground = 'priorityDForeground', priorityEForeground = 'priorityEForeground', priorityFForeground = 'priorityFForeground', completedTask = 'completedTask', } /** * Extension options available to user. Names should match **"configuration"** object properties in `package.json` file. */ export interface ExtensionConfig { /** * When true - shows more items in Command Palette. */ isDev: boolean; /** * When creating a task add creation date to it: `{cr:2020-04-30}` */ addCreationDate: boolean; /** * Whether to include date when completing a task: `{cm}` vs `{cm:2020-04-30}` */ completionDateIncludeDate: boolean; /** * When completing a task add date and time: `{cm:2020-04-30T09:11:17}` */ completionDateIncludeTime: boolean; /** * When creating a task add date and time: `{cr:2020-04-30T09:11:17}` */ creationDateIncludeTime: boolean; /** * When enabled - will move tasks to archive file (on completion). */ autoArchiveTasks: boolean; /** * Show confirmation when deleting task from Tree View or Webview. */ confirmTaskDelete: 'always' | 'hasNestedTasks' | 'never'; /** * Controls visibility of status bar task progress item `1/3 33%` */ statusBarCounterEnabled: boolean; /** * Controls tags Tree View sorting. */ sortTagsView: TreeItemSortType; /** * Controls projects Tree View sorting. */ sortProjectsView: TreeItemSortType; /** * Controls contexts Tree View sorting. */ sortContextsView: TreeItemSortType; /** * Controls task sorting in tags/projects/contexts Tree Views. */ sortNestedTasks: SortNestedTasks; /** * Choose files that extension will operate on (Glob). */ activatePattern: string; /** * When enabled - duration (editor, hover) includes seconds. */ durationIncludeSeconds: boolean; /** * Add items to autocomplete and optional description on hover. */ suggestItems: Record<string, string>; /** Editor decoration for nested tasks progress (pie chart) background. */ progressBackground: string; /** Editor decoration for nested tasks progress (pie chart) foreground. */ progressForeground: string; /** * Advanced decorations allowing to change any available editor decoration options (borders, outline, background, foreground, before, after...) */ decorations: { [key in AdvancedDecorations]: DecorationRenderOptions; }; /** * Number used for parsing nested tasks when indentation cannot be guessed (file is not opened in editor). */ tabSize: number; /** * Filters that you can pick when applying a filter. */ savedFilters: { title: string; filter: string; }[]; /** * Absolute file path to default file. (Used for webview or TreeView when no active file is opened) */ defaultFile: string; /** * Absolute file path to archive file */ defaultArchiveFile: string; /** * Add more tree views with predefined filters. */ treeViews: { title: string; filter: string; }[]; /** * Number of tasks returned by `getFewNextTasks` command. */ getNextNumberOfTasks: number; /** * Prefix for task that is due in labels (tree view, notification, modal, quick pick). */ labelDueSymbol: string; /** * Prefix for task that is overdue in labels (tree view, notification, modal, quick pick). */ labelOverdueSymbol: string; /** * Prefix for task that has invalid due date in labels (tree view, notification, modal, quick pick). */ labelInvalidDueSymbol: string; /** * Show projects/tags/contexts in labels (tree view, notification, modal, quick pick). */ labelShowItems: boolean; /** * Show strike-through text decoration for completed tasks in editor. */ completedStrikeThrough: boolean; /** * Options only applied to webview */ webview: { /** * Show autocomplete when typing. (When disabled suggest can be called by `Ctrl`+`Space`) */ autoShowSuggest: boolean; /** * If `true` - show transparent scrollbar on top of items. */ scrollbarOverflow: boolean; /** * Whether completed tasks are shown or not in the webview. */ showCompleted: boolean; /** * Whether recurring not due tasks are shown or not in the webview. */ showRecurringUpcoming: boolean; /** * Whether recurring completed tasks are shown or not in the webview. */ showRecurringCompleted: boolean; /** * Whether completed tasks should have a line drawn on them in the webview. */ completedStrikeThrough: boolean; /** * When true - show box on the bottom of the webview with selected task details. */ showTaskDetails: boolean; /** * Controls whether priority is shown in the webview. */ showPriority: boolean; /** * Controls whether checkbox is shown in the webview. */ showCheckbox: boolean; /** * When true - show notification after completing a task. */ notificationsEnabled: boolean; /** * Controls font size in the webview. */ fontSize: string; /** * Controls font family in the webview. */ fontFamily: string; /** * Controls line height in the webview. */ lineHeight: number; /** * Whether checkbox is rendered as native input element or a custom styled element. */ customCheckboxEnabled: boolean; /** * Controls spacing between items in a list. */ padding: string; /** * Visual distance of nested items. */ indentSize: string; /** * Set different color for any tag in a webview. */ tagStyles: { [tagName: string]: { color: string; backgroundColor: string; }; }; /** * Absolute path to custom CSS for the webview. */ customCSSPath: string; }; } /** * This extension context names */ export const enum VscodeContext { isActive = 'todomd:isActive', isDev = 'todomd:isDev', filterActive = 'todomd:filterActive', generic1FilterExists = 'todomd:generic1FilterExists', generic2FilterExists = 'todomd:generic2FilterExists', generic3FilterExists = 'todomd:generic3FilterExists', } /** * Helper type makes all properties optional with exceptions of required ones */ export type OptionalExceptFor<T, TRequired extends keyof T> = Partial<T> & Pick<T, TRequired>; interface WebviewMessageBase { type: string; value: unknown; } // From extension to webview interface WebviewMessageUpdateEverything extends WebviewMessageBase { type: 'updateEverything'; value: { tasksAsTree: TheTask[]; tags: string[]; projects: string[]; contexts: string[]; defaultFileSpecified: boolean; activeDocumentOpened: boolean; config: ExtensionConfig['webview']; }; } interface WebviewMessageFocusFilterInput { type: 'focusFilterInput'; } // From webview to extension interface WebviewMessageToggleDone extends WebviewMessageBase { type: 'toggleDone'; value: number; } interface WebviewMessageToggleCollapse extends WebviewMessageBase { type: 'toggleTaskCollapse'; value: number; } interface WebviewMessageToggleTaskCollapseRecursive extends WebviewMessageBase { type: 'toggleTaskCollapseRecursive'; value: number; } interface WebviewMessageShowNotification extends WebviewMessageBase { type: 'showNotification'; value: string; } interface WebviewMessageGoToTask extends WebviewMessageBase { type: 'goToTask'; value: number; } interface WebviewMessageIncrementCount extends WebviewMessageBase { type: 'incrementCount'; value: number; } interface WebviewMessageDecrementCount extends WebviewMessageBase { type: 'decrementCount'; value: number; } interface WebviewMessageDeleteTask extends WebviewMessageBase { type: 'deleteTask'; value: number; } interface WebviewMessageUpdateTitle extends WebviewMessageBase { type: 'updateWebviewTitle'; value: number; } interface WebviewMessageOpenFileByPath extends WebviewMessageBase { type: 'openFileByPath'; value: string; } interface WebviewMessageOpenFileInDefaultApp extends WebviewMessageBase { type: 'openInDefaultApp'; value: string; } interface WebviewMessageEditTaskRawText extends WebviewMessageBase { type: 'editTaskRawText'; value: { lineNumber: number; newRawText: string; }; } interface WebviewMessageEditTask extends WebviewMessageBase { type: 'editTask'; value: TheTask; } interface WebviewMessageSetDueDate extends WebviewMessageBase { type: 'setDueDate'; value: number; } interface WebviewMessageStartTask extends WebviewMessageBase { type: 'startTask'; value: number; } /** * Messages that can only be sent from webview to extension. */ export type MessageFromWebview = WebviewMessageDecrementCount | WebviewMessageDeleteTask | WebviewMessageEditTask | WebviewMessageEditTaskRawText | WebviewMessageGoToTask | WebviewMessageIncrementCount | WebviewMessageOpenFileByPath | WebviewMessageOpenFileInDefaultApp | WebviewMessageSetDueDate | WebviewMessageShowNotification | WebviewMessageStartTask | WebviewMessageToggleCollapse | WebviewMessageToggleDone | WebviewMessageToggleTaskCollapseRecursive | WebviewMessageUpdateTitle; /** * Messages that can only be sent from extension to webview. */ export type MessageToWebview = WebviewMessageFocusFilterInput | WebviewMessageUpdateEverything; /** * All commands contributed by this extension. */ export const enum CommandIds { toggleDone = 'todomd.toggleDone', hideTask = 'todomd.hideTask', collapseAllNestedTasks = 'todomd.collapseAllNestedTasks', expandAllTasks = 'todomd.expandAllTasks', focusTasksWebviewAndInput = 'todomd.focusTasksWebviewAndInput', deleteTask = 'todomd.deleteTask', archiveCompletedTasks = 'todomd.archiveCompletedTasks', archiveSelectedCompletedTasks = 'todomd.archiveSelectedCompletedTasks', startTask = 'todomd.startTask', sortByPriority = 'todomd.sortByPriority', sortByDefault = 'todomd.sortByDefault', createSimilarTask = 'todomd.createSimilarTask', getNextTask = 'todomd.getNextTask', getFewNextTasks = 'todomd.getFewNextTasks', getRandomTask = 'todomd.getRandomTask', addTaskToDefaultFile = 'todomd.addTaskToDefaultFile', addTaskToActiveFile = 'todomd.addTaskToActiveFile', setDueDate = 'todomd.setDueDate', setDueDateWithArgs = 'todomd.setDueDateWithArgs', openDefaultArchiveFile = 'todomd.openDefaultArchiveFile', openDefaultFile = 'todomd.openDefaultFile', specifyDefaultFile = 'todomd.specifyDefaultFile', specifyDefaultArchiveFile = 'todomd.specifyDefaultArchiveFile', completeTask = 'todomd.completeTask', filter = 'todomd.filter', clearFilter = 'todomd.clearFilter', clearGlobalState = 'todomd.clearGlobalState', showGlobalState = 'todomd.showGlobalState', removeAllOverdue = 'todomd.removeAllOverdue', goToLine = 'todomd.goToLine', goToLineInArchived = 'todomd.goToLineInArchived', resetAllRecurringTasks = 'todomd.resetAllRecurringTasks', followLink = 'todomd.followLink', setLastVisit = 'todomd.setLastVisit', incrementPriority = 'todomd.incrementPriority', decrementPriority = 'todomd.decrementPriority', showWebviewSettings = 'todomd.showWebviewSettings', showDefaultFileSetting = 'todomd.showDefaultFileSetting', webviewToggleShowRecurringUpcoming = 'todomd.webview.toggleShowRecurringUpcoming', toggleComment = 'todomd.toggleComment', toggleTagsTreeViewSorting = 'todomd.toggleTagsTreeViewSorting', toggleProjectsTreeViewSorting = 'todomd.toggleProjectsTreeViewSorting', toggleContextsTreeViewSorting = 'todomd.toggleContextsTreeViewSorting', sortTaskParts = 'todomd.sortTaskParts', // ──── Dev ─────────────────────────────────────────────────── replaceWithToday = 'todomd.dev.replaceDateWithToday', }
the_stack
import React, { FunctionComponent, useState, useEffect, useCallback } from 'react'; import { ContentSwitcher, Form, Switch, MultiSelect } from 'carbon-components-react'; import TransactionManualInput from '../TransactionManualInput/TransactionManualInput'; import TransactionDataInput from '../TransactionDataInput/TransactionDataInput'; import TransactionSubmitButtons from '../TransactionSubmitButtons/TransactionSubmitButtons'; import ISmartContract from '../../../interfaces/ISmartContract'; import IDataFileTransaction from '../../../interfaces/IDataFileTransaction'; import ITransactionManualInput from '../../../interfaces/ITransactionManualInput'; import { ExtensionCommands } from '../../../ExtensionCommands'; import Utils from '../../../Utils'; import IAssociatedTxdata from '../../../interfaces/IAssociatedTxdata'; import ITransaction from '../../../interfaces/ITransaction'; import './TransactionInputContainer.scss'; interface IProps { smartContract: ISmartContract | undefined; associatedTxdata: IAssociatedTxdata; preselectedTransaction: ITransaction; setTransactionSubmitted: () => void; } const emptyTransaction: ITransaction = { name: '', parameters: [], returns: { type: '' }, tag: [] }; const activeTransactionExists: any = (smartContract: ISmartContract, currentlyActiveTransaction: ITransaction) => { const index: number = smartContract.transactions.findIndex((transaction) => ( JSON.stringify(transaction) === JSON.stringify(currentlyActiveTransaction) )); return index > -1; }; const areTransactionArgsValid: (t: string) => boolean = (transactionArguments: string) => { if (transactionArguments === '') { return true; } try { JSON.parse(transactionArguments); return true; } catch { return false; } }; const convertJSONToArgs: (t: string, tr: ITransaction) => Array<string> = (transactionArguments: string, transaction: ITransaction) => { if (!transactionArguments) { return []; } const args: { [key: string]: any } = JSON.parse(transactionArguments); let argKeys: string[] = Object.keys(args); if (transaction !== emptyTransaction && transaction.parameters && transaction.parameters.length > 0) { // Typos in the arg names will lead to missing parameters, which is confusing // from a user perspective. Only use default order if there are no typos. const argNames: string[] = transaction.parameters.map((entry: any) => entry.name).filter((name: string) => argKeys.includes(name)); if (argKeys.length === argNames.length) { argKeys = argNames; } } const array: Array<any> = argKeys.map((key: string) => typeof args[key] === 'object' && args[key] !== null ? JSON.stringify(args[key]) : `${args[key]}`); return array; }; const getArgsFromTransactionAndConvertToJSON: any = (transaction: ITransaction, transactionArguments: string): string => { if (transaction && transaction.name !== '' && transaction.parameters && transaction.parameters.length > 0) { const args: { [key: string]: any } = {}; let parsedTransactionArguments: { [key: string]: any }; try { parsedTransactionArguments = JSON.parse(transactionArguments); } catch { parsedTransactionArguments = {}; } transaction.parameters.forEach(({ name }) => { args[name] = (parsedTransactionArguments && parsedTransactionArguments[name]) ? parsedTransactionArguments[name] : ''; }); return JSON.stringify(args, null, 2); } return '[]'; }; const TransactionInputContainer: FunctionComponent<IProps> = ({ smartContract, associatedTxdata, preselectedTransaction, setTransactionSubmitted }) => { const [smartContractName, setNewSmartContractName] = useState(smartContract ? smartContract.name : ''); const [currentPreselectedTransaction, setCurrentPreselectedTransaction] = useState(preselectedTransaction); const [isManual, setIsManual] = useState(true); const [peerTargetNames, setPeerTargetNames] = useState(smartContract ? smartContract.peerNames : []); const [manualInputState, updateManualInputState] = useState<ITransactionManualInput>({ activeTransaction: preselectedTransaction || emptyTransaction, transactionArguments: '[]', transientData: '', }); // The data input transaction only needs the transaction. // When more is needed, convert it to an object like above const [dataInputTransaction, updateDataInputTransaction] = useState<IDataFileTransaction>({ transactionName: '', transactionLabel: '', txDataFile: '', arguments: [], transientData: {} }); const setManualActiveTransaction: any = useCallback((activeTransaction: ITransaction) => { if (activeTransaction !== manualInputState.activeTransaction) { let args: string = '[]'; if (activeTransaction !== emptyTransaction) { args = getArgsFromTransactionAndConvertToJSON(activeTransaction, manualInputState.transactionArguments); } updateManualInputState({ ...manualInputState, activeTransaction, transactionArguments: args }); } }, [manualInputState]); useEffect(() => { const { activeTransaction } = manualInputState; if (smartContract && smartContract.namespace !== undefined && activeTransaction && activeTransaction.name !== '' && !activeTransactionExists(smartContract, activeTransaction)) { // if the smartContract is changed/updated, only persist the activeTransaction if it still exists setManualActiveTransaction(emptyTransaction); } }, [smartContract, manualInputState, setManualActiveTransaction]); useEffect(() => { const smartContractChanged: boolean = !smartContract || smartContract.name !== smartContractName; if (smartContractChanged) { setNewSmartContractName(smartContract ? smartContract.name : ''); // If smart contract is changed, clear the data input transaction no matter if it exists or not updateDataInputTransaction({ transactionName: '', transactionLabel: '', txDataFile: '', arguments: [], transientData: {} }); } }, [smartContract, smartContractName, updateDataInputTransaction]); useEffect(() => { // If the preselectedTransaction is changed, update the activeTransaction const preselectedTransactionHasChanged: boolean = preselectedTransaction !== currentPreselectedTransaction; if (preselectedTransactionHasChanged) { if (preselectedTransaction && preselectedTransaction.name) { setManualActiveTransaction(preselectedTransaction); } else { setManualActiveTransaction(emptyTransaction); } setCurrentPreselectedTransaction(preselectedTransaction); } }, [preselectedTransaction, currentPreselectedTransaction, setManualActiveTransaction]); const submitTransaction: any = (evaluate: boolean, activeTransaction: ITransaction): void => { const command: string = evaluate ? ExtensionCommands.EVALUATE_TRANSACTION : ExtensionCommands.SUBMIT_TRANSACTION; const args: Array<string> = isManual ? convertJSONToArgs(manualInputState.transactionArguments, activeTransaction) : dataInputTransaction.arguments; const data: any = { evaluate, peerTargetNames, smartContract: smartContractName, channelName: smartContract && smartContract.channel, namespace: smartContract && smartContract.namespace, transactionName: isManual ? manualInputState.activeTransaction.name : dataInputTransaction.transactionName, args, transientData: isManual ? manualInputState.transientData : dataInputTransaction.transientData, txDataFile: isManual ? undefined : dataInputTransaction.txDataFile, }; Utils.postToVSCode({ command, data }); setTransactionSubmitted(); }; const updateCustomPeers: any = (event: { selectedItems: { id: string; label: string}[] } ): void => { const peers: string[] = event.selectedItems.map((peerObject: {id: string, label: string }) => { return peerObject.id; }); setPeerTargetNames(peers); }; const formatPeersForMultiSelect: any = (peers: string[]): { id: string, label: string }[] => { return peers.map((peer) => ({ id: peer, label: peer })); }; const transactionArgumentsAreValid: boolean = areTransactionArgsValid(manualInputState.transactionArguments); const shouldDisableManual: boolean = !manualInputState.activeTransaction.name || !transactionArgumentsAreValid; const shouldDisableDataFile: boolean = dataInputTransaction.transactionName === ''; const shouldDisableButtons: boolean = (isManual && shouldDisableManual) || (!isManual && shouldDisableDataFile) || (peerTargetNames && peerTargetNames.length === 0); const transaction: ITransaction = manualInputState.activeTransaction; // tslint:disable-next-line: no-console const ignoreEvent: any = (e: any) => console.log('event ignored', e); return ( <> <ContentSwitcher className='transaction-input-content-switch' selectionMode='manual' onChange={() => setIsManual(!isManual)}> {/* Typescript requires the onClick and onKeyDown functions but we don't need them */} <Switch name='one' text='Manual input' data-testid='content-switch-manual' onClick={ignoreEvent} onKeyDown={ignoreEvent} /> <Switch name='two' text='Transaction data directory' data-testid='content-switch-data' onClick={ignoreEvent} onKeyDown={ignoreEvent}/> </ContentSwitcher> <Form id='create-txn-form'> {isManual ? ( <TransactionManualInput smartContract={smartContract} manualInputState={manualInputState} setManualInput={updateManualInputState} setActiveTransaction={setManualActiveTransaction} transactionArgumentsAreValid={transactionArgumentsAreValid} /> ) : ( <TransactionDataInput smartContract={smartContract} associatedTxdata={associatedTxdata} selectedTransaction={dataInputTransaction} updateTransaction={updateDataInputTransaction} /> ) } <MultiSelect id='peer-select' initialSelectedItems={formatPeersForMultiSelect(peerTargetNames)} items={smartContract && formatPeersForMultiSelect(smartContract.peerNames)} label='Select peers' onChange={updateCustomPeers} titleText={'Target specific peer (optional)'} disabled={!smartContract} /> <TransactionSubmitButtons transaction={transaction} shouldDisableButtons={shouldDisableButtons} submitTransaction={submitTransaction} /> </Form> </> ); }; export default TransactionInputContainer;
the_stack
import { getScaleFactor } from './Scale'; /** * @ignore */ export function getOrbitShaderFragment() { return ` varying vec3 vColor; uniform sampler2D texture; void main() { gl_FragColor = vec4(vColor, 1.0) * texture2D(texture, gl_PointCoord); } `; } /** * @ignore */ export function getOrbitShaderVertex() { return ` attribute vec3 fuzzColor; attribute vec3 origin; varying vec3 vColor; attribute float size; attribute float a; attribute float e; attribute float i; attribute float om; attribute float wBar; attribute float M; // Perihelion distance attribute float q; // CPU-computed term for parabolic orbits attribute float a0; // COSH Function (Hyperbolic Cosine) float cosh(float val) { float tmp = exp(val); float cosH = (tmp + 1.0 / tmp) / 2.0; return cosH; } // TANH Function (Hyperbolic Tangent) float tanh(float val) { float tmp = exp(val); float tanH = (tmp - 1.0 / tmp) / (tmp + 1.0 / tmp); return tanH; } // SINH Function (Hyperbolic Sine) float sinh(float val) { float tmp = exp(val); float sinH = (tmp - 1.0 / tmp) / 2.0; return sinH; } // Cube root helper that assumes param is positive float cbrt(float x) { return exp(log(x) / 3.0); } vec3 getPosNearParabolic() { // See https://stjarnhimlen.se/comp/ppcomp.html#17 float b = sqrt(1.0 + a0 * a0); float W = cbrt(b + a0) - cbrt(b - a0); float f = (1.0 - e) / (1.0 + e); float a1 = 2.0 / 3.0 + (2.0 / 5.0) * W * W; float a2 = 7.0 / 5.0 + (33.0 / 35.0) * W * W + (37.0 / 175.0) * pow(W, 4.0); float a3 = W * W * (432.0 / 175.0 + (956.0 / 1125.0) * W * W + (84.0 / 1575.0) * pow(W, 4.0)); float C = (W * W) / (1.0 + W * W); float g = f * C * C; float w = W * (1.0 + f * C * (a1 + a2 * g + a3 * g * g)); // True anomaly float v = 2.0 * atan(w); // Heliocentric distance float r = (q * (1.0 + w * w)) / (1.0 + w * w * f); // Compute heliocentric coords. float i_rad = i; float o_rad = om; float p_rad = wBar; float X = r * (cos(o_rad) * cos(v + p_rad - o_rad) - sin(o_rad) * sin(v + p_rad - o_rad) * cos(i_rad)); float Y = r * (sin(o_rad) * cos(v + p_rad - o_rad) + cos(o_rad) * sin(v + p_rad - o_rad) * cos(i_rad)); float Z = r * (sin(v + p_rad - o_rad) * sin(i_rad)); return vec3(X, Y, Z); } vec3 getPosHyperbolic() { float F0 = M; for (int count = 0; count < 100; count++) { float F1 = (M + e * (F0 * cosh(F0) - sinh(F0))) / (e * cosh(F0) - 1.0); float lastdiff = abs(F1 - F0); F0 = F1; if (lastdiff < 0.0000001) { break; } } float F = F0; float v = 2.0 * atan(sqrt((e + 1.0) / (e - 1.0))) * tanh(F / 2.0); float r = ${getScaleFactor().toFixed( 1, )} * (a * (1.0 - e * e)) / (1.0 + e * cos(v)); // Compute heliocentric coords. float i_rad = i; float o_rad = om; float p_rad = wBar; float X = r * (cos(o_rad) * cos(v + p_rad - o_rad) - sin(o_rad) * sin(v + p_rad - o_rad) * cos(i_rad)); float Y = r * (sin(o_rad) * cos(v + p_rad - o_rad) + cos(o_rad) * sin(v + p_rad - o_rad) * cos(i_rad)); float Z = r * (sin(v + p_rad - o_rad) * sin(i_rad)); return vec3(X, Y, Z); } vec3 getPosEllipsoid() { float i_rad = i; float o_rad = om; float p_rad = wBar; // Estimate eccentric and true anom using iterative approximation (this // is normally an intergral). float E0 = M; float E1 = M + e * sin(E0); float lastdiff = abs(E1-E0); E0 = E1; for (int count = 0; count < 100; count++) { E1 = M + e * sin(E0); lastdiff = abs(E1-E0); E0 = E1; if (lastdiff < 0.0000001) { break; } } float E = E0; float v = 2.0 * atan(sqrt((1.0+e)/(1.0-e)) * tan(E/2.0)); // Compute radius vector. float r = ${getScaleFactor().toFixed( 1, )} * a * (1.0 - e * e) / (1.0 + e * cos(v)); // Compute heliocentric coords. float X = r * (cos(o_rad) * cos(v + p_rad - o_rad) - sin(o_rad) * sin(v + p_rad - o_rad) * cos(i_rad)); float Y = r * (sin(o_rad) * cos(v + p_rad - o_rad) + cos(o_rad) * sin(v + p_rad - o_rad) * cos(i_rad)); float Z = r * (sin(v + p_rad - o_rad) * sin(i_rad)); return vec3(X, Y, Z); } vec3 getPos() { if (e > 0.9 && e < 1.2) { return getPosNearParabolic(); } else if (e > 1.2) { return getPosHyperbolic(); } return getPosEllipsoid(); } void main() { vColor = fuzzColor; vec3 newpos = getPos() + origin; vec4 mvPosition = modelViewMatrix * vec4(newpos, 1.0); gl_Position = projectionMatrix * mvPosition; gl_PointSize = size; } `; } export const STAR_SHADER_FRAGMENT = ` varying vec3 vColor; void main() { float a = 1.0 - 2.0 * length(gl_PointCoord - vec2(0.5, 0.5)); gl_FragColor = vec4(vColor, a); } `; export const STAR_SHADER_VERTEX = ` attribute float size; varying vec3 vColor; void main() { vColor = color; vec4 mvPosition = modelViewMatrix * vec4(position, 1.0); gl_PointSize = size; gl_Position = projectionMatrix * mvPosition; } `; export const GENERIC_PARTICLE_SHADER_VERTEX = ` attribute float size; attribute vec3 customColor; varying vec3 vColor; void main() { vColor = customColor; vec4 mvPosition = modelViewMatrix * vec4(position, 1.0); gl_PointSize = size * (300.0 / -mvPosition.z); gl_Position = projectionMatrix * mvPosition; } `; export const GENERIC_PARTICLE_SHADER_FRAGMENT = ` uniform vec3 color; uniform sampler2D texture; varying vec3 vColor; void main() { gl_FragColor = vec4(color * vColor, 1.0); gl_FragColor = gl_FragColor * texture2D(texture, gl_PointCoord); if (gl_FragColor.a < ALPHATEST) discard; } `; export const ATMOSPHERE_SHADER_VERTEX = ` uniform vec3 lightPos; varying vec2 vUv; varying vec3 vecPos; varying vec3 vecNormal; //varying vec3 vNormal; varying vec3 vViewLightPos; void main() { //vNormal = normalize(normalMatrix * normal); //gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); vUv = uv; // Since the light is in camera coordinates, // I'll need the vertex position in camera coords too vecPos = (modelViewMatrix * vec4(position, 1.0)).xyz; // That's NOT exacly how you should transform your // normals but this will work fine, since my model // matrix is pretty basic vecNormal = (modelViewMatrix * vec4(normal, 0.0)).xyz; vViewLightPos = (viewMatrix * vec4(lightPos, 1.0)).xyz; gl_Position = projectionMatrix * vec4(vecPos, 1.0); } `; // With help from https://stackoverflow.com/questions/43621274/how-to-correctly-set-lighting-for-custom-shader-material export const ATMOSPHERE_SHADER_FRAGMENT = ` uniform float c; uniform float p; uniform vec3 color; varying vec2 vUv; varying vec3 vecPos; varying vec3 vecNormal; varying vec3 vViewLightPos; void main() { float intensity = pow(c - dot(vecNormal, vec3(0.0, 0.0, 1.0)), p); vec4 addedLights = vec4(0.0, 0.0, 0.0, 1.0); vec3 lightDirection = normalize(vecPos - vViewLightPos); addedLights.rgb += clamp(dot(-lightDirection, vecNormal), 0.0, 1.0) * 1.0 /* intensity */; // * pointLights[i].color gl_FragColor = vec4(color, 1.0) * intensity * addedLights; } `; export const SPHERE_SHADER_VERTEX = ` uniform vec3 lightPos; varying vec2 vUv; varying vec3 vViewPosition; varying vec3 vViewLightPos; varying vec3 vNormal; void main() { vUv = uv; vec4 vViewPosition4 = modelViewMatrix * vec4(position, 1.0); vViewPosition = vViewPosition4.xyz; vViewLightPos = (viewMatrix * vec4(lightPos, 1.0)).xyz; vNormal = normalMatrix * normal; gl_Position = projectionMatrix * vViewPosition4; } `; export const SPHERE_SHADER_FRAGMENT = ` uniform sampler2D sphereTexture; varying vec2 vUv; varying vec3 vNormal; varying vec3 vViewPosition; varying vec3 vViewLightPos; void main() { vec3 normal = normalize(vNormal); vec3 lightDir = normalize(vViewLightPos - vViewPosition); float lambertian = max(dot(normal, lightDir), 0.0); gl_FragColor = texture2D(sphereTexture, vUv) * vec4(vec3(1.0) * lambertian, 1.0); } `; export const RING_SHADER_VERTEX = ` varying vec3 vPos; varying vec3 vWorldPosition; varying vec3 vNormal; void main() { vPos = position; vec4 worldPosition = (modelMatrix * vec4(position, 1.)); gl_Position = projectionMatrix * viewMatrix * vec4(worldPosition.xyz, 1.); vNormal = normalMatrix * normal; vWorldPosition = worldPosition.xyz; } `; export const RING_SHADER_FRAGMENT = ` uniform sampler2D ringTexture; uniform float innerRadius; uniform float outerRadius; uniform vec3 lightPos; varying vec3 vNormal; varying vec3 vPos; varying vec3 vWorldPosition; vec4 color() { vec2 uv = vec2(0); uv.x = (length(vPos) - innerRadius) / (outerRadius - innerRadius); if (uv.x < 0.0 || uv.x > 1.0) { discard; } vec4 pixel = texture2D(ringTexture, uv); return pixel; } vec3 shadow() { vec3 lightDir = normalize(vPos - lightPos); vec3 planetPos = vec3(0); vec3 ringPos = vPos - planetPos; float posDotLightDir = dot(ringPos, lightDir); float posDotLightDir2 = posDotLightDir * posDotLightDir; // TODO(ian): Generalize this line. float radius = 0.0389259903; // radius of saturn in coordinate system float radius2 = radius * radius; if (posDotLightDir > 0.0 && dot(ringPos, ringPos) - posDotLightDir2 < radius2) { return vec3(0.0); } return vec3(1.0); } vec3 lights() { vec3 lightDirection = normalize(vWorldPosition - lightPos); float c = 0.35 + max(0.0, dot(vNormal, lightDirection)) * 0.4; return vec3(c); } void main() { // NOTE: The order of multiplication matters here. color() may call // discard, which would cause problems on some Windows graphics drivers if // it is a left operand. // https://github.com/typpo/spacekit/issues/22 gl_FragColor = vec4(lights() * shadow(), 1.0) * color(); } `;
the_stack
import * as React from "react"; import { ZxSpectrumCoreBase } from "../machines/zx-spectrum/ZxSpectrumCoreBase"; import Key from "./Sp48Key"; import { Sp48ButtonClickArgs } from "./ui-core-types"; import styles from "styled-components"; import { getVmEngineService } from "../machines/core/vm-engine-service"; const DEFAULT_WIDTH = 10 * 104 + 130 + 48; const DEFAULT_HEIGHT = 4 * (128 + 16) + 48; interface Props { width: number; height: number; } /** * Represents the statusbar of the emulator */ export default function Sp48Keyboard(props: Props) { const zoom = calculateZoom(props.width, props.height); const row1Shift = 80 * zoom; const row2Shift = 110 * zoom; return ( <Root> <KeyRow> <Key zoom={zoom} code={15} keyAction={handleClick} topNum="BLUE" topNumColor="#0030ff" main="1" symbol="!" above="EDIT" below="DEF FN" glyph={1} /> <Key zoom={zoom} code={16} keyAction={handleClick} topNum="RED" topNumColor="#ff0000" main="2" symbol="@" above="CAPS LOCK" below="FN" glyph={2} /> <Key zoom={zoom} code={17} keyAction={handleClick} topNum="MAGENTA" topNumColor="#e000e0" main="3" symbol="#" above="TRUE VID" below="LINE" glyph={3} /> <Key zoom={zoom} code={18} keyAction={handleClick} topNum="GREEN" topNumColor="#00c000" main="4" symbol="$" above="INV.VIDEO" below="OPEN" glyph={4} /> <Key zoom={zoom} code={19} keyAction={handleClick} topNum="CYAN" topNumColor="#00c0c0" main="5" symbol="%" above={"\u140a"} below="CLOSE" glyph={5} /> <Key zoom={zoom} code={24} keyAction={handleClick} topNum="YELLOW" topNumColor="#fff000" main="6" symbol={"&"} above={"\u1401"} below="MOVE" glyph={6} /> <Key zoom={zoom} code={23} keyAction={handleClick} topNum="WHITE" topNumColor="#ffffff" main="7" symbol={"'"} above={"\u1403"} below="ERASE" glyph={7} /> <Key zoom={zoom} code={22} keyAction={handleClick} topNum="UNBRIGHT" topNumColor="#a0a0a0" main="8" symbol={"("} above={"\u1405"} below="POINT" glyph={16} /> <Key zoom={zoom} code={21} keyAction={handleClick} topNum="BRIGHT" main="9" symbol={")"} above="GRAPHICS" below="CAT" /> <Key zoom={zoom} code={20} keyAction={handleClick} topNum="BLACK" topNumColor="#606060" main="0" symbol={"\uff3f"} above="DELETE" below="FORMAT" /> </KeyRow> <KeyRow style={{ marginLeft: row1Shift }}> <Key zoom={zoom} code={10} keyAction={handleClick} main="Q" keyword="PLOT" symbol="<=" above="SIN" below="ASN" /> <Key zoom={zoom} code={11} keyAction={handleClick} main="W" keyword="DRAW" symbol="<>" above="COS" below="ACS" /> <Key zoom={zoom} code={12} keyAction={handleClick} main="E" keyword="REM" symbol=">=" above="TAN" below="ATB" /> <Key zoom={zoom} code={13} keyAction={handleClick} main="R" keyword="RUN" symbol="<" above="INT" below="VERIFY" /> <Key zoom={zoom} code={14} keyAction={handleClick} main="T" keyword="RAND" symbol=">" above="RND" below="MERGE" /> <Key zoom={zoom} code={29} keyAction={handleClick} main="Y" keyword="RETURN" symbolWord="AND" above="STR$" below="[" /> <Key zoom={zoom} code={28} keyAction={handleClick} main="U" keyword="IF" symbolWord="OR" above="CHR$" below="]" /> <Key zoom={zoom} code={27} keyAction={handleClick} main="I" keyword="INPUT" symbolWord="AT" above="CODE" below="IN" /> <Key zoom={zoom} code={26} keyAction={handleClick} main="O" keyword="POKE" symbol=";" above="PEEK" below="OUT" /> <Key zoom={zoom} code={25} keyAction={handleClick} main="P" keyword="PRINT" symbol={'"'} above="TAB" below="(C)" /> </KeyRow> <KeyRow style={{ marginLeft: row2Shift }}> <Key zoom={zoom} code={5} keyAction={handleClick} main="A" keyword="NEW" symbolWord="STOP" above="READ" below="~" /> <Key zoom={zoom} code={6} keyAction={handleClick} main="S" keyword="SAVE" symbolWord="NOT" above="RESTORE" below="|" /> <Key zoom={zoom} code={7} keyAction={handleClick} main="D" keyword="DIM" symbolWord="STEP" above="DATA" below="\" /> <Key zoom={zoom} code={8} keyAction={handleClick} main="F" keyword="FOR" symbolWord="TO" above="SGN" below={"{"} /> <Key zoom={zoom} code={9} keyAction={handleClick} main="G" keyword="GOTO" symbolWord="THEN" above="ABS" below="}" /> <Key zoom={zoom} code={34} keyAction={handleClick} main="H" keyword="GOSUB" symbol={"\u2191"} above="SQR" below="CIRCLE" /> <Key zoom={zoom} code={33} keyAction={handleClick} main="J" keyword="LOAD" symbol={"\u2212"} above="VAL" below="VAL$" /> <Key zoom={zoom} code={32} keyAction={handleClick} main="K" keyword="LIST" symbol="+" above="LEN" below="SCREEN$" /> <Key zoom={zoom} code={31} keyAction={handleClick} main="L" keyword="LET" symbol="=" above="USR" below="ATTR" /> <Key zoom={zoom} code={30} keyAction={handleClick} center="ENTER" /> </KeyRow> <KeyRow> <Key zoom={zoom} code={0} keyAction={handleClick} xwidth={130} top="CAPS" bottom="SHIFT" /> <Key zoom={zoom} code={1} keyAction={handleClick} main="Z" keyword="COPY" symbol=":" above="LN" below="BEEP" /> <Key zoom={zoom} code={2} keyAction={handleClick} main="X" keyword="CLEAR" symbol={"\u00a3"} above="EXP" below="INK" /> <Key zoom={zoom} code={3} keyAction={handleClick} main="C" keyword="CONT" symbol="?" above="LPRINT" below="PAPER" /> <Key zoom={zoom} code={4} keyAction={handleClick} main="V" keyword="CLS" symbol="/" above="LLIST" below="FLASH" /> <Key zoom={zoom} code={39} keyAction={handleClick} main="B" keyword="BORDER" symbol="*" above="BIN" below="BRIGHT" /> <Key zoom={zoom} code={38} keyAction={handleClick} main="N" keyword="NEXT" symbol="," above="INKEY$" below="OVER" /> <Key zoom={zoom} code={37} keyAction={handleClick} main="M" keyword="PAUSE" symbol="." above="INVERSE" below="PI" /> <Key zoom={zoom} code={36} keyAction={handleClick} top="SYMBOL" bottom="SHIFT" useSymColor={true} /> <Key zoom={zoom} code={35} keyAction={handleClick} xwidth={180} top="BREAK" center="SPACE" /> </KeyRow> </Root> ); function handleClick(e: Sp48ButtonClickArgs): void { const vmEngineService = getVmEngineService(); if (!vmEngineService.hasEngine) { // --- No engine return; } const engine = vmEngineService.getEngine() as ZxSpectrumCoreBase; const frameCount = engine.getMachineState().frameCount; if (vmEngineService.getKeyQueueLength() > 0) { // --- Emulated keys are being played back return; } switch (e.keyCategory) { case "main": setKeyStatus(e.down, e.code, e.button === 0 ? undefined : 0 /* CShift */); break; case "symbol": setKeyStatus(e.down, e.code, 36 /* SShift */); break; case "above": if (e.down) { vmEngineService.queueKeyStroke( frameCount, 2, 0 /* CShift */, 36 /* SShift */ ); vmEngineService.queueKeyStroke( frameCount + 3, 2, e.code, e.button === 0 ? undefined : 0 /* CShift */ ); } break; case "below": if (e.down) { vmEngineService.queueKeyStroke( frameCount, 2, 0 /* CShift */, 36 /* SShift */ ); vmEngineService.queueKeyStroke( frameCount + 3, 2, e.code, 36 /* SShift */ ); } break; case "topNum": setKeyStatus(e.down, e.code, 0); break; case "glyph": if ((engine.getCursorMode() & 0x02) !== 0) return; if (e.down) { vmEngineService.queueKeyStroke( frameCount, 2, 21 /* N9 */, 0 /* CShift */ ); vmEngineService.queueKeyStroke( frameCount + 3, 2, e.code, e.button === 0 ? undefined : 0 /* CShift */ ); vmEngineService.queueKeyStroke( frameCount + 6, 2, 21 /* N9 */, 0 /* CShift */ ); } break; } /** * Sets the status of the specified keys * @param down Is pressed down? * @param primary Primary key * @param secondary Optional secondary key */ function setKeyStatus( down: boolean, primary: number, secondary?: number ): void { engine.setKeyStatus(primary, down); if (secondary !== undefined) { engine.setKeyStatus(secondary, down); } } }; function calculateZoom(width: number, height: number): number { if (!width || !height) return 0.05; let widthRatio = (width - 24) / DEFAULT_WIDTH; let heightRatio = (height - 32) / DEFAULT_HEIGHT; return Math.min(widthRatio, heightRatio); } } // --- Helper component tags const Root = styles.div` display: flex; flex-direction: column; flex-shrink: 0; flex-grow: 0; height: 100%; background-color: transparent; box-sizing: border-box; align-content: start; justify-items: start; justify-content: center; overflow: hidden; `; const KeyRow = styles.div` padding: 0px 0px; margin: 0; display: flex; flex-grow: 0; flex-shrink: 0; `;
the_stack
namespace pxsim.protocol { /** * Host for debug session that is responsible with communication with * the debugger's user interface. */ export interface DebugSessionHost { send(msg: string): void; onData(cb: (msg: DebugProtocol.ProtocolMessage) => void): void; onError(cb: (e?: any) => void): void; onClose(cb: () => void): void; close(): void; } export class Message implements DebugProtocol.ProtocolMessage { seq: number; type: string; public constructor(type: string) { this.seq = 0; this.type = type; } } export class Response extends Message implements DebugProtocol.Response { request_seq: number; success: boolean; command: string; public constructor(request: DebugProtocol.Request, message?: string) { super('response'); this.request_seq = request.seq; this.command = request.command; if (message) { this.success = false; (<any>this).message = message; } else { this.success = true; } } } export class Event extends Message implements DebugProtocol.Event { event: string; public constructor(event: string, body?: any) { super('event'); this.event = event; if (body) { (<any>this).body = body; } } } export class Source implements DebugProtocol.Source { name: string; path: string; sourceReference: number; public constructor(name: string, path: string, id: number = 0, origin?: string, data?: any) { this.name = name; this.path = path; this.sourceReference = id; if (origin) { (<any>this).origin = origin; } if (data) { (<any>this).adapterData = data; } } } export class Scope implements DebugProtocol.Scope { name: string; variablesReference: number; expensive: boolean; public constructor(name: string, reference: number, expensive: boolean = false) { this.name = name; this.variablesReference = reference; this.expensive = expensive; } } export class StackFrame implements DebugProtocol.StackFrame { id: number; source: Source; line: number; column: number; name: string; public constructor(i: number, nm: string, src?: Source, ln: number = 0, col: number = 0) { this.id = i; this.source = src; this.line = ln; this.column = col; this.name = nm; } } export class Thread implements DebugProtocol.Thread { id: number; name: string; public constructor(id: number, name: string) { this.id = id; if (name) { this.name = name; } else { this.name = 'Thread #' + id; } } } export class Variable implements DebugProtocol.Variable { name: string; value: string; variablesReference: number; public constructor(name: string, value: string, ref: number = 0, indexedVariables?: number, namedVariables?: number) { this.name = name; this.value = value; this.variablesReference = ref; if (typeof namedVariables === 'number') { (<DebugProtocol.Variable>this).namedVariables = namedVariables; } if (typeof indexedVariables === 'number') { (<DebugProtocol.Variable>this).indexedVariables = indexedVariables; } } } export class Breakpoint implements DebugProtocol.Breakpoint { verified: boolean; public constructor(verified: boolean, line?: number, column?: number, source?: Source) { this.verified = verified; const e: DebugProtocol.Breakpoint = this; if (typeof line === 'number') { e.line = line; } if (typeof column === 'number') { e.column = column; } if (source) { e.source = source; } } } export class Module implements DebugProtocol.Module { id: number | string; name: string; public constructor(id: number | string, name: string) { this.id = id; this.name = name; } } export class CompletionItem implements DebugProtocol.CompletionItem { label: string; start: number; length: number; public constructor(label: string, start: number, length: number = 0) { this.label = label; this.start = start; this.length = length; } } export class StoppedEvent extends Event implements DebugProtocol.StoppedEvent { body: { reason: string; threadId: number; }; public constructor(reason: string, threadId: number, exception_text: string = null) { super('stopped'); this.body = { reason: reason, threadId: threadId }; if (exception_text) { const e: DebugProtocol.StoppedEvent = this; e.body.text = exception_text; } } } export class ContinuedEvent extends Event implements DebugProtocol.ContinuedEvent { body: { threadId: number; }; public constructor(threadId: number, allThreadsContinued?: boolean) { super('continued'); this.body = { threadId: threadId }; if (typeof allThreadsContinued === 'boolean') { (<DebugProtocol.ContinuedEvent>this).body.allThreadsContinued = allThreadsContinued; } } } export class InitializedEvent extends Event implements DebugProtocol.InitializedEvent { public constructor() { super('initialized'); } } export class TerminatedEvent extends Event implements DebugProtocol.TerminatedEvent { public constructor(restart?: boolean) { super('terminated'); if (typeof restart === 'boolean') { const e: DebugProtocol.TerminatedEvent = this; e.body = { restart: restart }; } } } export class OutputEvent extends Event implements DebugProtocol.OutputEvent { body: { category: string, output: string, data?: any }; public constructor(output: string, category: string = 'console', data?: any) { super('output'); this.body = { category: category, output: output }; if (data !== undefined) { this.body.data = data; } } } export class ThreadEvent extends Event implements DebugProtocol.ThreadEvent { body: { reason: string, threadId: number }; public constructor(reason: string, threadId: number) { super('thread'); this.body = { reason: reason, threadId: threadId }; } } export class BreakpointEvent extends Event implements DebugProtocol.BreakpointEvent { body: { reason: string, breakpoint: Breakpoint }; public constructor(reason: string, breakpoint: Breakpoint) { super('breakpoint'); this.body = { reason: reason, breakpoint: breakpoint }; } } export class ModuleEvent extends Event implements DebugProtocol.ModuleEvent { body: { reason: 'new' | 'changed' | 'removed', module: Module }; public constructor(reason: 'new' | 'changed' | 'removed', module: Module) { super('module'); this.body = { reason: reason, module: module }; } } export class ProtocolServer { private host: DebugSessionHost; private _pendingRequests: { [index: number]: (response: DebugProtocol.Response) => void } = {}; private _sequence: number; public start(host: DebugSessionHost): void { this._sequence = 1; this.host = host; this.host.onData(msg => { if (msg.type === 'request') { this.dispatchRequest(<DebugProtocol.Request> msg); } else if (msg.type === 'response') { const response = <DebugProtocol.Response> msg; const clb = this._pendingRequests[response.seq]; if (clb) { delete this._pendingRequests[response.seq]; clb(response); } } }); } public stop(): void { if (this.host) { this.host.close(); } } public sendEvent(event: DebugProtocol.Event): void { this.send('event', event); } public sendResponse(response: DebugProtocol.Response): void { if (response.seq > 0) { console.error(`attempt to send more than one response for command ${response.command}`); } else { this.send('response', response); } } public sendRequest(command: string, args: any, timeout: number, cb: (response: DebugProtocol.Response) => void): void { const request: any = { command: command }; if (args && Object.keys(args).length > 0) { request.arguments = args; } this.send('request', request); if (cb) { this._pendingRequests[request.seq] = cb; const timer = setTimeout(() => { clearTimeout(timer); const clb = this._pendingRequests[request.seq]; if (clb) { delete this._pendingRequests[request.seq]; clb(new protocol.Response(request, 'timeout')); } }, timeout); } } private send(typ: 'request' | 'response' | 'event', message: DebugProtocol.ProtocolMessage) { message.type = typ; message.seq = this._sequence++; if (this.host) { const json = JSON.stringify(message); this.host.send(json); } } // ---- protected ---------------------------------------------------------- protected dispatchRequest(request: DebugProtocol.Request): void { } } export class DebugSession extends ProtocolServer { private _debuggerLinesStartAt1: boolean = false; private _debuggerColumnsStartAt1: boolean = false; private _debuggerPathsAreURIs: boolean; private _clientLinesStartAt1: boolean = true; private _clientColumnsStartAt1: boolean = true; private _clientPathsAreURIs: boolean; private _isServer: boolean; public shutdown(): void { } protected dispatchRequest(request: DebugProtocol.Request): void { const response = new protocol.Response(request); try { if (request.command === 'initialize') { let args = <DebugProtocol.InitializeRequestArguments> request.arguments; if (typeof args.linesStartAt1 === 'boolean') { this._clientLinesStartAt1 = args.linesStartAt1; } if (typeof args.columnsStartAt1 === 'boolean') { this._clientColumnsStartAt1 = args.columnsStartAt1; } if (args.pathFormat !== 'path') { this.sendErrorResponse(response, 2018, 'debug adapter only supports native paths', null); } else { const initializeResponse = <DebugProtocol.InitializeResponse> response; initializeResponse.body = {}; this.initializeRequest(initializeResponse, args); } } else if (request.command === 'launch') { this.launchRequest(<DebugProtocol.LaunchResponse> response, request.arguments); } else if (request.command === 'attach') { this.attachRequest(<DebugProtocol.AttachResponse> response, request.arguments); } else if (request.command === 'disconnect') { this.disconnectRequest(<DebugProtocol.DisconnectResponse> response, request.arguments); } else if (request.command === 'setBreakpoints') { this.setBreakPointsRequest(<DebugProtocol.SetBreakpointsResponse> response, request.arguments); } else if (request.command === 'setFunctionBreakpoints') { this.setFunctionBreakPointsRequest(<DebugProtocol.SetFunctionBreakpointsResponse> response, request.arguments); } else if (request.command === 'setExceptionBreakpoints') { this.setExceptionBreakPointsRequest(<DebugProtocol.SetExceptionBreakpointsResponse> response, request.arguments); } else if (request.command === 'configurationDone') { this.configurationDoneRequest(<DebugProtocol.ConfigurationDoneResponse> response, request.arguments); } else if (request.command === 'continue') { this.continueRequest(<DebugProtocol.ContinueResponse> response, request.arguments); } else if (request.command === 'next') { this.nextRequest(<DebugProtocol.NextResponse> response, request.arguments); } else if (request.command === 'stepIn') { this.stepInRequest(<DebugProtocol.StepInResponse> response, request.arguments); } else if (request.command === 'stepOut') { this.stepOutRequest(<DebugProtocol.StepOutResponse> response, request.arguments); } else if (request.command === 'stepBack') { this.stepBackRequest(<DebugProtocol.StepBackResponse> response, request.arguments); } else if (request.command === 'restartFrame') { this.restartFrameRequest(<DebugProtocol.RestartFrameResponse> response, request.arguments); } else if (request.command === 'goto') { this.gotoRequest(<DebugProtocol.GotoResponse> response, request.arguments); } else if (request.command === 'pause') { this.pauseRequest(<DebugProtocol.PauseResponse> response, request.arguments); } else if (request.command === 'stackTrace') { this.stackTraceRequest(<DebugProtocol.StackTraceResponse> response, request.arguments); } else if (request.command === 'scopes') { this.scopesRequest(<DebugProtocol.ScopesResponse> response, request.arguments); } else if (request.command === 'variables') { this.variablesRequest(<DebugProtocol.VariablesResponse> response, request.arguments); } else if (request.command === 'setVariable') { this.setVariableRequest(<DebugProtocol.SetVariableResponse> response, request.arguments); } else if (request.command === 'source') { this.sourceRequest(<DebugProtocol.SourceResponse> response, request.arguments); } else if (request.command === 'threads') { this.threadsRequest(<DebugProtocol.ThreadsResponse> response); } else if (request.command === 'evaluate') { this.evaluateRequest(<DebugProtocol.EvaluateResponse> response, request.arguments); } else if (request.command === 'stepInTargets') { this.stepInTargetsRequest(<DebugProtocol.StepInTargetsResponse> response, request.arguments); } else if (request.command === 'gotoTargets') { this.gotoTargetsRequest(<DebugProtocol.GotoTargetsResponse> response, request.arguments); } else if (request.command === 'completions') { this.completionsRequest(<DebugProtocol.CompletionsResponse> response, request.arguments); } else { this.customRequest(request.command, <DebugProtocol.Response> response, request.arguments); } } catch (e) { this.sendErrorResponse(response, 1104, '{_stack}', { _exception: e.message, _stack: e.stack }); } } protected initializeRequest(response: DebugProtocol.InitializeResponse, args: DebugProtocol.InitializeRequestArguments): void { // This default debug adapter does not support conditional breakpoints. response.body.supportsConditionalBreakpoints = false; // This default debug adapter does not support hit conditional breakpoints. response.body.supportsHitConditionalBreakpoints = false; // This default debug adapter does not support function breakpoints. response.body.supportsFunctionBreakpoints = false; // This default debug adapter implements the 'configurationDone' request. response.body.supportsConfigurationDoneRequest = true; // This default debug adapter does not support hovers based on the 'evaluate' request. response.body.supportsEvaluateForHovers = false; // This default debug adapter does not support the 'stepBack' request. response.body.supportsStepBack = false; // This default debug adapter does not support the 'setVariable' request. response.body.supportsSetVariable = false; // This default debug adapter does not support the 'restartFrame' request. response.body.supportsRestartFrame = false; // This default debug adapter does not support the 'stepInTargetsRequest' request. response.body.supportsStepInTargetsRequest = false; // This default debug adapter does not support the 'gotoTargetsRequest' request. response.body.supportsGotoTargetsRequest = false; // This default debug adapter does not support the 'completionsRequest' request. response.body.supportsCompletionsRequest = false; this.sendResponse(response); } protected disconnectRequest(response: DebugProtocol.DisconnectResponse, args: DebugProtocol.DisconnectArguments): void { this.sendResponse(response); this.shutdown(); } protected launchRequest(response: DebugProtocol.LaunchResponse, args: DebugProtocol.LaunchRequestArguments): void { this.sendResponse(response); } protected attachRequest(response: DebugProtocol.AttachResponse, args: DebugProtocol.AttachRequestArguments): void { this.sendResponse(response); } protected setBreakPointsRequest(response: DebugProtocol.SetBreakpointsResponse, args: DebugProtocol.SetBreakpointsArguments): void { this.sendResponse(response); } protected setFunctionBreakPointsRequest(response: DebugProtocol.SetFunctionBreakpointsResponse, args: DebugProtocol.SetFunctionBreakpointsArguments): void { this.sendResponse(response); } protected setExceptionBreakPointsRequest(response: DebugProtocol.SetExceptionBreakpointsResponse, args: DebugProtocol.SetExceptionBreakpointsArguments): void { this.sendResponse(response); } protected configurationDoneRequest(response: DebugProtocol.ConfigurationDoneResponse, args: DebugProtocol.ConfigurationDoneArguments): void { this.sendResponse(response); } protected continueRequest(response: DebugProtocol.ContinueResponse, args: DebugProtocol.ContinueArguments): void { this.sendResponse(response); } protected nextRequest(response: DebugProtocol.NextResponse, args: DebugProtocol.NextArguments): void { this.sendResponse(response); } protected stepInRequest(response: DebugProtocol.StepInResponse, args: DebugProtocol.StepInArguments): void { this.sendResponse(response); } protected stepOutRequest(response: DebugProtocol.StepOutResponse, args: DebugProtocol.StepOutArguments): void { this.sendResponse(response); } protected stepBackRequest(response: DebugProtocol.StepBackResponse, args: DebugProtocol.StepBackArguments): void { this.sendResponse(response); } protected restartFrameRequest(response: DebugProtocol.RestartFrameResponse, args: DebugProtocol.RestartFrameArguments): void { this.sendResponse(response); } protected gotoRequest(response: DebugProtocol.GotoResponse, args: DebugProtocol.GotoArguments): void { this.sendResponse(response); } protected pauseRequest(response: DebugProtocol.PauseResponse, args: DebugProtocol.PauseArguments): void { this.sendResponse(response); } protected sourceRequest(response: DebugProtocol.SourceResponse, args: DebugProtocol.SourceArguments): void { this.sendResponse(response); } protected threadsRequest(response: DebugProtocol.ThreadsResponse): void { this.sendResponse(response); } protected stackTraceRequest(response: DebugProtocol.StackTraceResponse, args: DebugProtocol.StackTraceArguments): void { this.sendResponse(response); } protected scopesRequest(response: DebugProtocol.ScopesResponse, args: DebugProtocol.ScopesArguments): void { this.sendResponse(response); } protected variablesRequest(response: DebugProtocol.VariablesResponse, args: DebugProtocol.VariablesArguments): void { this.sendResponse(response); } protected setVariableRequest(response: DebugProtocol.SetVariableResponse, args: DebugProtocol.SetVariableArguments): void { this.sendResponse(response); } protected evaluateRequest(response: DebugProtocol.EvaluateResponse, args: DebugProtocol.EvaluateArguments): void { this.sendResponse(response); } protected stepInTargetsRequest(response: DebugProtocol.StepInTargetsResponse, args: DebugProtocol.StepInTargetsArguments): void { this.sendResponse(response); } protected gotoTargetsRequest(response: DebugProtocol.GotoTargetsResponse, args: DebugProtocol.GotoTargetsArguments): void { this.sendResponse(response); } protected completionsRequest(response: DebugProtocol.CompletionsResponse, args: DebugProtocol.CompletionsArguments): void { this.sendResponse(response); } /** * Override this hook to implement custom requests. */ protected customRequest(command: string, response: DebugProtocol.Response, args: any): void { this.sendErrorResponse(response, 1014, 'unrecognized request', null); } protected sendErrorResponse(response: DebugProtocol.Response, codeOrMessage: number | DebugProtocol.Message, format?: string, variables?: any): void { let msg: DebugProtocol.Message; if (typeof codeOrMessage === 'number') { msg = <DebugProtocol.Message> { id: <number> codeOrMessage, format: format }; if (variables) { msg.variables = variables; } msg.showUser = true; } else { msg = codeOrMessage; } response.success = false; DebugSession.formatPII(msg.format, true, msg.variables); if (!response.body) { response.body = { }; } response.body.error = msg; this.sendResponse(response); } protected convertClientLineToDebugger(line: number): number { if (this._debuggerLinesStartAt1) { return this._clientLinesStartAt1 ? line : line + 1; } return this._clientLinesStartAt1 ? line - 1 : line; } protected convertDebuggerLineToClient(line: number): number { if (this._debuggerLinesStartAt1) { return this._clientLinesStartAt1 ? line : line - 1; } return this._clientLinesStartAt1 ? line + 1 : line; } protected convertClientColumnToDebugger(column: number): number { if (this._debuggerColumnsStartAt1) { return this._clientColumnsStartAt1 ? column : column + 1; } return this._clientColumnsStartAt1 ? column - 1 : column; } protected convertDebuggerColumnToClient(column: number): number { if (this._debuggerColumnsStartAt1) { return this._clientColumnsStartAt1 ? column : column - 1; } return this._clientColumnsStartAt1 ? column + 1 : column; } protected convertClientPathToDebugger(clientPath: string): string { if (this._clientPathsAreURIs != this._debuggerPathsAreURIs) { if (this._clientPathsAreURIs) { return DebugSession.uri2path(clientPath); } else { return DebugSession.path2uri(clientPath); } } return clientPath; } protected convertDebuggerPathToClient(debuggerPath: string): string { if (this._debuggerPathsAreURIs != this._clientPathsAreURIs) { if (this._debuggerPathsAreURIs) { return DebugSession.uri2path(debuggerPath); } else { return DebugSession.path2uri(debuggerPath); } } return debuggerPath; } private static path2uri(str: string): string { let pathName = str.replace(/\\/g, '/'); if (pathName[0] !== '/') { pathName = '/' + pathName; } return encodeURI('file://' + pathName); } private static uri2path(url: string): string { return url; //return Url.parse(url).pathname; } private static _formatPIIRegexp = /{([^}]+)}/g; /* * If argument starts with '_' it is OK to send its value to telemetry. */ private static formatPII(format: string, excludePII: boolean, args: { [key: string]: string }): string { return format.replace(DebugSession._formatPIIRegexp, function(match, paramName) { if (excludePII && paramName.length > 0 && paramName[0] !== '_') { return match; } return args[paramName] && args.hasOwnProperty(paramName) ? args[paramName] : match; }) } } }
the_stack
import { Response } from 'node-fetch'; import { IResult } from '../../models/http-result'; import * as path from 'path'; import * as fs from 'fs'; export class Utils { private static readonly LOG_FILE_PATH = '../../../log.txt'; private static writeStream = fs.createWriteStream(path.resolve(__dirname, Utils.LOG_FILE_PATH), {flags: 'a'}); public static getPostsOfHashtagGraphQL(data: object) { if (data && data['graphql']) { return data['graphql']['hashtag']['edge_hashtag_to_media']['edges']; } else { return []; } } public static getPostGraphQL(data: object) { if (data && data['graphql'] && data['graphql']['shortcode_media']) { return data['graphql']['shortcode_media']; } else { return []; } } public static getResult<T>(response: Response, data?: T): IResult<T> { return { status: response.status, success: response.ok, data: data ? data : null, }; } /** * Returns a random number between min (inclusive) and max (exclusive) */ public static getRandomArbitrary(min, max) { return Math.random() * (max - min) + min; } /** * Returns a random integer between min (inclusive) and max (inclusive) * Using Math.round() will give you a non-uniform distribution! */ public static getRandomInt(min: number, max: number) { return Math.floor(Math.random() * (max - min + 1)) + min; } /** * Returns a random integer between min (inclusive) and max (inclusive) * Using Math.round() will give you a non-uniform distribution! * @returns a number between 67secs - 34secs (67000 - 34000) */ public static getDefaultRandom() { return Utils.getRandomInt(34, 67) * 1000; } public static getDateString(time: Date): string { return time.toLocaleDateString('en', { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', hour12: false, }); /*return `${time.getDate()}/${time.getMonth() + 1}/${time.getFullYear()} - ${time.getHours()}:${time.getMinutes()} o'clock`;*/ } public static getTimeString(time: Date): string { return time.toLocaleTimeString('en', { hour: 'numeric', minute: 'numeric', second: 'numeric', hour12: false, }); } public static writeLog( message: string, prefix?: string, ) { if (!prefix) { prefix = 'Log'; } const logMessage = `${Utils.getTimeString(new Date(Date.now()))} -> ${prefix}: ${message.toString()}`; console.log(logMessage); Utils.writeStream.write(logMessage+ '\r\n'); } public static writeProgress(message: string) { process.stdout.write(`${message} \r`); } public static getShutdownMessage(reason?: string): string { return `Bot is shutting down due to error, your need to restart him. \r\n${ reason ? 'Reason: ' + reason : '' }`; } public static writeShutdown(reason?: string) { console.log(Utils.getShutdownMessage(reason)); } public static writeLogError(error: any, prefix?: string) { if (!prefix) { prefix = 'ErrorLogger'; } if (error && Object.keys(error).length > 0) { // is object error if (error.statusMessage) { console.log(prefix, ':', error.statusMessage); } else if (error.message) { console.log(prefix, ':', error.message); } } else { console.log(prefix, ':', error); } } public static sleep(ms: number = Utils.getDefaultRandom(), prefix?: string) { /*if (prefix) { Utils.writeLog(`Sleeping for ${ms / 1000}s`, prefix); }*/ return new Promise(resolve => setTimeout(resolve, Number(ms.toFixed(0)))); } public static quickSleep() { const ms = Utils.getRandomInt(6, 17); return new Promise(resolve => setTimeout(resolve, Number(ms.toFixed(0)))); } public static sleepSecs(s: number) { return new Promise(resolve => setTimeout(resolve, Number((s * 1000).toFixed(0))), ); } public static getFakeUserAgent(): string { const UAs = [ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.1.1 Safari/603.2.4', 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0', 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36', 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:53.0) Gecko/20100101 Firefox/53.0', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:53.0) Gecko/20100101 Firefox/53.0', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.1 Safari/603.1.30', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:53.0) Gecko/20100101 Firefox/53.0', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:53.0) Gecko/20100101 Firefox/53.0', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; rv:53.0) Gecko/20100101 Firefox/53.0', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/603.2.5 (KHTML, like Gecko) Version/10.1.1 Safari/603.2.5', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/58.0.3029.110 Chrome/58.0.3029.110 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0', 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36 Edge/15.15063', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36', 'Mozilla/5.0 (X11; Linux x86_64; rv:53.0) Gecko/20100101 Firefox/53.0', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 OPR/45.0.2552.888', 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:53.0) Gecko/20100101 Firefox/53.0', 'Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/603.2.5 (KHTML, like Gecko) Version/10.1.1 Safari/603.2.5', 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36', 'Mozilla/5.0 (iPad; CPU OS 10_3_2 like Mac OS X) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.0 Mobile/14F89 Safari/602.1', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0', 'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36', 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/602.4.8 (KHTML, like Gecko) Version/10.0.3 Safari/602.4.8', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36 OPR/45.0.2552.812', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36', 'Mozilla/5.0 (Windows NT 5.1; rv:52.0) Gecko/20100101 Firefox/52.0', 'Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0', 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:54.0) Gecko/20100101 Firefox/54.0', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:53.0) Gecko/20100101 Firefox/53.0', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36', 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/5.0; Trident/5.0)', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0', 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; Trident/5.0)', 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:54.0) Gecko/20100101 Firefox/54.0', 'Mozilla/5.0 (iPad; CPU OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1', 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36', 'Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:53.0) Gecko/20100101 Firefox/53.0', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/601.7.7 (KHTML, like Gecko) Version/9.1.2 Safari/601.7.7', 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko', 'Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko', ]; return UAs[Utils.getRandomInt(0, UAs.length - 1)]; } }
the_stack
'use strict'; import {DebugSession, InitializedEvent, TerminatedEvent, StoppedEvent, BreakpointEvent, OutputEvent, Thread, StackFrame, Scope, Source, Handles, Breakpoint} from 'vscode-debugadapter'; import {DebugProtocol} from 'vscode-debugprotocol'; import {readFileSync} from 'fs'; import {basename, dirname} from 'path'; import * as net from 'net'; import * as childProcess from 'child_process'; import * as path from 'path'; import {DOMParser} from 'xmldom'; import {RubyProcess} from './ruby'; import {LaunchRequestArguments, AttachRequestArguments, IRubyEvaluationResult, IDebugVariable} from './interface'; import {SocketClientState, Mode} from './common'; import {endsWith, startsWith} from './helper'; class RubyDebugSession extends DebugSession { private _breakpointId = 1000; private _threadId = 2; private _frameId = 0; private _firstSuspendReceived = false; private _activeFileData = new Map<string, string[]>(); // maps from sourceFile to array of Breakpoints private _breakPoints = new Map<string, DebugProtocol.Breakpoint[]>(); private _variableHandles: Handles<IDebugVariable>; private rubyProcess: RubyProcess; private requestArguments: any; private debugMode: Mode; /** * Creates a new debug adapter. * We configure the default implementation of a debug adapter here * by specifying this this 'debugger' uses zero-based lines and columns. */ public constructor() { super(); this.setDebuggerLinesStartAt1(true); this.setDebuggerColumnsStartAt1(false); this._variableHandles = new Handles<IDebugVariable>(); } /** * The 'initialize' request is the first request called by the frontend * to interrogate the features the debug adapter provides. */ protected initializeRequest(response: DebugProtocol.InitializeResponse, args: DebugProtocol.InitializeRequestArguments): void { // This debug adapter implements the configurationDoneRequest. response.body.supportsConfigurationDoneRequest = true; //response.body.supportsFunctionBreakpoints = true; //currently cond bp doesn't work - but that doesn't really matter, because neither does this call response.body.supportsConditionalBreakpoints = false; this.sendResponse(response); } protected setupProcessHanlders() { this.rubyProcess.on('debuggerComplete', () => { this.sendEvent(new TerminatedEvent()); }).on('executableOutput', (data: Buffer) => { this.sendEvent(new OutputEvent(data.toString(), 'stdout')); }).on('executableStdErr', (error: Buffer) => { this.sendEvent(new OutputEvent(error.toString(), 'stderr')); }).on('nonTerminalError', (error: string) => { this.sendEvent(new OutputEvent("Debugger error: " + error + '\n', 'stderr')); }).on('breakpoint', result => { this.sendEvent(new StoppedEvent('breakpoint', result.threadId)); }).on('exception', result => { this.sendEvent(new OutputEvent("\nException raised: [" + result.type + "]: " + result.message + "\n",'stderr')); this.sendEvent(new StoppedEvent('exception', result.threadId, result.type + ": " + result.message)); }).on('terminalError', (error: string) => { this.sendEvent(new OutputEvent("Debugger terminal error: " + error)) this.sendEvent(new TerminatedEvent()); }); } protected launchRequest(response: DebugProtocol.LaunchResponse, args: LaunchRequestArguments): void { this.debugMode = Mode.launch; this.requestArguments = args; this.rubyProcess = new RubyProcess(Mode.launch, args); this.rubyProcess.on('debuggerConnect', () => { this.sendEvent(new InitializedEvent()); this.sendResponse(response); }).on('suspended', result => { if ( args.stopOnEntry && !this._firstSuspendReceived ) { this.sendEvent(new StoppedEvent('entry', result.threadId)); } else { this.sendEvent(new StoppedEvent('step', result.threadId)); } this._firstSuspendReceived = true; }); this.setupProcessHanlders(); if (args.showDebuggerOutput) { this.rubyProcess.on('debuggerOutput', (data: Buffer) => { this.sendEvent(new OutputEvent(data.toString() + '\n', 'console')); }); } } protected attachRequest(response: DebugProtocol.AttachResponse, args: AttachRequestArguments): void { this.requestArguments = args; this.debugMode = Mode.attach; this.rubyProcess = new RubyProcess(Mode.attach, args); this.rubyProcess.on('debuggerConnect', () => { this.sendEvent(new InitializedEvent()); this.sendResponse(response); }).on('suspended', result => { this.sendEvent(new StoppedEvent('step', result.threadId)); }); this.setupProcessHanlders(); } // Executed after all breakpints have been set by VS Code protected configurationDoneRequest(response: DebugProtocol.ConfigurationDoneResponse, args: DebugProtocol.ConfigurationDoneArguments): void { this.rubyProcess.Run('start'); this.sendResponse(response); } protected setExceptionBreakPointsRequest(response: DebugProtocol.SetExceptionBreakpointsResponse, args: DebugProtocol.SetExceptionBreakpointsArguments): void { if (args.filters.indexOf('all') >=0){ //Exception is the root of all (Ruby) exceptions - this is the best we can do //If someone makes their own exception class and doesn't inherit from //Exception, then they really didn't expect things to work properly //anyway. //We don't do anything with the return from this, but we //have to add an expectation for the output. this.rubyProcess.Enqueue('catch Exception').then(()=>1); } else { this.rubyProcess.Run('catch off'); } this.sendResponse(response); } protected setBreakPointsRequest(response: DebugProtocol.SetBreakpointsResponse, args: DebugProtocol.SetBreakpointsArguments): void { var path = this.convertClientPathToDebugger(args.source.path); //to ensure that breakpoints with altered conditions are set, it is //best to remove all and add them back. //In preperation for when they're working. if (this._breakPoints.get(path)) { let deletePromises = this._breakPoints.get(path).map(bp => this.rubyProcess.Enqueue('delete ' + bp.id)); //this will return before the adding (if any) completes Promise.all(deletePromises).then(() => this._breakPoints.delete(path)); } var breakpointAddPromises = args.breakpoints.map(b=>{ //let conditionString = b.condition ? ' if ' + b.condition : ''; //return this.rubyProcess.Enqueue('break ' + path + ':' + b.line + conditionString); return this.rubyProcess.Enqueue('break ' + path + ':' + b.line); }); Promise.all(breakpointAddPromises).then( values => { let breakpoints = values.map(attributes => { let bp = <DebugProtocol.Breakpoint> new Breakpoint(true, this.convertDebuggerLineToClient(+attributes.location.split(':')[1])); bp.id = +attributes.no; return bp; }); this._breakPoints.set(path, breakpoints); response.body = { breakpoints: breakpoints }; this.sendResponse(response); }); } protected threadsRequest(response: DebugProtocol.ThreadsResponse): void { this.rubyProcess.Enqueue('thread list').then(results => { this._threadId = results[0].id; response.body = { threads: results.map(thread => new Thread(+thread.id,'Thread ' + thread.id)) }; this.sendResponse(response); }); } // Called by VS Code after a StoppedEvent /** StackTrace request; value of command field is 'stackTrace'. The request returns a stacktrace from the current execution state. */ protected stackTraceRequest(response: DebugProtocol.StackTraceResponse, args: DebugProtocol.StackTraceArguments): void { this.rubyProcess.Enqueue('where').then(results => { //drop rdbug frames results = results.filter(stack => !( endsWith(stack.file, '/rdebug-ide', null) || endsWith(stack.file, '/ruby-debug-ide.rb', null) || (this.debugMode == Mode.attach && path.normalize(stack.file).toLocaleLowerCase().indexOf(path.normalize(this.requestArguments.remoteWorkspaceRoot).toLocaleLowerCase()) === -1)) ); //get the current frame results.some(stack=> stack.current ? this._frameId = +stack.no: 0); //only read the file if we don't have it already results.forEach(stack=>{ if (!this._activeFileData.has(this.convertDebuggerPathToClient(stack.file))) { this._activeFileData.set(this.convertDebuggerPathToClient(stack.file), readFileSync(this.convertDebuggerPathToClient(stack.file),'utf8').split('\n')) } }); response.body = { stackFrames: results.filter(stack=>stack.file.indexOf('debug-ide')<0) .map(stack => new StackFrame(+stack.no, this._activeFileData.get(this.convertDebuggerPathToClient(stack.file))[+stack.line-1].trim(), new Source(basename(stack.file), this.convertDebuggerPathToClient(stack.file)), this.convertDebuggerLineToClient(+stack.line), 0)) }; if (response.body.stackFrames.length){ this.sendResponse(response); } else { this.sendEvent(new TerminatedEvent()); } return; }); } protected convertClientPathToDebugger(localPath: string): string { if (this.debugMode == Mode.launch) { return localPath; } var relativePath = path.join( this.requestArguments.remoteWorkspaceRoot, localPath.substring(this.requestArguments.cwd.length) ); var sepIndex = this.requestArguments.remoteWorkspaceRoot.lastIndexOf('/'); if (sepIndex !== -1) { // *inx or darwin relativePath = relativePath.replace(/\\/g, '/'); } return relativePath; } protected convertDebuggerPathToClient(serverPath: string):string{ if (this.debugMode == Mode.launch) { return serverPath; } // Path.join will convert the path using local OS preferred separator var relativePath = path.join( this.requestArguments.cwd, serverPath.substring(this.requestArguments.remoteWorkspaceRoot.length) ); return relativePath; } protected switchFrame(frameId) { if (frameId === this._frameId) return; this._frameId = frameId; this.rubyProcess.Run('frame ' + frameId) } protected varyVariable(variable){ if (variable.type === 'String') { variable.hasChildren = false; variable.value = "'" + variable.value.replace(/'/g,"\\'") + "'"; } else if ( variable.value && startsWith(variable.value, '#<' + variable.type, 0)){ variable.value = variable.type; } return variable; } protected createVariableReference(variables): IRubyEvaluationResult[]{ return variables.map(this.varyVariable).map(variable=>({ name: variable.name, kind: variable.kind, type: variable.type, value: variable.value === undefined ? 'undefined' : variable.value, id: variable.objectId, variablesReference: variable.hasChildren === 'true' ? this._variableHandles.create({objectId:variable.objectId}):0 })); } /** Scopes request; value of command field is 'scopes'. The request returns the variable scopes for a given stackframe ID. */ protected scopesRequest(response: DebugProtocol.ScopesResponse, args: DebugProtocol.ScopesArguments): void { //this doesn't work properly across threads. this.switchFrame(args.frameId); Promise.all([ this.rubyProcess.Enqueue('var local'), this.rubyProcess.Enqueue('var global') ]) .then( results =>{ const scopes = new Array<Scope>(); scopes.push(new Scope('Local',this._variableHandles.create({variables:this.createVariableReference(results[0])}),false)); scopes.push(new Scope('Global',this._variableHandles.create({variables:this.createVariableReference(results[1])}),false)); response.body = { scopes: scopes }; this.sendResponse(response); }); } protected variablesRequest(response: DebugProtocol.VariablesResponse, args: DebugProtocol.VariablesArguments): void { var varRef = this._variableHandles.get(args.variablesReference); let varPromise; if ( varRef.objectId ){ varPromise = this.rubyProcess.Enqueue('var i ' + varRef.objectId).then(results => this.createVariableReference(results)); } else { varPromise = Promise.resolve(varRef.variables); } varPromise.then(variables =>{ response.body = { variables: variables }; this.sendResponse(response); }); } protected continueRequest(response: DebugProtocol.ContinueResponse, args: DebugProtocol.ContinueArguments): void { this.sendResponse(response); this.rubyProcess.Run('c'); } protected nextRequest(response: DebugProtocol.NextResponse, args: DebugProtocol.NextArguments): void { this.sendResponse(response); this.rubyProcess.Run('next'); } protected stepInRequest(response: DebugProtocol.StepInResponse): void { this.sendResponse(response); this.rubyProcess.Run('step'); } protected pauseRequest(response: DebugProtocol.PauseResponse): void{ this.sendResponse(response); this.rubyProcess.Run('pause'); } protected stepOutRequest(response: DebugProtocol.StepInResponse): void { this.sendResponse(response); //Not sure which command we should use, `finish` will execute all frames. this.rubyProcess.Run('finish'); } /** Evaluate request; value of command field is 'evaluate'. Evaluates the given expression in the context of the top most stack frame. The expression has access to any variables and arguments this are in scope. */ protected evaluateRequest(response: DebugProtocol.EvaluateResponse, args: DebugProtocol.EvaluateArguments): void { // TODO: this will often not work. Will try to call // Class.@variable which doesn't work. // need to tie it to the existing variablesReference set // That will required having ALL variables stored, which will also (hopefully) fix // the variable value mismatch between threads this.rubyProcess.Enqueue("eval " + args.expression).then(result => { if ( startsWith(result.value, '#<', 0)){ //is an object } response.body = { result: result.value, variablesReference: 0 }; this.sendResponse(response); }); } protected disconnectRequest(response: DebugProtocol.DisconnectResponse, args: DebugProtocol.DisconnectArguments) { if (this.rubyProcess.state !== SocketClientState.closed) { this.rubyProcess.Run('quit'); } this.sendResponse(response); } } DebugSession.run(RubyDebugSession);
the_stack
import { CreateOptionsRes } from '../core/components/formTypes'; import { IBlockType, IStoreData } from '../core/store/storetype'; import { CSSProperties, PropsWithChildren, useEffect, useMemo, useState } from 'react'; import React from 'react'; import { Tabs, Input, Row, Col, Checkbox, InputNumber } from 'antd'; import UserConfig from '../config'; import { RGBColor, SketchPicker } from 'react-color'; import { rgba2Obj } from '../core/utils'; import deepcopy from 'deepcopy'; import { replaceLocale } from '../locale'; const colStyle: CSSProperties = { display: 'flex', alignItems: 'center', justifyContent: 'flex-end', }; interface RightConfigProps { state: IStoreData; config: UserConfig; } /** * * 这里一个需要异步拿取当前注册组件的配置项,另外需要异步加载所需的配置项。 * @param {*} props * @returns */ function RightConfig(props: PropsWithChildren<RightConfigProps>) { const [menuSelect, setMenuSelect] = useState('0'); const [current, setCurrent] = useState<IBlockType | null>(null); const rightMapRenderListCategory = useMemo(() => { return props.config.getConfig().rightRenderListCategory; }, [props.config]); const store = props.config.getStore(); useEffect(() => { const fn = () => { let item: IBlockType | undefined; store.getData().block.some((v) => { if (v.focus) { item = v; } return v.focus === true; }); if (item) { setCurrent({ ...item }); } else { setCurrent(null); } }; const unregist = store.subscribe(fn); return () => { unregist(); }; }, [store]); const render = useMemo(() => { return (type: string, current: IBlockType) => { const fn = () => props.config.getComponentRegister().getComp(current.name); const data = fn(); // 这里不可能拿不到组件,因为点击的那个组件已经渲染出来了 if (data) { const renderList = data.props[type]; if (renderList) { return renderList.map((v, i) => { const Component = props.config.getFormRegister().formMap[v.type]; if (!Component) { console.error(`you might forgot to regist form component ${v.type}`); return null; } return ( <Component key={i} data={v as CreateOptionsRes<any, any>} current={current} config={props.config} ></Component> ); }); } else { return <div>{replaceLocale('right.noprops', '还没有配置属性', props.config)}</div>; } } return null; }; }, [props.config]); const initColor = useMemo(() => { return props.config.getStoreChanger().isEdit() ? rgba2Obj(props.config.getStoreChanger().getOrigin()?.now.globalState.containerColor) : rgba2Obj(props.config.getStore().getData().globalState.containerColor); }, [props.config]); const initColor2 = useMemo(() => { return props.config.getStoreChanger().isEdit() ? rgba2Obj(props.config.getStoreChanger().getOrigin()?.now.globalState.bodyColor) : rgba2Obj(props.config.getStore().getData().globalState.bodyColor); }, [props.config]); const [color, setColor] = useState<RGBColor>(initColor); const [color2, setColor2] = useState<RGBColor>(initColor2); const [colorPickerVisible, setColorPickerVisible] = useState(false); const [colorPickerVisible2, setColorPickerVisible2] = useState(false); const initTitle = useMemo(() => { const title = props.config.getStoreChanger().isEdit() ? props.config.getStoreChanger().getOrigin()?.now.globalState.title : props.config.getStore().getData().globalState.title; return title; }, [props.config]); const [title, setTitle] = useState(initTitle); const customGlobal = props.config.getConfig().rightGlobalCustom; const isEdit = props.config.getStoreChanger().isEdit(); const modalName = props.config.getStoreChanger().getState().modalEditName; const originData = props.config.getStoreChanger().getOrigin()?.now; return ( <div className="ant-menu" style={{ height: '100%', width: '400px', overflow: 'auto', padding: '0 10px', lineHeight: 1.5715, }} > {current && ( <Tabs activeKey={menuSelect} style={{ width: '100%' }} onChange={(e) => { setMenuSelect(e); }} > {rightMapRenderListCategory.map((v, i) => { return ( <Tabs.TabPane tab={v.icon} key={i + ''}> <div className="scrollbar" style={{ height: 'calc(100vh - 110px)', overflow: 'auto', }} > {v.custom && v.customRender && v.customRender(v.type, current)} {!v.custom && render(v.type, current)} </div> </Tabs.TabPane> ); })} </Tabs> )} {!current && !isEdit && !customGlobal && ( <div style={{ padding: '20px' }}> <Row style={{ padding: '10px 0 20px 0', fontWeight: 'bold', userSelect: 'none' }}> {replaceLocale('right.global', '全局设置', props.config)} </Row> <Row style={{ padding: '10px 0' }}> <Col span={6} style={{ userSelect: 'none' }}> {replaceLocale('title', '标题', props.config)} </Col> <Col span={18} style={colStyle}> <Input value={title} onChange={(e) => { const val = e.target.value; setTitle(val); const isEdit = props.config.getStoreChanger().isEdit(); if (isEdit) { const originData: IStoreData = deepcopy( props.config.getStoreChanger().getOrigin()!.now ); originData.globalState.title = val; props.config.getStoreChanger().updateOrigin(originData); } else { const originData = deepcopy(props.config.getStore().getData()); originData.globalState.title = val; props.config.getStore().setData(originData); } }} /> </Col> </Row> <Row style={{ padding: '10px 0' }}> <Col span={6} style={{ userSelect: 'none' }}> {replaceLocale('right.containerheight', '容器高度', props.config)} </Col> <Col span={18} style={colStyle}> <InputNumber min={0} value={props.config.getStore().getData().container.height} onChange={(e) => { const val = e; const isEdit = props.config.getStoreChanger().isEdit(); if (isEdit) { const originData: IStoreData = deepcopy( props.config.getStoreChanger().getOrigin()!.now ); originData.container.height = val; props.config.getStoreChanger().updateOrigin(originData); } else { const originData = deepcopy(props.config.getStore().getData()); originData.container.height = val; props.config.getStore().setData(originData); } }} /> </Col> </Row> <Row style={{ padding: '10px 0' }}> <Col span={6} style={{ userSelect: 'none' }}> {replaceLocale('right.containerColor', '容器底色', props.config)} </Col> <Col span={18} style={colStyle}> { <div style={{ position: 'relative' }}> <div onClick={() => { setColorPickerVisible((pre) => !pre); }} style={{ background: '#fff', borderRadius: '1px', boxShadow: '0 0 0 1px rgba(0,0,0,.1)', cursor: 'pointer', display: 'inline-block', }} > <div style={{ width: '20px', height: '20px', borderRadius: '2px', background: `rgba(${color.r}, ${color.g}, ${color.b}, ${color.a})`, }} /> </div> {colorPickerVisible && ( <> <div style={{ position: 'absolute', zIndex: 2000, transform: `translate(-100%, 0px)`, }} > <SketchPicker color={color} onChange={(c) => { const newcolor = c.rgb; setColor(newcolor); const isEdit = props.config.getStoreChanger().isEdit(); if (isEdit) { const originData: IStoreData = deepcopy( props.config.getStoreChanger().getOrigin()!.now ); originData.globalState.containerColor = `rgba(${newcolor.r}, ${newcolor.g}, ${newcolor.b}, ${newcolor.a})`; props.config.getStoreChanger().updateOrigin(originData); } else { const originData = deepcopy(props.config.getStore().getData()); originData.globalState.containerColor = `rgba(${newcolor.r}, ${newcolor.g}, ${newcolor.b}, ${newcolor.a})`; props.config.getStore().setData(originData); } }} ></SketchPicker> </div> <div style={{ position: 'fixed', top: '0px', right: '0px', bottom: '0px', left: '0px', zIndex: 1000, }} onClick={() => setColorPickerVisible(false)} /> </> )} </div> } </Col> </Row> <Row style={{ padding: '10px 0' }}> <Col span={6} style={{ userSelect: 'none' }}> {replaceLocale('right.bodyColor', 'body底色', props.config)} </Col> <Col span={18} style={colStyle}> { <div style={{ position: 'relative' }}> <div onClick={() => { setColorPickerVisible2((pre) => !pre); }} style={{ background: '#fff', borderRadius: '1px', boxShadow: '0 0 0 1px rgba(0,0,0,.1)', cursor: 'pointer', display: 'inline-block', }} > <div style={{ width: '20px', height: '20px', borderRadius: '2px', background: `rgba(${color2.r}, ${color2.g}, ${color2.b}, ${color2.a})`, }} /> </div> {colorPickerVisible2 && ( <> <div style={{ position: 'absolute', zIndex: 2000, transform: `translate(-100%, 0px)`, }} > <SketchPicker color={color2} onChange={(c) => { const newcolor = c.rgb; setColor2(newcolor); const isEdit = props.config.getStoreChanger().isEdit(); if (isEdit) { const originData: IStoreData = deepcopy( props.config.getStoreChanger().getOrigin()!.now ); originData.globalState.bodyColor = `rgba(${newcolor.r}, ${newcolor.g}, ${newcolor.b}, ${newcolor.a})`; props.config.getStoreChanger().updateOrigin(originData); } else { const originData = deepcopy(props.config.getStore().getData()); originData.globalState.bodyColor = `rgba(${newcolor.r}, ${newcolor.g}, ${newcolor.b}, ${newcolor.a})`; props.config.getStore().setData(originData); } }} ></SketchPicker> </div> <div style={{ position: 'fixed', top: '0px', right: '0px', bottom: '0px', left: '0px', zIndex: 1000, }} onClick={() => setColorPickerVisible2(false)} /> </> )} </div> } </Col> </Row> </div> )} {!current && !isEdit && customGlobal && customGlobal(props.config)} {!current && isEdit && ( <div style={{ padding: '20px' }} className="yh-tcsz"> <Row style={{ padding: '10 0 20px 0', fontWeight: 'bold' }}> {replaceLocale('modal.control', '弹窗配置', props.config)} </Row> <Row style={{ padding: '10px 0' }}> <Col span={8}> {replaceLocale('modal.control.remove', '取消点击删除弹窗', props.config)} </Col> <Col span={16} style={{ ...colStyle }}> <Checkbox checked={originData ? originData.modalConfig[modalName] : false} onChange={(e) => { const val = e.target.checked; const cloneData = deepcopy(originData); if (cloneData) { cloneData.modalConfig[modalName] = val; props.config.getStoreChanger().updateOrigin(cloneData); props.config.getStore().forceUpdate(); } }} ></Checkbox> </Col> </Row> </div> )} </div> ); } export default RightConfig;
the_stack
import ClassOrder from './class-order' import { defaultGraphURI } from './factories/canonical-data-factory' import Formula, { FormulaOpts } from './formula' import { ArrayIndexOf } from './utils' import { RDFArrayRemove } from './utils-js' import { isRDFlibObject, isStore, isGraph, isPredicate, isQuad, isSubject } from './utils/terms' import Node from './node' import Variable from './variable' import { Query, indexedFormulaQuery } from './query' import UpdateManager from './update-manager' import { Bindings, BlankNodeTermType, CollectionTermType, DefaultGraphTermType, EmptyTermType, GraphTermType, LiteralTermType, NamedNodeTermType, VariableTermType } from './types' import Statement from './statement' import { Indexable } from './factories/factory-types' import NamedNode from './named-node' import Fetcher from './fetcher' import { Quad_Graph, Literal as TFLiteral, NamedNode as TFNamedNode, Quad_Object, Quad_Predicate, Quad, Quad_Subject, Term, } from './tf-types' import { namedNode } from './index' import BlankNode from './blank-node' import DefaultGraph from './default-graph' import Empty from './empty' import Literal from './literal' import Collection from './collection' const owlNamespaceURI = 'http://www.w3.org/2002/07/owl#' type FeaturesType = Array<('sameAs' | 'InverseFunctionalProperty' | 'FunctionalProperty')> | undefined export { defaultGraphURI } // var link_ns = 'http://www.w3.org/2007/ont/link#' // Handle Functional Property function handleFP ( formula: IndexedFormula, subj: Quad_Subject, pred: Quad_Predicate, obj: Quad_Object ): boolean { var o1 = formula.any(subj, pred, undefined) if (!o1) { return false // First time with this value } // log.warn("Equating "+o1.uri+" and "+obj.uri + " because FP "+pred.uri); //@@ formula.equate(o1, obj) return true } // handleFP // Handle Inverse Functional Property function handleIFP ( formula: IndexedFormula, subj: Quad_Subject, pred: Quad_Predicate, obj: Quad_Object ): boolean { var s1 = formula.any(undefined, pred, obj) if (!s1) { return false // First time with this value } // log.warn("Equating "+s1.uri+" and "+subj.uri + " because IFP "+pred.uri); //@@ formula.equate(s1, subj) return true } // handleIFP function handleRDFType ( formula: IndexedFormula, subj: Quad_Subject, pred: Quad_Predicate, obj: Quad_Object, why: Quad_Graph ) { //@ts-ignore this method does not seem to exist in this library if (formula.typeCallback) { (formula as any).typeCallback(formula, obj, why) } var x = formula.classActions[formula.id(obj)] var done = false if (x) { for (var i = 0; i < x.length; i++) { done = done || x[i](formula, subj, pred, obj, why) } } return done // statement given is not needed if true } /** * Indexed Formula aka Store */ export default class IndexedFormula extends Formula { // IN future - allow pass array of statements to constructor /** * An UpdateManager initialised to this store */ updater?: UpdateManager /** * Dictionary of namespace prefixes */ namespaces: {[key: string]: string} /** Map of iri predicates to functions to call when adding { s type X } */ classActions: { [k: string]: Function[] } /** Map of iri predicates to functions to call when getting statement with {s X o} */ propertyActions: { [k: string]: Function[] } /** Redirect to lexically smaller equivalent symbol */ redirections: any[] /** Reverse mapping to redirection: aliases for this */ aliases: any[] /** Redirections we got from HTTP */ HTTPRedirects: Statement[] /** Array of statements with this X as subject */ subjectIndex: Statement[] /** Array of statements with this X as predicate */ predicateIndex: Statement[] /** Array of statements with this X as object */ objectIndex: Statement[] /** Array of statements with X as provenance */ whyIndex: Statement[] index: [ Statement[], Statement[], Statement[], Statement[] ] features: FeaturesType static handleRDFType: Function _universalVariables?: NamedNode[] _existentialVariables?: BlankNode[] /** Function to remove quads from the store arrays with */ private rdfArrayRemove: (arr: Quad[], q: Quad) => void /** Callbacks which are triggered after a statement has been added to the store */ private dataCallbacks?: Array<(q: Quad) => void> /** * Creates a new formula * @param features - What sort of automatic processing to do? Array of string * @param features.sameAs - Smush together A and B nodes whenever { A sameAs B } * @param opts * @param [opts.rdfFactory] - The data factory that should be used by the store * @param [opts.rdfArrayRemove] - Function which removes statements from the store * @param [opts.dataCallback] - Callback when a statement is added to the store, will not trigger when adding duplicates */ constructor (features?: FeaturesType, opts: FormulaOpts = {}) { super(undefined, undefined, undefined, undefined, opts) this.propertyActions = {} this.classActions = {} this.redirections = [] this.aliases = [] this.HTTPRedirects = [] this.subjectIndex = [] this.predicateIndex = [] this.objectIndex = [] this.whyIndex = [] this.index = [ this.subjectIndex, this.predicateIndex, this.objectIndex, this.whyIndex ] this.namespaces = {} // Dictionary of namespace prefixes this.features = features || [ // By default, devs do not expect these features. // See https://github.com/linkeddata/rdflib.js/issues/458 // 'sameAs', // 'InverseFunctionalProperty', // 'FunctionalProperty', ] this.rdfArrayRemove = opts.rdfArrayRemove || RDFArrayRemove if (opts.dataCallback) { this.dataCallbacks = [opts.dataCallback] } this.initPropertyActions(this.features) } /** * Gets the URI of the default graph */ static get defaultGraphURI(): string { return defaultGraphURI } /** * Gets this graph with the bindings substituted * @param bindings The bindings */ substitute <T extends Node = IndexedFormula>(bindings: Bindings): T { var statementsCopy = this.statements.map(function (ea: Quad) { return (ea as Statement).substitute(bindings) }) var y = new IndexedFormula() y.add(statementsCopy) return y as unknown as T } /** * Add a callback which will be triggered after a statement has been added to the store. * @param cb */ addDataCallback(cb: (q: Quad) => void): void { if (!this.dataCallbacks) { this.dataCallbacks = [] } this.dataCallbacks.push(cb) } /** * Apply a set of statements to be deleted and to be inserted * * @param patch - The set of statements to be deleted and to be inserted * @param target - The name of the document to patch * @param patchCallback - Callback to be called when patching is complete */ applyPatch( patch: { delete?: ReadonlyArray<Statement>, patch?: ReadonlyArray<Statement>, where?: any }, target: TFNamedNode, patchCallback: (errorString?: string) => void ): void { var targetKB = this var ds var binding: Bindings | null = null function doPatch (onDonePatch: (errorString?: string) => void) { if (patch['delete']) { ds = patch['delete'] // console.log(bindingDebug(binding)) // console.log('ds before substitute: ' + ds) if (binding) ds = ds.substitute(binding) // console.log('applyPatch: delete: ' + ds) ds = ds.statements as Statement[] var bad: Quad[] = [] var ds2 = ds.map(function (st: Quad) { // Find the actual statements in the store var sts = targetKB.statementsMatching(st.subject, st.predicate, st.object, target) if (sts.length === 0) { // log.info("NOT FOUND deletable " + st) bad.push(st) return null } else { // log.info("Found deletable " + st) return sts[0] } }) if (bad.length) { // console.log('Could not find to delete ' + bad.length + 'statements') // console.log('despite ' + targetKB.statementsMatching(bad[0].subject, bad[0].predicate)[0]) return patchCallback('Could not find to delete: ' + bad.join('\n or ')) } ds2.map(function (st: Quad) { targetKB.remove(st) }) } if (patch['insert']) { // log.info("doPatch insert "+patch['insert']) ds = patch['insert'] if (binding) ds = ds.substitute(binding) ds = ds.statements ds.map(function (st: Quad) { st.graph = target targetKB.add(st.subject, st.predicate, st.object, st.graph) }) } onDonePatch() } if (patch.where) { // log.info("Processing WHERE: " + patch.where + '\n') var query = new Query('patch') query.pat = patch.where query.pat.statements.map(function (st) { st.graph = namedNode(target.value) }) //@ts-ignore TODO: add sync property to Query when converting Query to typescript query.sync = true var bindingsFound: Bindings[] = [] targetKB.query( query, function onBinding (binding) { bindingsFound.push(binding) // console.log(' got a binding: ' + bindingDebug(binding)) }, targetKB.fetcher, function onDone () { if (bindingsFound.length === 0) { return patchCallback('No match found to be patched:' + patch.where) } if (bindingsFound.length > 1) { return patchCallback('Patch ambiguous. No patch done.') } binding = bindingsFound[0] doPatch(patchCallback) }) } else { doPatch(patchCallback) } } /** * N3 allows for declaring blank nodes, this function enables that support * * @param x The blank node to be declared, supported in N3 */ declareExistential(x: BlankNode): BlankNode { if (!this._existentialVariables) this._existentialVariables = [] this._existentialVariables.push(x) return x } /** * @param features */ initPropertyActions(features: FeaturesType) { // If the predicate is #type, use handleRDFType to create a typeCallback on the object this.propertyActions[this.rdfFactory.id(this.rdfFactory.namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'))] = [ handleRDFType ] // Assumption: these terms are not redirected @@fixme if (ArrayIndexOf(features, 'sameAs') >= 0) { this.propertyActions[this.rdfFactory.id(this.rdfFactory.namedNode(`${owlNamespaceURI}sameAs`))] = [ function (formula, subj, pred, obj, why) { // log.warn("Equating "+subj.uri+" sameAs "+obj.uri); //@@ formula.equate(subj, obj) return true // true if statement given is NOT needed in the store } ] // sameAs -> equate & don't add to index } if (ArrayIndexOf(features, 'InverseFunctionalProperty') >= 0) { this.classActions[this.rdfFactory.id(this.rdfFactory.namedNode(`${owlNamespaceURI}InverseFunctionalProperty`))] = [ function (formula, subj, pred, obj, addFn) { // yes subj not pred! return formula.newPropertyAction(subj, handleIFP) } ] // IFP -> handleIFP, do add to index } if (ArrayIndexOf(features, 'FunctionalProperty') >= 0) { this.classActions[this.rdfFactory.id(this.rdfFactory.namedNode(`${owlNamespaceURI}FunctionalProperty`))] = [ function (formula, subj, proj, obj, addFn) { return formula.newPropertyAction(subj, handleFP) } ] // FP => handleFP, do add to index } } /** @deprecated Use {add} instead */ addStatement (st: Quad): number { this.add(st.subject, st.predicate, st.object, st.graph) return this.statements.length } /** * Adds a triple (quad) to the store. * * @param subj - The thing about which the fact a relationship is asserted. * Also accepts a statement or an array of Statements. * @param pred - The relationship which is asserted * @param obj - The object of the relationship, e.g. another thing or a value. If passed a string, this will become a literal. * @param why - The document in which the triple (S,P,O) was or will be stored on the web * @returns The statement added to the store, or the store */ add ( subj: Quad_Subject | Quad | Quad[] | Statement | Statement[], pred?: Quad_Predicate, obj?: Term | string, why?: Quad_Graph ): Statement | null | this | number { var i: number if (arguments.length === 1) { if (subj instanceof Array) { for (i = 0; i < subj.length; i++) { this.add(subj[i]) } } else if (isQuad(subj)) { this.add(subj.subject, subj.predicate, subj.object, subj.graph) } else if (isStore(subj)) { this.add((subj as any).statements) } return this } var actions: Function[] var st: Statement if (!why) { // system generated why = this.fetcher ? this.fetcher.appNode : this.rdfFactory.defaultGraph() } if (typeof subj == 'string') { subj = this.rdfFactory.namedNode(subj) } pred = Node.fromValue(pred) const objNode = Node.fromValue(obj) as Term why = Node.fromValue(why) if (!isSubject(subj)) { throw new Error('Subject is not a subject type') } if (!isPredicate(pred)) { throw new Error(`Predicate ${pred} is not a predicate type`) } if (!isRDFlibObject(objNode)) { throw new Error(`Object ${objNode} is not an object type`) } if (!isGraph(why)) { throw new Error("Why is not a graph type") } //@ts-ignore This is not used internally if (this.predicateCallback) { //@ts-ignore This is not used internally this.predicateCallback(this, pred, why) } // Action return true if the statement does not need to be added var predHash = this.id(this.canon(pred!)) actions = this.propertyActions[predHash] // Predicate hash var done = false if (actions) { // alert('type: '+typeof actions +' @@ actions='+actions) for (i = 0; i < actions.length; i++) { done = done || actions[i](this, subj, pred, objNode, why) } } if (this.holds(subj, pred, objNode, why)) { // Takes time but saves duplicates // console.log('rdflib: Ignoring dup! {' + subj + ' ' + pred + ' ' + obj + ' ' + why + '}') return null // @@better to return self in all cases? } // If we are tracking provenance, every thing should be loaded into the store // if (done) return this.rdfFactory.quad(subj, pred, obj, why) // Don't put it in the store // still return this statement for owl:sameAs input var hash = [ this.id(this.canon(subj)), predHash, this.id(this.canon(objNode)), this.id(this.canon(why)) ] // @ts-ignore this will fail if you pass a collection and the factory does not allow Collections st = this.rdfFactory.quad(subj, pred, objNode, why) for (i = 0; i < 4; i++) { var ix = this.index[i] var h = hash[i] if (!ix[h]) { ix[h] = [] } ix[h].push(st) // Set of things with this as subject, etc } // log.debug("ADDING {"+subj+" "+pred+" "+objNode+"} "+why) this.statements.push(st) if (this.dataCallbacks) { for (const callback of this.dataCallbacks) { callback(st) } } return st } /** * Returns the symbol with canonical URI as smushed * @param term - An RDF node */ canon(term?: Term): Node { if (!term) { // @@ TODO Should improve this to return proper value - doing this to keep it backward compatible return term as unknown as Node } const y = this.redirections[this.id(term)] if (y) { return y } switch (term.termType) { case BlankNodeTermType: return new BlankNode(term.value) case CollectionTermType: return term as Collection // non-RDF/JS type, should just need to cast case DefaultGraphTermType: return new DefaultGraph() case EmptyTermType: // non-RDF/JS type, should just need to cast return term as Empty case GraphTermType: // non-RDF/JS type, should just need to cast return term as IndexedFormula case LiteralTermType: return new Literal(term.value, (term as TFLiteral).language, (term as TFLiteral).datatype) case NamedNodeTermType: return new NamedNode(term.value) case VariableTermType: return new Variable(term.value) default: throw new Error(`Term Type not recognized for canonization: ${term.termType}`) } } /** * Checks this formula for consistency */ check(): void { this.checkStatementList(this.statements) for (var p = 0; p < 4; p++) { var ix = this.index[p] for (var key in ix) { if (ix.hasOwnProperty(key)) { // @ts-ignore should this pass an array or a single statement? checkStateMentsList expects an array. this.checkStatementList(ix[key], p) } } } } /** * Checks a list of statements for consistency * @param sts - The list of statements to check * @param from - An index with the array ['subject', 'predicate', 'object', 'why'] */ checkStatementList( sts: ReadonlyArray<Quad>, from?: number ): boolean | void { if (from === undefined) { from = 0 } var names = ['subject', 'predicate', 'object', 'why'] var origin = ' found in ' + names[from] + ' index.' var st: Quad for (var j = 0; j < sts.length; j++) { st = sts[j] var term = [ st.subject, st.predicate, st.object, st.graph ] var arrayContains = function (a: Array<any>, x: Quad) { for (var i = 0; i < a.length; i++) { if (a[i].subject.equals(x.subject) && a[i].predicate.equals(x.predicate) && a[i].object.equals(x.object) && a[i].why.equals(x.graph)) { return true } } } for (var p = 0; p < 4; p++) { var c = this.canon(term[p]) var h = this.id(c) if (!this.index[p][h]) { // throw new Error('No ' + name[p] + ' index for statement ' + st + '@' + st.why + origin) } else { if (!arrayContains(this.index[p][h], st)) { // throw new Error('Index for ' + name[p] + ' does not have statement ' + st + '@' + st.why + origin) } } } if (!arrayContains(this.statements, st)) { throw new Error('Statement list does not statement ' + st + '@' + st.graph + origin) } } } /** * Closes this formula (and return it) */ close(): IndexedFormula { return this } compareTerms(u1: Term, u2: Term): number { // Keep compatibility with downstream classOrder changes if (Object.prototype.hasOwnProperty.call(u1, "compareTerm")) { return (u1 as Node).compareTerm(u2 as Node) } if (ClassOrder[u1.termType] < ClassOrder[u2.termType]) { return -1 } if (ClassOrder[u1.termType] > ClassOrder[u2.termType]) { return +1 } if (u1.value < u2.value) { return -1 } if (u1.value > u2.value) { return +1 } return 0 } /** * replaces @template with @target and add appropriate triples * removes no triples by default and is a one-direction replication * @param template node to copy * @param target node to copy to * @param flags Whether or not to do a two-directional copy and/or delete triples */ copyTo( template: Quad_Subject, target: Quad_Subject, flags?: Array<('two-direction' | 'delete')> ): void { if (!flags) flags = [] var statList = this.statementsMatching(template) if (ArrayIndexOf(flags, 'two-direction') !== -1) { statList.concat(this.statementsMatching(undefined, undefined, template)) } for (var i = 0; i < statList.length; i++) { var st = statList[i] switch (st.object.termType) { case 'NamedNode': this.add(target, st.predicate, st.object) break case 'Literal': case 'BlankNode': // @ts-ignore Collections can appear here case 'Collection': // @ts-ignore Possible bug: copy is not available on Collections this.add(target, st.predicate, st.object.copy(this)) } if (ArrayIndexOf(flags, 'delete') !== -1) { this.remove(st) } } } /** * Simplify graph in store when we realize two identifiers are equivalent * We replace the bigger with the smaller. * @param u1in The first node * @param u2in The second node */ equate(u1in: Term, u2in : Term): boolean { // log.warn("Equating "+u1+" and "+u2); // @@ // @@JAMBO Must canonicalize the uris to prevent errors from a=b=c // 03-21-2010 const u1 = this.canon(u1in) as Quad_Subject const u2 = this.canon(u2in) as Quad_Subject var d = this.compareTerms(u1, u2) if (!d) { return true // No information in {a = a} } // var big // var small if (d < 0) { // u1 less than u2 return this.replaceWith(u2, u1) } else { return this.replaceWith(u1, u2) } } /** * Creates a new empty indexed formula * Only applicable for IndexedFormula, but TypeScript won't allow a subclass to override a property * @param features The list of features */ formula(features: FeaturesType): IndexedFormula { return new IndexedFormula(features) } /** * Returns the number of statements contained in this IndexedFormula. * (Getter proxy to this.statements). * Usage: * ``` * var kb = rdf.graph() * kb.length // -> 0 * ``` * @returns {Number} */ get length (): number { return this.statements.length } /** * Returns any quads matching the given arguments. * Standard RDFJS spec method for Source objects, implemented as an * alias to `statementsMatching()` * @param subject The subject * @param predicate The predicate * @param object The object * @param graph The graph that contains the statement */ match( subject?: Quad_Subject | null, predicate?: Quad_Predicate | null, object?: Quad_Object | null, graph?: Quad_Graph | null ): Quad[] { return this.statementsMatching( Node.fromValue(subject), Node.fromValue(predicate), Node.fromValue(object), Node.fromValue(graph) ) } /** * Find out whether a given URI is used as symbol in the formula * @param uri The URI to look for */ mentionsURI(uri: string): boolean { var hash = '<' + uri + '>' return (!!this.subjectIndex[hash] || !!this.objectIndex[hash] || !!this.predicateIndex[hash]) } /** * Existentials are BNodes - something exists without naming * @param uri An URI */ newExistential(uri: string): Term { if (!uri) return this.bnode() var x = this.sym(uri) // @ts-ignore x should be blanknode, but is namedNode. return this.declareExistential(x) } /** * Adds a new property action * @param pred the predicate that the function should be triggered on * @param action the function that should trigger */ newPropertyAction( pred: Quad_Predicate, action: ( store: IndexedFormula, subject: Quad_Subject, predicate: Quad_Predicate, object: Quad_Object ) => boolean ): boolean { // log.debug("newPropertyAction: "+pred) var hash = this.id(pred) if (!this.propertyActions[hash]) { this.propertyActions[hash] = [] } this.propertyActions[hash].push(action) // Now apply the function to to statements already in the store var toBeFixed = this.statementsMatching(undefined, pred, undefined) var done = false for (var i = 0; i < toBeFixed.length; i++) { // NOT optimized - sort toBeFixed etc done = done || action(this, toBeFixed[i].subject, pred, toBeFixed[i].object) } return done } /** * Creates a new universal node * Universals are Variables * @param uri An URI */ newUniversal(uri: string): TFNamedNode { var x = this.sym(uri) if (!this._universalVariables) this._universalVariables = [] this._universalVariables.push(x) return x } // convenience function used by N3 parser variable (name: string) { return new Variable(name) } /** * Find an unused id for a file being edited: return a symbol * (Note: Slow iff a lot of them -- could be O(log(k)) ) * @param doc A document named node */ nextSymbol(doc: TFNamedNode): TFNamedNode { for (var i = 0; ;i++) { var uri = doc.value + '#n' + i if (!this.mentionsURI(uri)) return this.sym(uri) } } /** * Query this store asynchronously, return bindings in callback * * @param myQuery The query to be run * @param callback Function to call when bindings * @param Fetcher | null If you want the query to do link following * @param onDone OBSOLETE - do not use this // @@ Why not ?? Called when query complete */ query( myQuery: Query, callback: (bindings: Bindings) => void, fetcher?: Fetcher | null, onDone?: () => void ): void { return indexedFormulaQuery.call(this, myQuery, callback, fetcher, onDone) } /** * Query this store synchronously and return bindings * * @param myQuery The query to be run */ querySync(myQuery: Query): any[] { var results: Bindings[] = [] function saveBinginds (bindings: Bindings) { results.push(bindings) } function onDone () { done = true } var done = false // @ts-ignore TODO: Add .sync to Query myQuery.sync = true indexedFormulaQuery.call(this, myQuery, saveBinginds, null, onDone) if (!done) { throw new Error('Sync query should have called done function') } return results } /** * Removes one or multiple statement(s) from this formula * @param st - A Statement or array of Statements to remove */ remove(st: Quad | Quad[]): IndexedFormula { if (st instanceof Array) { for (var i = 0; i < st.length; i++) { this.remove(st[i]) } return this } if (isStore(st)) { return this.remove(st.statements) } var sts = this.statementsMatching(st.subject, st.predicate, st.object, st.graph) if (!sts.length) { throw new Error('Statement to be removed is not on store: ' + st) } this.removeStatement(sts[0]) return this } /** * Removes all statements in a doc * @param doc - The document / graph */ removeDocument(doc: Quad_Graph): IndexedFormula { var sts: Quad[] = this.statementsMatching(undefined, undefined, undefined, doc).slice() // Take a copy as this is the actual index for (var i = 0; i < sts.length; i++) { this.removeStatement(sts[i]) } return this } /** * Remove all statements matching args (within limit) * * @param subj The subject * @param pred The predicate * @param obj The object * @param why The graph that contains the statement * @param limit The number of statements to remove */ removeMany( subj?: Quad_Subject | null, pred?: Quad_Predicate | null, obj?: Quad_Object | null, why?: Quad_Graph | null, limit?: number ): void { // log.debug("entering removeMany w/ subj,pred,obj,why,limit = " + subj +", "+ pred+", " + obj+", " + why+", " + limit) var sts = this.statementsMatching(subj, pred, obj, why, false) // This is a subtle bug that occurred in updateCenter.js too. // The fact is, this.statementsMatching returns this.whyIndex instead of a copy of it // but for perfromance consideration, it's better to just do that // so make a copy here. var statements: Quad[] = [] for (var i = 0; i < sts.length; i++) statements.push(sts[i]) if (limit) statements = statements.slice(0, limit) for (i = 0; i < statements.length; i++) this.remove(statements[i]) } /** * Remove all matching statements * @param subject The subject * @param predicate The predicate * @param object The object * @param graph The graph that contains the statement */ removeMatches( subject?: Quad_Subject | null, predicate?: Quad_Predicate | null, object?: Quad_Object | null, graph?: Quad_Graph | null ): IndexedFormula { this.removeStatements( this.statementsMatching(subject, predicate, object, graph) ) return this } /** * Remove a particular statement object from the store * * @param st - a statement which is already in the store and indexed. * Make sure you only use this for these. * Otherwise, you should use remove() above. */ removeStatement(st: Quad): IndexedFormula { // log.debug("entering remove w/ st=" + st) var term = [ st.subject, st.predicate, st.object, st.graph ] for (var p = 0; p < 4; p++) { var c = this.canon(term[p]) var h = this.id(c) if (!this.index[p][h]) { // log.warn ("Statement removal: no index '+p+': "+st) } else { this.rdfArrayRemove(this.index[p][h], st) } } this.rdfArrayRemove(this.statements, st) return this } /** * Removes statements * @param sts The statements to remove */ removeStatements(sts: ReadonlyArray<Quad>): IndexedFormula { for (var i = 0; i < sts.length; i++) { this.remove(sts[i]) } return this } /** * Replace big with small, obsoleted with obsoleting. */ replaceWith (big: Quad_Subject, small: Quad_Subject): boolean { // log.debug("Replacing "+big+" with "+small) // this.id(@@ var oldhash = this.id(big) var newhash = this.id(small) var moveIndex = function (ix) { var oldlist = ix[oldhash] if (!oldlist) { return // none to move } var newlist = ix[newhash] if (!newlist) { ix[newhash] = oldlist } else { ix[newhash] = oldlist.concat(newlist) } delete ix[oldhash] } // the canonical one carries all the indexes for (var i = 0; i < 4; i++) { moveIndex(this.index[i]) } this.redirections[oldhash] = small if (big.value) { // @@JAMBO: must update redirections,aliases from sub-items, too. if (!this.aliases[newhash]) { this.aliases[newhash] = [] } this.aliases[newhash].push(big) // Back link if (this.aliases[oldhash]) { for (i = 0; i < this.aliases[oldhash].length; i++) { this.redirections[this.id(this.aliases[oldhash][i])] = small this.aliases[newhash].push(this.aliases[oldhash][i]) } } this.add(small, this.sym('http://www.w3.org/2007/ont/link#uri'), big) // If two things are equal, and one is requested, we should request the other. if (this.fetcher) { this.fetcher.nowKnownAs(big, small) } } moveIndex(this.classActions) moveIndex(this.propertyActions) // log.debug("Equate done. "+big+" to be known as "+small) return true // true means the statement does not need to be put in } /** * Return all equivalent URIs by which this is known * @param x A named node */ allAliases(x: NamedNode): NamedNode[] { var a = this.aliases[this.id(this.canon(x))] || [] a.push(this.canon(x)) return a } /** * Compare by canonical URI as smushed * @param x A named node * @param y Another named node */ sameThings(x: NamedNode, y: NamedNode): boolean { if (x.equals(y)) { return true } var x1 = this.canon(x) // alert('x1='+x1) if (!x1) return false var y1 = this.canon(y) // alert('y1='+y1); //@@ if (!y1) return false return (x1.value === y1.value) } setPrefixForURI (prefix: string, nsuri: string): void { // TODO: This is a hack for our own issues, which ought to be fixed // post-release // See http://dig.csail.mit.edu/cgi-bin/roundup.cgi/$rdf/issue227 if (prefix === 'tab' && this.namespaces['tab']) { return } // There are files around with long badly generated prefixes like this if (prefix.slice(0, 2) === 'ns' || prefix.slice(0, 7) === 'default') { return } this.namespaces[prefix] = nsuri } /** Search the Store * * ALL CONVENIENCE LOOKUP FUNCTIONS RELY ON THIS! * @param subj - A node to search for as subject, or if null, a wildcard * @param pred - A node to search for as predicate, or if null, a wildcard * @param obj - A node to search for as object, or if null, a wildcard * @param why - A node to search for as graph, or if null, a wildcard * @param justOne - flag - stop when found one rather than get all of them? * @returns An array of nodes which match the wildcard position */ statementsMatching ( subj?: Quad_Subject | null, pred?: Quad_Predicate | null, obj?: Quad_Object | null, why?: Quad_Graph | null, justOne?: boolean ): Statement[] { // log.debug("Matching {"+subj+" "+pred+" "+obj+"}") var pat = [ subj, pred, obj, why ] var pattern: Term[] = [] var hash: Indexable[] = [] var wild: number[] = [] // wildcards var given: number[] = [] // Not wild var p: number var list for (p = 0; p < 4; p++) { pattern[p] = this.canon(Node.fromValue(pat[p])) if (!pattern[p]) { wild.push(p) } else { given.push(p) hash[p] = this.id(pattern[p]) } } if (given.length === 0) { return this.statements } if (given.length === 1) { // Easy too, we have an index for that p = given[0] list = this.index[p][hash[p]] if (list && justOne) { if (list.length > 1) { list = list.slice(0, 1) } } list = list || [] return list } // Now given.length is 2, 3 or 4. // We hope that the scale-free nature of the data will mean we tend to get // a short index in there somewhere! var best = 1e10 // really bad var iBest var i for (i = 0; i < given.length; i++) { p = given[i] // Which part we are dealing with list = this.index[p][hash[p]] if (!list) { return [] // No occurrences } if (list.length < best) { best = list.length iBest = i // (not p!) } } // Ok, we have picked the shortest index but now we have to filter it var pBest = given[iBest] var possibles: Statement[] = this.index[pBest][hash[pBest]] var check = given.slice(0, iBest).concat(given.slice(iBest + 1)) // remove iBest var results: Statement[] = [] var parts = [ 'subject', 'predicate', 'object', 'why' ] for (var j = 0; j < possibles.length; j++) { var st: Statement | null = possibles[j] for (i = 0; i < check.length; i++) { // for each position to be checked p = check[i] if (!this.canon(st[parts[p]]).equals(pattern[p])) { st = null break } } if (st != null) { results.push(st) if (justOne) break } } return results } /** * A list of all the URIs by which this thing is known * @param term */ uris(term: Quad_Subject): string[] { var cterm = this.canon(term) var terms = this.aliases[this.id(cterm)] if (!cterm.value) return [] var res = [ cterm.value ] if (terms) { for (var i = 0; i < terms.length; i++) { res.push(terms[i].uri) } } return res } } IndexedFormula.handleRDFType = handleRDFType
the_stack
import BTree from 'sorted-btree'; import { fail, assert, comparePayloads, copyPropertyIfDefined } from './Common'; import { NodeData, Payload } from './generic'; import { NodeId, TraitLabel } from './Identifiers'; import { compareStrings } from './SnapshotUtilities'; type Optional<T> = { [P in keyof T]: T[P] | undefined; }; /** * A node that can be contained within a Forest. */ export interface ForestNode extends NodeData { readonly traits: ReadonlyMap<TraitLabel, readonly NodeId[]>; } interface ForestNodeWithParentage extends ForestNode, Optional<ParentData> { readonly _brand: unique symbol; } /** * Information about a ForestNode's parent */ export interface ParentData { readonly parentId: NodeId; readonly traitParent: TraitLabel; } /** * Differences from one forest to another. */ export interface Delta<NodeId> { /** * Nodes whose content changed. */ readonly changed: readonly NodeId[]; /** * Nodes that were added. */ readonly added: readonly NodeId[]; /** * Nodes that were removed. */ readonly removed: readonly NodeId[]; } interface ForestState { nodes: BTree<NodeId, ForestNodeWithParentage>; expensiveValidation: boolean; } /** * An immutable forest of ForestNode. * Enforces single parenting, and allows querying the parent. */ export class Forest { /** * Contains the nodes in the forest. * Used as an immutable data-structure: must not be modified. */ private readonly nodes: BTree<NodeId, ForestNodeWithParentage>; /** * If true, consistency checks will be applied after forest operations. */ private readonly expensiveValidation: boolean; /** * Caller must ensure provided BTrees are not modified. * Will not modify the BTrees. */ private constructor(data: ForestState); /** * Construct a new forest without reusing nodes from a previous one. */ private constructor(expensiveValidation: boolean); private constructor(data?: ForestState | boolean) { if (typeof data === 'object') { this.nodes = data.nodes; this.expensiveValidation = data.expensiveValidation; } else { this.nodes = new BTree<NodeId, ForestNodeWithParentage>(undefined, compareStrings); this.expensiveValidation = data ?? false; } if (this.expensiveValidation) { this.assertConsistent(); } } /** * Creates a new Forest. */ public static create(expensiveValidation = false): Forest { return new Forest(expensiveValidation); } /** * Returns the number of nodes in the forest. */ public get size(): number { return this.nodes.size; } /** * Adds the supplied nodes to the forest. The IDs must be unique in the forest. * @param nodes - the sequence of nodes to add to the forest. If any of them have children which exist in the forest already, those * children will be parented. Any trait arrays present in a node must be non-empty. */ public add(nodes: Iterable<ForestNode>): Forest { const newNodes = [...nodes]; const childToParent = new Map<NodeId, ParentData>(); const mutableNodes = this.nodes.clone(); for (const node of newNodes) { const { identifier } = node; for (const [traitLabel, trait] of node.traits) { assert(trait.length > 0, 'any trait arrays present in a node must be non-empty'); for (const childId of trait) { const child = mutableNodes.get(childId); if (child !== undefined) { assert(child.parentId === undefined, 'can not give a child multiple parents'); // A child already exists in the forest, and its parent is now being added const parentedChild = { definition: child.definition, identifier: child.identifier, traits: child.traits, parentId: identifier, traitParent: traitLabel, }; copyPropertyIfDefined(child, parentedChild, 'payload'); mutableNodes.set(childId, parentedChild as ForestNodeWithParentage); } else { childToParent.set(childId, { parentId: identifier, traitParent: traitLabel }); } } } } for (const node of newNodes) { const parentData = childToParent.get(node.identifier); assert(!mutableNodes.has(node.identifier), 'can not add node with already existing id'); if (parentData !== undefined) { // A parent and child have both been added for the first time const child = { definition: node.definition, identifier: node.identifier, traits: node.traits, ...parentData, }; copyPropertyIfDefined(node, child, 'payload'); mutableNodes.set(node.identifier, child as ForestNodeWithParentage); } else { // A root node (no parent) has been added to the forest mutableNodes.set(node.identifier, node as ForestNodeWithParentage); } } return new Forest({ nodes: mutableNodes, expensiveValidation: this.expensiveValidation, }); } /** * Parents a set of nodes already in the forest at a specified location within a trait. * @param parentId - the id of the parent under which to insert the new nodes * @param label - the label of the trait under which to insert the new nodes * @param index - the index in the trait after which to insert the new nodes * @param childIds - the ids of the nodes to insert */ public attachRangeOfChildren( parentId: NodeId, label: TraitLabel, index: number, childIds: readonly NodeId[] ): Forest { assert(index >= 0, 'invalid attach index'); const parentNode = this.nodes.get(parentId); assert(parentNode, 'can not insert children under node that does not exist'); const mutableNodes = this.nodes.clone(); const traits = new Map(parentNode.traits); const trait = traits.get(label) ?? []; assert(index <= trait.length, 'invalid attach index'); // If there is nothing to insert, return early. // This is good for performance, but also avoids an edge case where an empty trait could be created (which is an error). if (childIds.length === 0) { return this; } const newChildren = [...trait.slice(0, index), ...childIds, ...trait.slice(index)]; traits.set(label, newChildren); mutableNodes.set(parentId, { ...parentNode, traits }); for (const childId of childIds) { mutableNodes.editRange(childId, childId, true, (_, n) => { assert(n.parentId === undefined, 'can not attach node that already has a parent'); const breakVal: { value: ForestNodeWithParentage } = { value: { ...n, parentId, traitParent: label, }, }; return breakVal; }); } return new Forest({ nodes: mutableNodes, expensiveValidation: this.expensiveValidation, }); } /** * Detaches a range of nodes from their parent. The detached nodes remain in the `Forest`. * @param parentId - the id of the parent from which to detach the nodes * @param label - the label of the trait from which to detach the nodes * @param startIndex - the index of the first node in the range to detach * @param endIndex - the index after the last node in the range to detach * @returns a new `Forest` with the nodes detached, and a list of the ids of the nodes that were detached */ public detachRangeOfChildren( parentId: NodeId, label: TraitLabel, startIndex: number, endIndex: number ): { forest: Forest; detached: readonly NodeId[] } { assert(startIndex >= 0 && endIndex >= startIndex, 'invalid detach index range'); const parentNode = this.nodes.get(parentId); assert(parentNode, 'can not detach children under node that does not exist'); if (startIndex === endIndex) { return { forest: this, detached: [] }; } const mutableNodes = this.nodes.clone(); const traits = new Map(parentNode.traits); const trait = traits.get(label) ?? []; assert(endIndex <= trait.length, 'invalid detach index range'); const detached: NodeId[] = trait.slice(startIndex, endIndex); const newChildren = [...trait.slice(0, startIndex), ...trait.slice(endIndex)]; const deleteTrait = newChildren.length === 0; if (deleteTrait) { traits.delete(label); } else { traits.set(label, newChildren); } mutableNodes.set(parentId, { ...parentNode, traits }); for (const childId of detached) { mutableNodes.editRange(childId, childId, true, (_, n) => { const breakVal: { value: ForestNodeWithParentage } = { value: { ...n, parentId: undefined, traitParent: undefined, }, }; return breakVal; }); } return { forest: new Forest({ nodes: mutableNodes, expensiveValidation: this.expensiveValidation, }), detached, }; } /** * Replaces a node's value. The node must exist in this `Forest`. * @param nodeId - the id of the node * @param value - the new value */ public setValue(nodeId: NodeId, value: Payload | null): Forest { const node = this.nodes.get(nodeId); assert(node, 'can not replace payload for node that does not exist'); const mutableNodes = this.nodes.clone(); const newNode = { ...node }; /* eslint-disable-next-line no-null/no-null */ if (value !== null) { newNode.payload = value; } else { delete newNode.payload; } mutableNodes.set(nodeId, newNode as ForestNodeWithParentage); return new Forest({ nodes: mutableNodes, expensiveValidation: this.expensiveValidation, }); } /** * @returns the node associated with `id`. Should not be used if there is no node with the provided id. */ public get(id: NodeId): ForestNode { return this.nodes.get(id) ?? fail('NodeId not found'); } /** * @returns the node associated with `id`, or undefined if there is none */ public tryGet(id: NodeId): ForestNode | undefined { return this.nodes.get(id); } /** * Deletes every node in ids (each of which must be unparented) * @param ids - The IDs of the nodes to delete. * @param deleteChildren - If true, recursively deletes descendants. Otherwise, leaves children unparented. */ public delete(ids: Iterable<NodeId>, deleteChildren: boolean): Forest { const mutableNodes = this.nodes.clone(); for (const id of ids) { this.deleteRecursive(mutableNodes, id, deleteChildren); } return new Forest({ nodes: mutableNodes, expensiveValidation: this.expensiveValidation, }); } private deleteRecursive( mutableNodes: BTree<NodeId, ForestNodeWithParentage>, id: NodeId, deleteChildren: boolean ): void { const node = mutableNodes.get(id) ?? fail('node to delete must exist'); assert(node.parentId === undefined && node.traitParent === undefined, 'deleted nodes must be unparented'); mutableNodes.delete(id); for (const trait of node.traits.values()) { for (const childId of trait) { mutableNodes.editRange(childId, childId, true, (_, n) => { const breakVal: { value: ForestNodeWithParentage } = { value: { ...n, parentId: undefined, traitParent: undefined, }, }; return breakVal; }); if (deleteChildren) { this.deleteRecursive(mutableNodes, childId, deleteChildren); } } } } /** * Checks that the metadata is correct, and the items form a forest. * This is an expensive O(map size) operation. */ public assertConsistent(): void { const checkedChildren = new Set<NodeId>([]); for (const [nodeId, node] of this.nodes.entries(undefined, [])) { assert( (node.parentId === undefined) === (node.traitParent === undefined), 'node must have either both parent and traitParent set or neither' ); if (node.parentId !== undefined && node.traitParent !== undefined) { const parent = this.get(node.parentId); const trait = parent.traits.get(node.traitParent); assert(trait !== undefined); assert(trait.indexOf(node.identifier) >= 0, 'node is parented incorrectly'); } for (const trait of node.traits.values()) { assert(trait.length > 0, 'trait is present but empty'); for (const childId of trait) { const child = this.nodes.get(childId); assert(child, 'child in trait is not in forest'); assert(child.parentId === node.identifier, 'child parent pointer is incorrect'); assert( !checkedChildren.has(childId), 'the item tree tree must not contain cycles or multi-parented nodes' ); assert( (child.parentId ?? fail('each node must have associated metadata')) === nodeId, 'cached parent is incorrect' ); checkedChildren.add(childId); } } } } /** * @returns the parent of `id`. Should not be used if there is no node with id or if id refers to the root node. */ public getParent(id: NodeId): ParentData { const child = this.nodes.get(id); if (child === undefined) { fail('NodeId not found'); } return { parentId: child.parentId ?? fail('Node is not parented'), traitParent: child.traitParent ?? fail('Node is not parented'), }; } /** * @returns undefined iff root, otherwise the parent of `id`. */ public tryGetParent(id: NodeId): ParentData | undefined { const child = this.nodes.get(id); if (child === undefined) { return undefined; } if (child.parentId === undefined || child.traitParent === undefined) { return undefined; } return { parentId: child.parentId, traitParent: child.traitParent, }; } private static breakOnDifference(): { break: boolean } { return { break: true }; } /** * Compares two forests for equality. * @param forest - the other forest to compare to this one * @param comparator - a function which returns true if two objects of type ForestNode are equivalent, false otherwise * @returns true iff the forests are equal. */ public equals(forest: Forest): boolean { if (this === forest || this.nodes === forest.nodes) { return true; } if (forest.size !== this.size) { return false; } const diff = this.nodes.diffAgainst( forest.nodes, Forest.breakOnDifference, Forest.breakOnDifference, (_, nodeThis, nodeOther) => { if (!compareForestNodes(nodeThis, nodeOther)) { return { break: true }; } return undefined; } ); return diff === undefined; } /** * Calculate the difference between two forests. * @param forest - the other forest to compare to this one * @param comparator - a function which returns true if two objects of type ForestNode are equivalent, false otherwise * @returns A {@link Delta} listing which nodes must be changed, added, and removed to get from `this` to `forest`. */ public delta(forest: Forest): Delta<NodeId> { const changed: NodeId[] = []; const removed: NodeId[] = []; const added: NodeId[] = []; this.nodes.diffAgainst( forest.nodes, (id) => { removed.push(id); }, (id) => { added.push(id); }, (id, nodeThis, nodeOther) => { if (!compareForestNodes(nodeThis, nodeOther)) { changed.push(id); } } ); return { changed, added, removed, }; } } /** * @returns true iff two `SnapshotNodes` are equivalent. * May return false for nodes they contain equivalent payloads encoded differently. */ export function compareForestNodes(nodeA: ForestNode, nodeB: ForestNode): boolean { if (nodeA === nodeB) { return true; } if (nodeA.identifier !== nodeB.identifier) { return false; } if (nodeA.definition !== nodeB.definition) { return false; } if (!comparePayloads(nodeA.payload, nodeB.payload)) { return false; } if (nodeA.traits.size !== nodeB.traits.size) { return false; } for (const traitA of nodeA.traits) { const [traitLabelA, nodeSequenceA] = traitA; const nodeSequenceB = nodeB.traits.get(traitLabelA); if (!nodeSequenceB) { return false; } if (nodeSequenceA.length !== nodeSequenceB.length) { return false; } for (let i = 0; i < nodeSequenceA.length; i++) { if (nodeSequenceA[i] !== nodeSequenceB[i]) { return false; } } } return true; }
the_stack
import path from 'path' import { renderMarkdown } from './util' interface HandlebarData { packageName?: string packageDirectory?: string shortPackageName?: string tokenizerName: string tokenizerPriority: string inGfm?: boolean inGfmEx?: boolean isInlineTokenizer: boolean isBlockTokenizer: boolean usageDemoSourceContent: string } const items: HandlebarData[] = [ // admonition { tokenizerName: 'admonition', tokenizerPriority: 'TokenizerPriority.FENCED_BLOCK', isInlineTokenizer: false, isBlockTokenizer: true, usageDemoSourceContent: `\` :::info this is a info type admonition waw ### some block contents ::: \``, }, // autolink { tokenizerName: 'autolink', tokenizerPriority: 'TokenizerPriority.ATOMIC', inGfm: true, inGfmEx: true, isInlineTokenizer: true, isBlockTokenizer: false, usageDemoSourceContent: `\` <foo@bar.example.com> <http://foo.bar.baz> <made-up-scheme://foo,bar> \``, }, // autolink-extension { tokenizerName: 'autolink-extension', tokenizerPriority: 'TokenizerPriority.ATOMIC', inGfm: false, inGfmEx: true, isInlineTokenizer: true, isBlockTokenizer: false, usageDemoSourceContent: `\` foo@bar.example.com http://foo.bar.baz made-up-scheme://foo,bar \``, }, // blockquote { tokenizerName: 'blockquote', tokenizerPriority: 'TokenizerPriority.CONTAINING_BLOCK', inGfm: true, inGfmEx: true, isInlineTokenizer: false, isBlockTokenizer: true, usageDemoSourceContent: `\` > This is blockquote > - with some list contents > - apple > > ## A cat in heading \``, }, // break { tokenizerName: 'break', tokenizerPriority: 'TokenizerPriority.ATOMIC', inGfm: true, inGfmEx: true, isInlineTokenizer: true, isBlockTokenizer: false, usageDemoSourceContent: `\` foo baz foo\\ baz foo baz \``, }, // definition { tokenizerName: 'definition', tokenizerPriority: 'TokenizerPriority.ATOMIC', inGfm: true, inGfmEx: true, isInlineTokenizer: false, isBlockTokenizer: true, usageDemoSourceContent: `\` [foo]: /url ' title line1 line2 ' [foo] \``, }, // delete { tokenizerName: 'delete', tokenizerPriority: 'TokenizerPriority.CONTAINING_INLINE', inGfm: false, inGfmEx: true, isInlineTokenizer: true, isBlockTokenizer: false, usageDemoSourceContent: `\` This ~~has a new paragraph~~. \``, }, // ecmaImport { tokenizerName: 'ecma-import', tokenizerPriority: 'TokenizerPriority.ATOMIC', inGfm: false, inGfmEx: false, isInlineTokenizer: false, isBlockTokenizer: true, usageDemoSourceContent: `\` import { Parser } from '@yozora/parser' import { Button } from '@material-ui/core' import Markdown from '@yozora/react-markdown' \``, }, // emphasis { tokenizerName: 'emphasis', tokenizerPriority: 'TokenizerPriority.CONTAINING_INLINE', inGfm: true, inGfmEx: true, isInlineTokenizer: true, isBlockTokenizer: false, usageDemoSourceContent: `\` **foo bar** __foo bar__ _foo bar_ *foo bar* __**__foo__**__ \``, }, // fenced-block { tokenizerName: 'fenced-block', tokenizerPriority: 'TokenizerPriority.FENCED_BLOCK', inGfm: true, inGfmEx: true, isInlineTokenizer: false, isBlockTokenizer: true, usageDemoSourceContent: `"source contents"`, }, // fenced-code { tokenizerName: 'fenced-code', tokenizerPriority: 'TokenizerPriority.FENCED_BLOCK', inGfm: true, inGfmEx: true, isInlineTokenizer: false, isBlockTokenizer: true, usageDemoSourceContent: `\` \\\`\\\`\\\`ruby def foo(x) return 3 end \\\`\\\`\\\` ~~~typescript export const foo: string = 'waw' ~~~ # baz \``, }, // footnote { tokenizerName: 'footnote', tokenizerPriority: 'TokenizerPriority.LINKS', inGfm: false, inGfmEx: false, isInlineTokenizer: true, isBlockTokenizer: false, usageDemoSourceContent: `\` ^[inline footnote] ^[footnote with *emphasis* and $x^2+y^2$ and \`inline code\`] \``, }, // footnote-definition { tokenizerName: 'footnote-definition', tokenizerPriority: 'TokenizerPriority.ATOMIC', inGfm: false, inGfmEx: false, isInlineTokenizer: false, isBlockTokenizer: true, usageDemoSourceContent: `\` Here is a footnote reference,[^1] another,[^long note], [^big footnote]: Here's one with multiple paragraphs and code. Indent paragraphs to include them in the footnote. \\\`\\\`\\\` Fenced coding \\\`\\\`\\\` ## heading Add as many paragraphs as you like. \``, }, // footnote-reference { tokenizerName: 'footnote-reference', tokenizerPriority: 'TokenizerPriority.ATOMIC', inGfm: false, inGfmEx: false, isInlineTokenizer: true, isBlockTokenizer: false, usageDemoSourceContent: `\` Here is a footnote reference,[^1] another,[^long note], [^big footnote]: Here's one with multiple paragraphs and code. Indent paragraphs to include them in the footnote. \\\`\\\`\\\` Fenced coding \\\`\\\`\\\` ## heading Add as many paragraphs as you like. \``, }, // heading { tokenizerName: 'heading', tokenizerPriority: 'TokenizerPriority.ATOMIC', inGfm: true, inGfmEx: true, isInlineTokenizer: false, isBlockTokenizer: true, usageDemoSourceContent: `\` # h1 ## h2 ### h3 #### h4 ##### h5 ###### h6 \``, }, // html-block { tokenizerName: 'html-block', tokenizerPriority: 'TokenizerPriority.ATOMIC', inGfm: true, inGfmEx: true, isInlineTokenizer: false, isBlockTokenizer: true, usageDemoSourceContent: `\` <pre language="haskell"><code> import Text.HTML.TagSoup main :: IO () main = print $ parseTags tags </code></pre> okay \``, }, // html-inline { tokenizerName: 'html-inline', tokenizerPriority: 'TokenizerPriority.ATOMIC', inGfm: true, inGfmEx: true, isInlineTokenizer: true, isBlockTokenizer: false, usageDemoSourceContent: `\` <a><bab><c2c> foo <?php echo $a; ?> \``, }, // image { tokenizerName: 'image', tokenizerPriority: 'TokenizerPriority.LINKS', inGfm: true, inGfmEx: true, isInlineTokenizer: true, isBlockTokenizer: false, usageDemoSourceContent: `\` ![foo](/url "title") \``, }, // image-reference { tokenizerName: 'image-reference', tokenizerPriority: 'TokenizerPriority.LINKS', inGfm: true, inGfmEx: true, isInlineTokenizer: true, isBlockTokenizer: false, usageDemoSourceContent: `\` ![foo][] [foo]: /url "title" \``, }, // indented-code { tokenizerName: 'indented-code', tokenizerPriority: 'TokenizerPriority.ATOMIC', inGfm: true, inGfmEx: true, isInlineTokenizer: false, isBlockTokenizer: true, usageDemoSourceContent: `\` <a/> *hi* - one \``, }, // inline-code { tokenizerName: 'inline-code', tokenizerPriority: 'TokenizerPriority.ATOMIC', inGfm: true, inGfmEx: true, isInlineTokenizer: true, isBlockTokenizer: false, usageDemoSourceContent: '"`inline code`"', }, // inline-math { tokenizerName: 'inline-math', tokenizerPriority: 'TokenizerPriority.ATOMIC', inGfm: false, inGfmEx: false, isInlineTokenizer: true, isBlockTokenizer: false, usageDemoSourceContent: '"`$x^2 + y^2 = z^2, x < 0$`"', }, // link { tokenizerName: 'link', tokenizerPriority: 'TokenizerPriority.LINKS', inGfm: true, inGfmEx: true, isInlineTokenizer: true, isBlockTokenizer: false, usageDemoSourceContent: `\` [link](/uri "title") [link](/uri) \``, }, // link-reference { tokenizerName: 'link-reference', tokenizerPriority: 'TokenizerPriority.LINKS', inGfm: true, inGfmEx: true, isInlineTokenizer: true, isBlockTokenizer: false, usageDemoSourceContent: `\` [foo][bar] [bar]: /url "title" \``, }, // list { tokenizerName: 'list', tokenizerPriority: 'TokenizerPriority.CONTAINING_BLOCK', inGfm: true, inGfmEx: true, isInlineTokenizer: false, isBlockTokenizer: true, usageDemoSourceContent: `\` - a - b - c - d - e - f - g --- - [ ] This is a TODO item. - [-] This is a processing TODO item. - [x] This is a finished TODO item. --- 1. This is an ordered list item a. This is an another type of ordered list item \``, }, // list-item { tokenizerName: 'list-item', tokenizerPriority: 'TokenizerPriority.CONTAINING_BLOCK', inGfm: true, inGfmEx: true, isInlineTokenizer: false, isBlockTokenizer: true, usageDemoSourceContent: `\` - a - b - c - d - e - f - g --- - [ ] This is a TODO item. - [-] This is a processing TODO item. - [x] This is a finished TODO item. --- 1. This is an ordered list item a. This is an another type of ordered list item \``, }, // math { tokenizerName: 'math', tokenizerPriority: 'TokenizerPriority.FENCED_BLOCK', inGfm: false, inGfmEx: false, isInlineTokenizer: false, isBlockTokenizer: true, usageDemoSourceContent: `\` $$x^2 + y^2=z^2$$ $$ f(x)=\\left\\lbrace\\begin{aligned} &x^2, &x < 0\\\\ &0, &x = 0\\\\ &x^3, &x > 0 \\end{aligned}\\right. $$ \``, }, // paragraph { tokenizerName: 'paragraph', tokenizerPriority: 'TokenizerPriority.FALLBACK', inGfm: true, inGfmEx: true, isInlineTokenizer: false, isBlockTokenizer: true, usageDemoSourceContent: `\` aaa bbb \``, }, // setext-heading { tokenizerName: 'setext-heading', tokenizerPriority: 'TokenizerPriority.ATOMIC', inGfm: true, inGfmEx: true, isInlineTokenizer: false, isBlockTokenizer: true, usageDemoSourceContent: `\` Foo *bar* ========= Foo *bar* --------- \``, }, // table { tokenizerName: 'table', tokenizerPriority: 'TokenizerPriority.INTERRUPTABLE_BLOCK', inGfm: false, inGfmEx: true, isInlineTokenizer: false, isBlockTokenizer: true, usageDemoSourceContent: `\` | foo | bar | | --- | --- | | baz | bim | \``, }, // text { tokenizerName: 'text', tokenizerPriority: 'TokenizerPriority.FALLBACK', inGfm: true, inGfmEx: true, isInlineTokenizer: true, isBlockTokenizer: false, usageDemoSourceContent: `"hello $.;'there"`, }, // thematic-break { tokenizerName: 'thematic-break', tokenizerPriority: 'TokenizerPriority.ATOMIC', inGfm: true, inGfmEx: true, isInlineTokenizer: false, isBlockTokenizer: true, usageDemoSourceContent: `\` *** --- ___ \``, }, ] // Perform replace items.forEach((item): void => { const data = item data.packageDirectory ??= 'tokenizers/' + data.tokenizerName const docFilepath = path.join(__dirname, '../../', data.packageDirectory, 'README.md') data.packageName ??= `@yozora/tokenizer-${data.tokenizerName}` data.shortPackageName ??= `tokenizer-${data.tokenizerName}` data.inGfm ??= false data.inGfmEx ??= false renderMarkdown<HandlebarData>(docFilepath, data) })
the_stack
import { emitMempoolInfo, dropWebSocket } from "../../support/websocket"; const baseModule = Cypress.env("BASE_MODULE"); //Credit: https://github.com/bahmutov/cypress-examples/blob/6cedb17f83a3bb03ded13cf1d6a3f0656ca2cdf5/docs/recipes/overlapping-elements.md /** * Returns true if two DOM rectangles are overlapping * @param {DOMRect} rect1 the bounding client rectangle of the first element * @param {DOMRect} rect2 the bounding client rectangle of the second element * @returns {boolean} */ const areOverlapping = (rect1, rect2) => { // if one rectangle is on the left side of the other if (rect1.right < rect2.left || rect2.right < rect1.left) { return false } // if one rectangle is above the other if (rect1.bottom < rect2.top || rect2.bottom < rect1.top) { return false } // the rectangles must overlap return true } /** * Returns the bounding rectangle of the first DOM * element in the given jQuery object. */ const getRectangle = ($el) => $el[0].getBoundingClientRect(); describe('Mainnet', () => { beforeEach(() => { //cy.intercept('/sockjs-node/info*').as('socket'); cy.intercept('/api/block-height/*').as('block-height'); cy.intercept('/api/block/*').as('block'); cy.intercept('/api/block/*/txs/0').as('block-txs'); cy.intercept('/api/tx/*/outspends').as('tx-outspends'); cy.intercept('/resources/pools.json').as('pools'); // Search Auto Complete cy.intercept('/api/address-prefix/1wiz').as('search-1wiz'); cy.intercept('/api/address-prefix/1wizS').as('search-1wizS'); cy.intercept('/api/address-prefix/1wizSA').as('search-1wizSA'); Cypress.Commands.add('waitForBlockData', () => { cy.wait('@tx-outspends'); cy.wait('@pools'); }); }); if (baseModule === 'mempool') { it('check first mempool block after skeleton loads', () => { cy.visit('/'); cy.waitForSkeletonGone(); cy.get('#mempool-block-0 > .blockLink').should('exist'); }); it('loads the status screen', () => { cy.visit('/status'); cy.get('#mempool-block-0').should('be.visible'); cy.get('[id^="bitcoin-block-"]').should('have.length', 8); cy.get('.footer').should('be.visible'); cy.get('.row > :nth-child(1)').invoke('text').then((text) => { expect(text).to.match(/Incoming transactions.* vB\/s/); }); cy.get('.row > :nth-child(2)').invoke('text').then((text) => { expect(text).to.match(/Unconfirmed:(.*)/); }); cy.get('.row > :nth-child(3)').invoke('text').then((text) => { expect(text).to.match(/Mempool size:(.*) (kB|MB) \((\d+) (block|blocks)\)/); }); }); //TODO: This test is flaky, refactor later it.skip('loads dashboard, drop websocket and reconnect', () => { cy.viewport('macbook-16'); cy.mockMempoolSocket(); cy.visit('/'); cy.get('.badge').should('not.exist'); dropWebSocket(); cy.get('.badge').should('be.visible'); cy.get('.badge', { timeout: 25000 }).should('not.exist'); emitMempoolInfo({ 'params': { command: 'init' } }); cy.get(':nth-child(1) > #bitcoin-block-0').should('not.exist'); cy.get(':nth-child(2) > #bitcoin-block-0').should('not.exist'); cy.get(':nth-child(3) > #bitcoin-block-0').should('not.exist'); }); it('loads the dashboard', () => { cy.visit('/'); cy.waitForSkeletonGone(); }); it('check op_return tx tooltip', () => { cy.visit('/block/00000000000000000003c5f542bed265319c6cf64238cf1f1bb9bca3ebf686d2'); cy.waitForSkeletonGone(); cy.get('tbody > :nth-child(2) > :nth-child(1) > a').first().trigger('onmouseover'); cy.get('tbody > :nth-child(2) > :nth-child(1) > a').first().trigger('mouseenter'); cy.get('.tooltip-inner').should('be.visible'); }); it('check op_return coinbase tooltip', () => { cy.visit('/block/00000000000000000003c5f542bed265319c6cf64238cf1f1bb9bca3ebf686d2'); cy.waitForSkeletonGone(); cy.get('div > a > .badge').first().trigger('onmouseover'); cy.get('div > a > .badge').first().trigger('mouseenter'); cy.get('.tooltip-inner').should('be.visible'); }); describe('search', () => { it('allows searching for partial Bitcoin addresses', () => { cy.visit('/'); cy.get('.search-box-container > .form-control').type('1wiz').then(() => { cy.wait('@search-1wiz'); cy.get('ngb-typeahead-window button.dropdown-item').should('have.length', 10); }); cy.get('.search-box-container > .form-control').type('S').then(() => { cy.wait('@search-1wizS'); cy.get('ngb-typeahead-window button.dropdown-item').should('have.length', 5); }); cy.get('.search-box-container > .form-control').type('A').then(() => { cy.wait('@search-1wizSA'); cy.get('ngb-typeahead-window button.dropdown-item').should('have.length', 1) }); cy.get('ngb-typeahead-window button.dropdown-item.active').click().then(() => { cy.url().should('include', '/address/1wizSAYSbuyXbt9d8JV8ytm5acqq2TorC'); cy.waitForSkeletonGone(); cy.get('.text-center').should('not.have.text', 'Invalid Bitcoin address'); }); }); ['BC1PQYQSZQ', 'bc1PqYqSzQ'].forEach((searchTerm) => { it(`allows searching for partial case insensitive bech32m addresses: ${searchTerm}`, () => { cy.visit('/'); cy.get('.search-box-container > .form-control').type(searchTerm).then(() => { cy.get('ngb-typeahead-window button.dropdown-item').should('have.length', 1); cy.get('ngb-typeahead-window button.dropdown-item.active').click().then(() => { cy.url().should('include', '/address/bc1pqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsyjer9e'); cy.waitForSkeletonGone(); cy.get('.text-center').should('not.have.text', 'Invalid Bitcoin address'); }); }); }); }); ['BC1Q000375VXCU', 'bC1q000375vXcU'].forEach((searchTerm) => { it(`allows searching for partial case insensitive bech32 addresses: ${searchTerm}`, () => { cy.visit('/'); cy.get('.search-box-container > .form-control').type(searchTerm).then(() => { cy.get('ngb-typeahead-window button.dropdown-item').should('have.length', 1); cy.get('ngb-typeahead-window button.dropdown-item.active').click().then(() => { cy.url().should('include', '/address/bc1q000375vxcuf5v04lmwy22vy2thvhqkxghgq7dy'); cy.waitForSkeletonGone(); cy.get('.text-center').should('not.have.text', 'Invalid Bitcoin address'); }); }); }); }); }); describe('address highlighting', () => { it('highlights single input addresses', () => { const address = '1wiz32gbHZwMzJCRHMGehJuBgsMTPdaCa'; cy.visit(`/address/${address}`); cy.waitForSkeletonGone(); cy.get('[data-cy="tx-0"] .table-tx-vin .highlight').should('exist'); cy.get('[data-cy="tx-0"] .table-tx-vin .highlight').invoke('text').should('contain', `${address}`); }); it('highlights multiple input addresses', () => { const address = '1wiz1rtKFBA58qjb582WF5KAFg9mWCuZV'; cy.visit(`/address/${address}`); cy.waitForSkeletonGone(); cy.get('[data-cy="tx-2"] .table-tx-vin .highlight').should('exist'); cy.get('[data-cy="tx-2"] .table-tx-vin .highlight').its('length').should('equal', 2); cy.get('[data-cy="tx-2"] .table-tx-vin .highlight').invoke('text').should('contain', `${address}`); }); it('highlights both input and output addresses in the same transaction', () => { const address = 'bc1q03u63r6hm7a3v6em58zdqtp446w2pw30nm63mv'; cy.visit(`/address/${address}`); cy.waitForSkeletonGone(); cy.get('[data-cy="tx-1"] .table-tx-vin .highlight').should('exist'); cy.get('[data-cy="tx-1"] .table-tx-vout .highlight').should('exist'); }); it('highlights single output addresses', () => { const address = '1wiz32gbHZwMzJCRHMGehJuBgsMTPdaCa'; cy.visit(`/address/${address}`); cy.waitForSkeletonGone(); cy.get('[data-cy="tx-1"] .table-tx-vout .highlight').should('exist'); cy.get('[data-cy="tx-1"] .table-tx-vout .highlight').invoke('text').should('contain', `${address}`); }); it('highlights multiple output addresses', () => { const address = '1F3Q3sQmiGsWSqK5K6T9tYnX8yqzYRgQbe'; cy.visit(`/address/${address}`); cy.waitForSkeletonGone(); cy.get('[data-cy="tx-1"] .table-tx-vout .highlight').should('exist'); cy.get('[data-cy="tx-1"] .table-tx-vout .highlight').its('length').should('equal', 2); cy.get('[data-cy="tx-1"] .table-tx-vout .highlight').invoke('text').should('contain', `${address}`); }); }); describe('blocks navigation', () => { describe('keyboard events', () => { it('loads first blockchain blocks visible and keypress arrow right', () => { cy.viewport('macbook-16'); cy.visit('/'); cy.waitForSkeletonGone(); cy.get('.blockchain-blocks-0 > a').click().then(() => { cy.get('[ngbtooltip="Next Block"] > .ng-fa-icon > .svg-inline--fa').should('not.exist'); cy.get('[ngbtooltip="Previous Block"] > .ng-fa-icon > .svg-inline--fa').should('be.visible'); cy.waitForPageIdle(); cy.document().right(); cy.get('[ngbtooltip="Next Block"] > .ng-fa-icon > .svg-inline--fa').should('be.visible'); cy.get('[ngbtooltip="Previous Block"] > .ng-fa-icon > .svg-inline--fa').should('be.visible'); }); }); it('loads first blockchain blocks visible and keypress arrow left', () => { cy.viewport('macbook-16'); cy.visit('/'); cy.waitForSkeletonGone(); cy.get('.blockchain-blocks-0 > a').click().then(() => { cy.waitForPageIdle(); cy.get('[ngbtooltip="Next Block"] > .ng-fa-icon > .svg-inline--fa').should('not.exist'); cy.get('[ngbtooltip="Previous Block"] > .ng-fa-icon > .svg-inline--fa').should('be.visible'); cy.document().left(); cy.get('.title-block h1').invoke('text').should('equal', 'Next Block'); }); }); it('loads last blockchain blocks and keypress arrow right', () => { cy.viewport('macbook-16'); cy.visit('/'); cy.waitForSkeletonGone(); cy.get('.blockchain-blocks-4 > a').click().then(() => { cy.waitForPageIdle(); // block 6 cy.document().right(); cy.wait(5000); cy.get('[ngbtooltip="Next Block"] > .ng-fa-icon > .svg-inline--fa').should('be.visible'); cy.get('[ngbtooltip="Previous Block"] > .ng-fa-icon > .svg-inline--fa').should('be.visible'); // block 7 cy.document().right(); cy.wait(5000); cy.get('[ngbtooltip="Next Block"] > .ng-fa-icon > .svg-inline--fa').should('be.visible'); cy.get('[ngbtooltip="Previous Block"] > .ng-fa-icon > .svg-inline--fa').should('be.visible'); // block 8 - last visible block cy.document().right(); cy.wait(5000); cy.get('[ngbtooltip="Next Block"] > .ng-fa-icon > .svg-inline--fa').should('be.visible'); cy.get('[ngbtooltip="Previous Block"] > .ng-fa-icon > .svg-inline--fa').should('be.visible'); // block 9 - not visible at the blochchain blocks visible block cy.document().right(); cy.wait(5000); cy.get('[ngbtooltip="Next Block"] > .ng-fa-icon > .svg-inline--fa').should('be.visible'); cy.get('[ngbtooltip="Previous Block"] > .ng-fa-icon > .svg-inline--fa').should('be.visible'); }); }); it('loads genesis block and keypress arrow right', () => { cy.viewport('macbook-16'); cy.visit('/block/0'); cy.waitForSkeletonGone(); cy.waitForPageIdle(); cy.document().right(); cy.wait(5000); cy.get('[ngbtooltip="Next Block"] > .ng-fa-icon > .svg-inline--fa').should('be.visible'); cy.get('[ngbtooltip="Previous Block"] > .ng-fa-icon > .svg-inline--fa').should('not.exist'); }); it('loads genesis block and keypress arrow left', () => { cy.viewport('macbook-16'); cy.visit('/block/0'); cy.waitForSkeletonGone(); cy.waitForPageIdle(); cy.document().left(); cy.wait(5000); cy.get('[ngbtooltip="Next Block"] > .ng-fa-icon > .svg-inline--fa').should('be.visible'); cy.get('[ngbtooltip="Previous Block"] > .ng-fa-icon > .svg-inline--fa').should('be.visible'); }); }); describe('mouse events', () => { it('loads first blockchain blocks visible and click on the arrow right', () => { cy.viewport('macbook-16'); cy.visit('/'); cy.waitForSkeletonGone(); cy.get('.blockchain-blocks-0 > a').click().then(() => { cy.waitForPageIdle(); cy.get('[ngbtooltip="Next Block"] > .ng-fa-icon > .svg-inline--fa').should('not.exist'); cy.get('[ngbtooltip="Previous Block"] > .ng-fa-icon > .svg-inline--fa').should('be.visible'); cy.get('[ngbtooltip="Previous Block"] > .ng-fa-icon > .svg-inline--fa').click().then(() => { cy.get('[ngbtooltip="Next Block"] > .ng-fa-icon > .svg-inline--fa').should('be.visible'); cy.get('[ngbtooltip="Previous Block"] > .ng-fa-icon > .svg-inline--fa').should('be.visible'); }); }); }); it('loads genesis block and click on the arrow left', () => { cy.viewport('macbook-16'); cy.visit('/block/0'); cy.waitForSkeletonGone(); cy.waitForPageIdle(); cy.get('[ngbtooltip="Next Block"] > .ng-fa-icon > .svg-inline--fa').should('be.visible'); cy.get('[ngbtooltip="Previous Block"] > .ng-fa-icon > .svg-inline--fa').should('not.exist'); cy.get('[ngbtooltip="Next Block"] > .ng-fa-icon > .svg-inline--fa').click().then(() => { cy.get('[ngbtooltip="Next Block"] > .ng-fa-icon > .svg-inline--fa').should('be.visible'); cy.get('[ngbtooltip="Previous Block"] > .ng-fa-icon > .svg-inline--fa').should('be.visible'); }); }); }); }); it('loads skeleton when changes between networks', () => { cy.visit('/'); cy.waitForSkeletonGone(); cy.changeNetwork("testnet"); cy.changeNetwork("signet"); cy.changeNetwork("mainnet"); }); it.skip('loads the dashboard with the skeleton blocks', () => { cy.mockMempoolSocket(); cy.visit("/"); cy.get(':nth-child(1) > #bitcoin-block-0').should('be.visible'); cy.get(':nth-child(2) > #bitcoin-block-0').should('be.visible'); cy.get(':nth-child(3) > #bitcoin-block-0').should('be.visible'); cy.get('#mempool-block-0').should('be.visible'); cy.get('#mempool-block-1').should('be.visible'); cy.get('#mempool-block-2').should('be.visible'); emitMempoolInfo({ 'params': { command: 'init' } }); cy.get(':nth-child(1) > #bitcoin-block-0').should('not.exist'); cy.get(':nth-child(2) > #bitcoin-block-0').should('not.exist'); cy.get(':nth-child(3) > #bitcoin-block-0').should('not.exist'); }); it('loads the pools screen', () => { cy.visit('/'); cy.waitForSkeletonGone(); cy.get('#btn-pools').click().then(() => { cy.wait(1000); }); }); it('loads the graphs screen', () => { cy.visit('/'); cy.waitForSkeletonGone(); cy.get('#btn-graphs').click().then(() => { cy.wait(1000); }); }); describe('graphs page', () => { it('check buttons - mobile', () => { cy.viewport('iphone-6'); cy.visit('/graphs'); cy.waitForSkeletonGone(); cy.get('.small-buttons > :nth-child(2)').should('be.visible'); cy.get('#dropdownFees').should('be.visible'); cy.get('.btn-group').should('be.visible'); }); it('check buttons - tablet', () => { cy.viewport('ipad-2'); cy.visit('/graphs'); cy.waitForSkeletonGone(); cy.get('.small-buttons > :nth-child(2)').should('be.visible'); cy.get('#dropdownFees').should('be.visible'); cy.get('.btn-group').should('be.visible'); }); it('check buttons - desktop', () => { cy.viewport('macbook-16'); cy.visit('/graphs'); cy.waitForSkeletonGone(); cy.get('.small-buttons > :nth-child(2)').should('be.visible'); cy.get('#dropdownFees').should('be.visible'); cy.get('.btn-group').should('be.visible'); }); }); it('loads the tv screen - desktop', () => { cy.viewport('macbook-16'); cy.visit('/'); cy.waitForSkeletonGone(); cy.get('#btn-tv').click().then(() => { cy.viewport('macbook-16'); cy.get('.chart-holder'); cy.get('.blockchain-wrapper').should('be.visible'); cy.get('#mempool-block-0').should('be.visible'); }); }); it('loads the tv screen - mobile', () => { cy.viewport('iphone-6'); cy.visit('/tv'); cy.waitForSkeletonGone(); cy.get('.chart-holder'); cy.get('.blockchain-wrapper').should('not.visible'); }); it('loads the api screen', () => { cy.visit('/'); cy.waitForSkeletonGone(); cy.get('#btn-docs').click().then(() => { cy.wait(1000); }); }); describe('blocks', () => { it('shows empty blocks properly', () => { cy.visit('/block/0000000000000000000bd14f744ef2e006e61c32214670de7eb891a5732ee775'); cy.waitForSkeletonGone(); cy.waitForPageIdle(); cy.get('h2').invoke('text').should('equal', '1 transaction'); }); it('expands and collapses the block details', () => { cy.visit('/block/0'); cy.waitForSkeletonGone(); cy.waitForPageIdle(); cy.get('.btn.btn-outline-info').click().then(() => { cy.get('#details').should('be.visible'); }); cy.get('.btn.btn-outline-info').click().then(() => { cy.get('#details').should('not.be.visible'); }); }); it('shows blocks with no pagination', () => { cy.visit('/block/00000000000000000001ba40caf1ad4cec0ceb77692662315c151953bfd7c4c4'); cy.waitForSkeletonGone(); cy.waitForPageIdle(); cy.get('.block-tx-title h2').invoke('text').should('equal', '19 transactions'); cy.get('.pagination-container ul.pagination').first().children().should('have.length', 5); }); it('supports pagination on the block screen', () => { // 41 txs cy.visit('/block/00000000000000000009f9b7b0f63ad50053ad12ec3b7f5ca951332f134f83d8'); cy.waitForSkeletonGone(); cy.get('.pagination-container a').invoke('text').then((text1) => { cy.get('.active + li').first().click().then(() => { cy.waitForSkeletonGone(); cy.waitForPageIdle(); cy.get('.header-bg.box > a').invoke('text').then((text2) => { expect(text1).not.to.eq(text2); }); }); }); }); it('shows blocks pagination with 5 pages (desktop)', () => { cy.viewport(760, 800); cy.visit('/block/000000000000000000049281946d26fcba7d99fdabc1feac524bc3a7003d69b3').then(() => { cy.waitForSkeletonGone(); cy.waitForPageIdle(); }); // 5 pages + 4 buttons = 9 buttons cy.get('.pagination-container ul.pagination').first().children().should('have.length', 9); }); it('shows blocks pagination with 3 pages (mobile)', () => { cy.viewport(669, 800); cy.visit('/block/000000000000000000049281946d26fcba7d99fdabc1feac524bc3a7003d69b3').then(() => { cy.waitForSkeletonGone(); cy.waitForPageIdle(); }); // 3 pages + 4 buttons = 7 buttons cy.get('.pagination-container ul.pagination').first().children().should('have.length', 7); }); }); describe('RBF transactions', () => { it('shows RBF transactions properly (mobile)', () => { cy.viewport('iphone-xr'); cy.mockMempoolSocket(); cy.visit('/tx/f81a08699b62b2070ad8fe0f2a076f8bea0386a2fdcd8124caee42cbc564a0d5'); cy.waitForSkeletonGone(); emitMempoolInfo({ 'params': { command: 'init' } }); cy.get('#mempool-block-0'); emitMempoolInfo({ 'params': { command: 'rbfTransaction' } }); cy.get('.alert-mempool').should('be.visible'); cy.get('.alert-mempool').invoke('css', 'width').then((alertWidth) => { cy.get('.container-xl > :nth-child(3)').invoke('css', 'width').should('equal', alertWidth); }); cy.get('.btn-success').then(getRectangle).then((rectA) => { cy.get('.alert-mempool').then(getRectangle).then((rectB) => { expect(areOverlapping(rectA, rectB), 'Confirmations box and RBF alert are overlapping').to.be.false; }); }); }); it('shows RBF transactions properly (desktop)', () => { cy.viewport('macbook-16'); cy.mockMempoolSocket(); cy.visit('/tx/f81a08699b62b2070ad8fe0f2a076f8bea0386a2fdcd8124caee42cbc564a0d5'); cy.waitForSkeletonGone(); emitMempoolInfo({ 'params': { command: 'init' } }); cy.get('#mempool-block-0'); emitMempoolInfo({ 'params': { command: 'rbfTransaction' } }); cy.get('.alert-mempool').should('be.visible'); const alertLocator = '.alert-mempool'; const tableLocator = '.container-xl > :nth-child(3)'; cy.get(tableLocator).invoke('css', 'width').then((firstWidth) => { cy.get(alertLocator).invoke('css', 'width').should('equal', firstWidth); }); cy.get('.btn-success').then(getRectangle).then((rectA) => { cy.get('.alert-mempool').then(getRectangle).then((rectB) => { expect(areOverlapping(rectA, rectB), 'Confirmations box and RBF alert are overlapping').to.be.false; }); }); }); }); } else { it.skip(`Tests cannot be run on the selected BASE_MODULE ${baseModule}`); } });
the_stack
import { left, right, leftStopAtNewLines, chompLeft } from "string-left-right"; import { fixEnt } from "string-fix-broken-named-entities"; import { removeWidows } from "string-remove-widows"; import { rProcessOutside } from "ranges-process-outside"; import { collapse } from "string-collapse-white-space"; import { trimSpaces } from "string-trim-spaces-only"; import { stripHtml, CbObj } from "string-strip-html"; import { rInvert } from "ranges-invert"; import { rApply } from "ranges-apply"; import ansiRegex from "ansi-regex"; import { Ranges } from "ranges-push"; import he from "he"; import { version as v } from "../package.json"; const version: string = v; import { processCharacter } from "./processCharacter"; import { removeTrailingSlash, defaultOpts, Opts, State, Res, voidTags, isLetter, isNumber, isLowercaseLetter, rawMDash, EndOfLineVal, rightSingleQuote, ApplicableOpts, } from "./util"; // import escape from "js-string-escape"; /** * Extracts, cleans and encodes text */ function det(str: string, inputOpts?: Partial<Opts>): Res { // // input validation // --------------------------------------------------------------------------- if (typeof str !== "string") { throw new Error( `detergent(): [THROW_ID_01] the first input argument must be of a string type, not ${typeof str}` ); } if (inputOpts && typeof inputOpts !== "object") { throw new Error( `detergent(): [THROW_ID_02] Options object must be a plain object, not ${typeof inputOpts}` ); } if (inputOpts && inputOpts.cb && typeof inputOpts.cb !== "function") { throw new Error( `detergent(): [THROW_ID_03] Options callback, opts.cb must be a function, not ${typeof inputOpts.cb} (value was given as:\n${JSON.stringify( inputOpts.cb, null, 0 )})` ); } const opts = { ...defaultOpts, ...inputOpts }; if (!["lf", "crlf", "cr"].includes(opts.eol)) { opts.eol = "lf"; } // prepare applicable rules object. It is a clone of the default opts object // (which comes from util.js), where for starters all values are turned off, // then upon traversal, each applicable rule sets the key to true, it does not // matter, rule is enabled in opts or not. We just mark that particular // options setting could be applicable. const applicableOpts: ApplicableOpts = { fixBrokenEntities: false, removeWidows: false, convertEntities: false, convertDashes: false, convertApostrophes: false, replaceLineBreaks: false, removeLineBreaks: false, useXHTML: false, dontEncodeNonLatin: false, addMissingSpaces: false, convertDotsToEllipsis: false, stripHtml: false, eol: false, }; // // vars and internal functions // -------------------------------------------------------------------------- let endOfLineVal: EndOfLineVal = "\n"; if (opts.eol === "crlf") { endOfLineVal = "\r\n"; } else if (opts.eol === "cr") { endOfLineVal = "\r"; } const brClosingBracketIndexesArr: number[] = []; // We need to track what actions need to be done. Each action (a range) is // an array of two elements: from index and to index. It means what to delete. // There can be third element, a string, which means what to insert instead. const finalIndexesToDelete = new Ranges({ limitToBeAddedWhitespace: false, }); // the main container to gather the ranges. Ranges is a JS class. // When we process the input, we gather the information about it and sometimes // it's very efficient to stop processing chunks once they're cleared. // For example, any index ranges taken by HTML entities can be ignored after // those index range are identified. It's even a hassle otherwise: entities // contain ampersands and if we didn't ignore entity ranges, we'd have to // take measures to ignore ampersand encoding. const skipArr = new Ranges(); function applyAndWipe() { str = rApply(str, finalIndexesToDelete.current()); finalIndexesToDelete.wipe(); // skipArr.wipe(); } function isNum(something: any): boolean { return Number.isInteger(something); } const state: State = { onUrlCurrently: false, }; console.log( `131 ${`\u001b[${32}m${`FINAL`}\u001b[${39}m`} ${`\u001b[${33}m${`opts`}\u001b[${39}m`} = ${JSON.stringify( opts, null, 4 )}` ); // ____ // massive hammer | | // O=================| | // upon all bugs |____| // .=O=. // // // // // // // // // // // // T H E P I P E L I N E // // --------------------------------------------------------------------------- // NEXT STEP. console.log( `173 ${`\u001b[${90}m${`================= NEXT STEP. Initial =================`}\u001b[${39}m`}` ); str = trimSpaces(str.replace(ansiRegex(), "").replace(/\u200A/g, " "), { cr: true, lf: true, tab: true, space: true, nbsp: false, }).res; console.log( `183 after the initial trim, str = ${JSON.stringify(str, null, 0)}` ); // --------------------------------------------------------------------------- // NEXT STEP. let temp = str; let lastVal; do { lastVal = temp; temp = he.decode(temp); } while (temp !== str && lastVal !== temp); if (str !== temp) { str = temp; } console.log( `201 "str" after decoding, before collapsing: ${JSON.stringify( str, null, 0 )}` ); str = collapse(str, { trimLines: true, removeEmptyLines: true, limitConsecutiveEmptyLinesTo: 1, }).result; console.log(`212 "str" after collapsing: ${JSON.stringify(str, null, 0)}`); // --------------------------------------------------------------------------- // NEXT STEP. // preliminary loop through to remove/replace characters which later might // be needed to be considered when replacing others in the main loop; // that's mostly some nasties converted into spaces - those spaces will // be needed to already by there in the main loop for (let i = 0, len = str.length; i < len; i++) { if (str[i].charCodeAt(0) === 65533) { // REPLACEMENT CHARACTER, \uFFFD, or "�" console.log(`225 main.js: entering charcode #65533 catch clauses`); // Delete/fix all cases of Replacement character, \uFFFD, or "�": // It usually comes from Windows. if ( (str[i - 1] && str[i + 1] && ((str[i - 1].toLowerCase() === "n" && str[i + 1].toLowerCase() === "t") || (isLetter(str[i - 1]) && str[i + 1].toLowerCase() === "s"))) || (str[i + 2] && (((str[i + 1].toLowerCase() === "r" || str[i + 1].toLowerCase() === "v") && str[i + 2].toLowerCase() === "e") || (str[i + 1].toLowerCase() === "l" && str[i + 2].toLowerCase() === "l")) && ((str[i - 3] && str[i - 3].toLowerCase() === "y" && str[i - 2].toLowerCase() === "o" && str[i - 1].toLowerCase() === "u") || (str[i - 2] && str[i - 2].toLowerCase() === "w" && str[i - 1].toLowerCase() === "e") || (str[i - 4] && str[i - 4].toLowerCase() === "t" && str[i - 3].toLowerCase() === "h" && str[i - 2].toLowerCase() === "e" && str[i - 1].toLowerCase() === "y"))) || (((str[i - 1] && str[i - 1].toLowerCase() === "i") || (str[i - 2] && str[i - 2].toLowerCase() === "h" && str[i - 1].toLowerCase() === "e") || (str[i - 3] && str[i - 3].toLowerCase() === "s" && str[i - 2].toLowerCase() === "h" && str[i - 1].toLowerCase() === "e")) && str[i + 2] && str[i + 1].toLowerCase() === "l" && str[i + 2].toLowerCase() === "l") || (str[i - 5] && str[i + 2] && str[i - 5].toLowerCase() === "m" && str[i - 4].toLowerCase() === "i" && str[i - 3].toLowerCase() === "g" && str[i - 2].toLowerCase() === "h" && str[i - 1].toLowerCase() === "t" && str[i + 1] === "v" && str[i + 2] === "e") || (str[i - 1] && str[i - 1].toLowerCase() === "s" && (!str[i + 1] || (!isLetter(str[i + 1]) && !isNumber(str[i + 1])))) ) { // 1. case of n�t, for example, couldn�t (n + � + t), // or case of <letter>�s, for example your�s (letter + � + s). // 2. case of we�re, you�re, they�re // 3. case of we�ve, you�ve, they�ve // 4. case of I�ll, you�ll, he'�ll, she�ll, we�ll, they�ll, it�ll const replacement = opts.convertApostrophes ? rightSingleQuote : "'"; finalIndexesToDelete.push(i, i + 1, `${replacement}`); console.log(`284 main.js - PUSH [${i}, ${i + 1}, ${replacement}]`); applicableOpts.convertApostrophes = true; console.log( `287 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`applicableOpts.convertApostrophes`}\u001b[${39}m`} = ${JSON.stringify( applicableOpts.convertApostrophes, null, 4 )}` ); } else if ( str[i - 2] && isLowercaseLetter(str[i - 2]) && !str[i - 1].trim() && str[i + 2] && isLowercaseLetter(str[i + 2]) && !str[i + 1].trim() ) { // we don't encode here, no matter if opts.convertEntities is on: finalIndexesToDelete.push(i, i + 1, rawMDash); console.log(`303 main.js - PUSH [${i}, ${i + 1}, ${rawMDash}]`); // it's because it's a preliminary replacement, we'll encode in the main loop } else { finalIndexesToDelete.push(i, i + 1); console.log(`307 main.js - PUSH [${i}, ${i + 1}]`); } } } // --------------------------------------------------------------------------- // NEXT STEP. applyAndWipe(); // --------------------------------------------------------------------------- // NEXT STEP. // fix broken named HTML entities, if any: console.log( `322 ${`\u001b[${90}m${`================= NEXT STEP. fix broken HTML entity references =================`}\u001b[${39}m`}` ); const entityFixes = fixEnt(str, { decode: false }); if (entityFixes && entityFixes.length) { // 1. report option as applicable: applicableOpts.fixBrokenEntities = true; console.log( `330 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`applicableOpts.fixBrokenEntities`}\u001b[${39}m`} = ${JSON.stringify( applicableOpts.fixBrokenEntities, null, 4 )}` ); // 2. if option is enabled, apply it: if (opts.fixBrokenEntities) { str = rApply(str, entityFixes); console.log( `341 after fixing broken entities, str = ${JSON.stringify( str, null, 0 )}` ); } } // --------------------------------------------------------------------------- // NEXT STEP. // callback, opts.cb processing outside the tags if (typeof opts.cb === "function") { // if there are potential HTML tags, we'll need to extract them and process // outside them if (str.includes("<") || str.includes(">")) { console.log( `360 ${`\u001b[${90}m${`================= NEXT STEP. HTML tags, pt.1 =================`}\u001b[${39}m`}` ); const calcRanges = stripHtml(str, { cb: ({ tag, rangesArr }) => { console.log( `${`\u001b[${33}m${`tag`}\u001b[${39}m`} = ${JSON.stringify( tag, null, 4 )}` ); return rangesArr.push( tag.lastOpeningBracketAt, tag.lastClosingBracketAt + 1 ); }, skipHtmlDecoding: true, }).ranges; const outsideTagRanges: Range[] = ( rInvert(calcRanges, str.length) || [] ).reduce((accumRanges, currRange) => { // if there's difference after callback's result, push it as range if ( typeof opts.cb === "function" && str.slice(currRange[0], currRange[1]) !== opts.cb(str.slice(currRange[0], currRange[1])) ) { return (accumRanges as any).concat([ [ currRange[0], currRange[1], opts.cb(str.slice(currRange[0], currRange[1])), ], ]); } return accumRanges; }, []); console.log( `400 ${`\u001b[${33}m${`outsideTagRanges`}\u001b[${39}m`} = ${JSON.stringify( outsideTagRanges, null, 4 )}` ); if (Array.isArray(outsideTagRanges) && outsideTagRanges.length) { console.log(`407 before cb, str = "${str}"`); str = rApply(str, outsideTagRanges as any); console.log(`409 after cb, str = "${str}"`); } } else { // if there are no tags, whole string can be processed: console.log(`413 before cb, str = "${str}"`); str = opts.cb(str); console.log(`415 after cb, str = "${str}"`); } } // --------------------------------------------------------------------------- // NEXT STEP. // tend the HTML tags // but maybe our input string doesn't even have any HTML tags? if (str.includes("<") || str.includes(">")) { console.log( `426 ${`\u001b[${90}m${`================= NEXT STEP. HTML tags, pt.2 =================`}\u001b[${39}m`}` ); // submit all HTML tags to be skipped from now on: // we're using callback interface to ignore strictly from bracket to bracket // (including brackets), without range extension which normally would get // added in callback's "deleteFrom" / "deleteTo" equivalent. // Normally, we wipe whole tag and its surrounding whitespace, then replace // it with space if needed, otherwise just delete that range. // This extended range is a liability in light of widow word removal processes // down the line - those won't "see" some of the spaces around tags! // prepare the callback for string-strip-html const cb = ({ tag, deleteFrom, deleteTo, // insert, // rangesArr proposedReturn, }: CbObj) => { console.log( `448 main.js: ${`\u001b[${33}m${`tag`}\u001b[${39}m`} = ${JSON.stringify( tag, null, 4 )}` ); // if it's a tag if ( (isNum(tag.lastOpeningBracketAt) && isNum(tag.lastClosingBracketAt) && tag.lastOpeningBracketAt < tag.lastClosingBracketAt) || tag.slashPresent ) { console.log(`462 tag confirmed`); applicableOpts.stripHtml = true; console.log( `465 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`applicableOpts.stripHtml`}\u001b[${39}m`} = ${JSON.stringify( applicableOpts.stripHtml, null, 4 )}` ); // 1. add range from bracket to bracket to ignores list: skipArr.push( tag.lastOpeningBracketAt, tag.lastClosingBracketAt ? tag.lastClosingBracketAt + 1 : str.length ); console.log( `478 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} to skipArr [${ tag.lastOpeningBracketAt }, ${ tag.lastClosingBracketAt ? tag.lastClosingBracketAt + 1 : str.length }]` ); // 2. strip tag if opts.stripHtml is enabled if ( opts.stripHtml && (!tag.name || (typeof tag.name === "string" && !opts.stripHtmlButIgnoreTags.includes(tag.name.toLowerCase()))) ) { // 1. strip tag console.log(`493 strip tag clauses`); // take care of tags listed under opts.stripHtmlAddNewLine if ( Array.isArray(opts.stripHtmlAddNewLine) && opts.stripHtmlAddNewLine.length && opts.stripHtmlAddNewLine.some( (tagName) => (tagName.startsWith("/") && // present slash will be reported for both frontal and // self-closing cases: </td> and <br/> but we want only // frontal, so... tag.slashPresent && // additional check, is slash frontal tag.slashPresent < tag.nameEnds && typeof tag.name === "string" && tag.name.toLowerCase() === tagName.slice(1)) || (!tagName.startsWith("/") && !( // slash is present ( tag.slashPresent && // and it's frontal (slash as in </td> not <br/>) tag.slashPresent < tag.nameEnds ) ) && typeof tag.name === "string" && tag.name.toLowerCase() === removeTrailingSlash(tagName)) ) ) { console.log(`523 opts.stripHtmlAddNewLine clauses`); applicableOpts.removeLineBreaks = true; console.log( `527 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`applicableOpts.removeLineBreaks`}\u001b[${39}m`} = ${JSON.stringify( applicableOpts.removeLineBreaks, null, 4 )}` ); if ( !opts.removeLineBreaks && typeof deleteFrom === "number" && typeof deleteTo === "number" ) { applicableOpts.replaceLineBreaks = true; console.log( `541 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`applicableOpts.replaceLineBreaks`}\u001b[${39}m`} = ${JSON.stringify( applicableOpts.replaceLineBreaks, null, 4 )}` ); if (opts.replaceLineBreaks) { applicableOpts.useXHTML = true; console.log( `551 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`applicableOpts.useXHTML`}\u001b[${39}m`} = ${JSON.stringify( applicableOpts.useXHTML, null, 4 )}` ); } // insert <br> finalIndexesToDelete.push( deleteFrom, deleteTo, `${ opts.replaceLineBreaks ? `<br${opts.useXHTML ? "/" : ""}>` : "" }\n` ); console.log( `570 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} ${JSON.stringify( [ deleteFrom, deleteTo, `${ opts.replaceLineBreaks ? `<br${opts.useXHTML ? "/" : ""}>` : "" }\n`, ], null, 0 )}` ); console.log( `585 FINALLY, finalIndexesToDelete.current() = ${JSON.stringify( finalIndexesToDelete.current(), null, 4 )}` ); } else { finalIndexesToDelete.push(proposedReturn as any); console.log( `594 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} ${JSON.stringify( proposedReturn, null, 4 )}` ); } } else { console.log( `603 didn't fell into opts.stripHtmlAddNewLine clauses` ); finalIndexesToDelete.push(proposedReturn as any); skipArr.push(proposedReturn as any); console.log( `608 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} to ${`\u001b[${33}m${`finalIndexesToDelete`}\u001b[${39}m`} and ${`\u001b[${33}m${`skipArr`}\u001b[${39}m`} ${JSON.stringify( proposedReturn, null, 4 )}` ); } } else { console.log("616 - not stripping tags"); // 3. add closing slash on void tags if XHTML mode is on if ( typeof tag.name === "string" && voidTags.includes(tag.name.toLowerCase()) ) { // // IF A VOID TAG // applicableOpts.useXHTML = true; console.log( `628 it's a void tag. ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.useXHTML = ${ applicableOpts.useXHTML }` ); if ( str[left(str, tag.lastClosingBracketAt) as number] !== "/" && tag.lastClosingBracketAt ) { console.log(`637`); if (opts.useXHTML) { console.log( `640 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${ tag.lastClosingBracketAt }, ${tag.lastClosingBracketAt}, "/"]` ); finalIndexesToDelete.push( tag.lastClosingBracketAt, tag.lastClosingBracketAt, "/" ); } } // 4. remove slashes in front of a void tag if ( tag.slashPresent && isNum(tag.lastOpeningBracketAt) && tag.nameStarts && tag.lastOpeningBracketAt < tag.nameStarts - 1 && str .slice(tag.lastOpeningBracketAt + 1, tag.nameStarts) .split("") .every((char) => !char.trim() || char === "/") ) { console.log( `664 remove whitespace/slashes ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${ tag.lastOpeningBracketAt + 1 }, ${tag.nameStarts}]` ); finalIndexesToDelete.push( tag.lastOpeningBracketAt + 1, tag.nameStarts ); } console.log( `675 finalIndexesToDelete.current() = ${JSON.stringify( finalIndexesToDelete.current(), null, 4 )}` ); // 5. remove closing slash from void tags is XHTML mode is off // or excessive, multiple closing slashes if ( tag.slashPresent && str[left(str, tag.lastClosingBracketAt) as number] === "/" ) { console.log("688"); if ( str[ left( str, left(str, tag.lastClosingBracketAt) as number ) as number ] === "/" ) { applicableOpts.useXHTML = true; console.log( `699 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.useXHTML = ${ applicableOpts.useXHTML }` ); if ( !opts.useXHTML || (typeof chompLeft( str, tag.lastClosingBracketAt, { mode: 2 }, "/" ) === "number" && str.slice( chompLeft( str, tag.lastClosingBracketAt, { mode: 2 }, "/" ) as number, tag.lastClosingBracketAt ) !== "/") ) { // multiple closing slashes finalIndexesToDelete.push( // chomp mode 2: hungrily chomp all whitespace except newlines // for example: // chompLeft("a b c b c x y", 12, { mode: 2 }, "b", "c") // => 1 chompLeft( str, tag.lastClosingBracketAt, { mode: 2 }, "/" ) as number, tag.lastClosingBracketAt, opts.useXHTML ? "/" : undefined ); console.log( `738 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} chomped [${chompLeft( str, tag.lastClosingBracketAt, { mode: 2 }, "/" )}, ${tag.lastClosingBracketAt}, ${ opts.useXHTML ? "/" : undefined }]` ); } } else if ( !opts.useXHTML || typeof left(str, tag.slashPresent) !== "number" || str.slice( (left(str, tag.slashPresent) as number) + 1, tag.lastClosingBracketAt ) !== "/" ) { const calculatedFrom = (left(str, tag.slashPresent) as number) + 1; const calculatedTo = tag.lastClosingBracketAt; const whatToInsert = opts.useXHTML ? "/" : null; if (whatToInsert) { console.log( `763 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${calculatedFrom}, ${calculatedTo}, ${whatToInsert}]` ); finalIndexesToDelete.push( calculatedFrom, calculatedTo, whatToInsert ); } else { console.log( `772 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${calculatedFrom}, ${calculatedTo}]` ); finalIndexesToDelete.push(calculatedFrom, calculatedTo); } } } } // // IF NOT A VOID TAG // // 6. if it's not a void tag and there's slash on a wrong side, correct it else if ( tag.slashPresent && str[left(str, tag.lastClosingBracketAt) as number] === "/" ) { // 6-1. remove the wrong slash finalIndexesToDelete.push( chompLeft( str, tag.lastClosingBracketAt, { mode: 2 }, "/" ) as number, tag.lastClosingBracketAt ); // 6-2. add where it needs to be finalIndexesToDelete.push( tag.lastOpeningBracketAt + 1, tag.lastOpeningBracketAt + 1, "/" ); } console.log( `807 finalIndexesToDelete.current() = ${JSON.stringify( finalIndexesToDelete.current(), null, 4 )}` ); // 7. remove whitespace after tag name like <tr > if ( `/>`.includes(str[right(str, tag.nameEnds - 1) as number]) && (right(str, tag.nameEnds - 1) || 0) > tag.nameEnds ) { console.log( `820 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${ tag.nameEnds }, ${right(str, tag.nameEnds - 1)}]` ); finalIndexesToDelete.push( tag.nameEnds, right(str, tag.nameEnds - 1) as number ); } // 8. remove whitespace in front of tag name, considering closing slashes if ( isNum(tag.lastOpeningBracketAt) && isNum(tag.nameStarts) && tag.lastOpeningBracketAt + 1 < tag.nameStarts ) { // cases like < tr> if ( !str.slice(tag.lastOpeningBracketAt + 1, tag.nameStarts).trim() .length ) { // all this whitespace goes console.log( `843 whitespace in front of tag name - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${ tag.lastOpeningBracketAt + 1 }, ${tag.nameStarts}]` ); finalIndexesToDelete.push( tag.lastOpeningBracketAt + 1, tag.nameStarts ); } else if ( typeof tag.name === "string" && !voidTags.includes(tag.name.toLowerCase()) && str .slice(tag.lastOpeningBracketAt + 1, tag.nameStarts) .split("") .every((char) => !char.trim() || char === "/") ) { // if there is mix of whitespace and closing slashes, all this // goes and replaced with single slash. // Imagine: < /// /// table> finalIndexesToDelete.push( tag.lastOpeningBracketAt + 1, tag.nameStarts, "/" ); console.log( `868 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${ tag.lastOpeningBracketAt + 1 }, ${tag.nameStarts}, ${"/"}]` ); } } } // 9. if it's a BR, take a note of its closing bracket's location: if ( typeof tag.name === "string" && tag.name.toLowerCase() === "br" && tag.lastClosingBracketAt ) { brClosingBracketIndexesArr.push(tag.lastClosingBracketAt); console.log( `884 brClosingBracketIndexesArr now = ${JSON.stringify( brClosingBracketIndexesArr, null, 0 )}` ); } // 10. remove whitespace in front of UL/LI tags if ( typeof tag.name === "string" && ["ul", "li"].includes(tag.name.toLowerCase()) && !opts.removeLineBreaks && str[tag.lastOpeningBracketAt - 1] && !str[tag.lastOpeningBracketAt - 1].trim() && typeof tag.lastOpeningBracketAt === "number" && typeof leftStopAtNewLines(str, tag.lastOpeningBracketAt) === "number" ) { console.log(`902 - ul/li prep`); // if there's whitespace in front, finalIndexesToDelete.push( (leftStopAtNewLines(str, tag.lastOpeningBracketAt) as number) + 1, tag.lastOpeningBracketAt ); console.log( `909 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${ (leftStopAtNewLines(str, tag.lastOpeningBracketAt) as number) + 1 }, ${tag.lastOpeningBracketAt}]` ); } // 11. remove whitespace before closing bracket if ( str[tag.lastClosingBracketAt - 1] && !str[tag.lastClosingBracketAt - 1].trim() && typeof tag.lastClosingBracketAt === "number" && typeof left(str, tag.lastClosingBracketAt) === "number" ) { finalIndexesToDelete.push( (left(str, tag.lastClosingBracketAt) as number) + 1, tag.lastClosingBracketAt ); console.log( `927 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${ (left(str, tag.lastClosingBracketAt) as number) + 1 }, ${tag.lastClosingBracketAt}]` ); } } // LOGGING: console.log( `${`\u001b[${90}m${`========================================\nENDING finalIndexesToDelete[]:\n`}\u001b[${39}m`}` ); console.log( `${`\u001b[${90}m${JSON.stringify( finalIndexesToDelete.current(), null, 4 )}\u001b[${39}m`}` ); }; console.log( `${`\u001b[${90}m${`========================================`}\u001b[${39}m`}` ); // since we rely on callback interface, we don't need to assign the function // to a result, we perform all the processing within the callback "cb": stripHtml(str, { cb, trimOnlySpaces: true, ignoreTags: opts.stripHtml ? opts.stripHtmlButIgnoreTags : [], skipHtmlDecoding: true, }); } console.log( `961 ${str.includes("<") || str.includes(">") ? "" : "no tags found"}` ); console.log( `964 ${`\u001b[${33}m${`rangesArr`}\u001b[${39}m`}.current() = ${JSON.stringify( finalIndexesToDelete.current(), null, 0 )}; ${`\u001b[${33}m${`skipArr`}\u001b[${39}m`}.current() = ${JSON.stringify( skipArr.current(), null, 0 )}` ); // --------------------------------------------------------------------------- // NEXT STEP. console.log( `979 ${`\u001b[${90}m${`================= NEXT STEP. Process outside tags =================`}\u001b[${39}m`}` ); console.log(`982 call rProcessOutside()`); rProcessOutside( str, skipArr.current(), (idxFrom, idxTo, offsetBy) => processCharacter( str, opts, finalIndexesToDelete, idxFrom, idxTo, offsetBy, brClosingBracketIndexesArr, state, applicableOpts, endOfLineVal ), true ); console.log( `\u001b[${36}m${`===============================`}\u001b[${39}m \u001b[${35}m looping done \u001b[${36}m${`===============================`}\u001b[${39}m` ); console.log( `1006 back to main.js(): ${`\u001b[${33}m${`str`}\u001b[${39}m`}=${JSON.stringify( str, null, 0 )}\n---\n${`\u001b[${33}m${`rangesArr.current()`}\u001b[${39}m`} = ${JSON.stringify( finalIndexesToDelete.current(), null, 4 )}` ); console.log( `1017 ${`\u001b[${33}m${`applicableOpts`}\u001b[${39}m`} = ${JSON.stringify( applicableOpts, null, 4 )}` ); // --------------------------------------------------------------------------- // NEXT STEP. console.log( `1028 ${`\u001b[${90}m${`================= NEXT STEP. apply+wipe =================`}\u001b[${39}m`}` ); console.log( `1032 ${`\u001b[${33}m${`str`}\u001b[${39}m`} before apply+wipe: ${JSON.stringify( str, null, 4 )}` ); applyAndWipe(); console.log( `1040 ${`\u001b[${33}m${`str`}\u001b[${39}m`} after apply+wipe: ${JSON.stringify( str, null, 4 )}` ); // patch up spaces in front of <br/> str = str.replace(/ (<br[/]?>)/g, "$1"); str = str.replace(/(\r\n|\r|\n){3,}/g, `${endOfLineVal}${endOfLineVal}`); console.log( `1051 ${`\u001b[${33}m${`str`}\u001b[${39}m`} after str.replace: ${JSON.stringify( str, null, 4 )}` ); console.log( `1058 ${`\u001b[${33}m${`finalIndexesToDelete.current()`}\u001b[${39}m`} = ${JSON.stringify( finalIndexesToDelete.current(), null, 4 )}` ); // --------------------------------------------------------------------------- // NEXT STEP. console.log( `1069 ${`\u001b[${90}m${`================= NEXT STEP. widows =================`}\u001b[${39}m`}` ); console.log( `1072 ${`\u001b[${33}m${`skipArr.current()`}\u001b[${39}m`} = ${JSON.stringify( skipArr.current(), null, 4 )}` ); // remove widow words const widowFixes = removeWidows(str, { ignore: "all", convertEntities: opts.convertEntities, // full-on setup targetLanguage: "html", UKPostcodes: true, // full-on setup hyphens: opts.convertDashes, // full-on setup tagRanges: skipArr.current(), }); console.log( `1089 ${`\u001b[${33}m${`widowFixes`}\u001b[${39}m`} = ${JSON.stringify( widowFixes, null, 4 )}` ); if (widowFixes && widowFixes.ranges && widowFixes.ranges.length) { // 1. report option as potentially applicable: if (!applicableOpts.removeWidows && widowFixes.whatWasDone.removeWidows) { applicableOpts.removeWidows = true; console.log( `1100 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`applicableOpts.removeWidows`}\u001b[${39}m`} = true` ); if (opts.removeWidows) { applicableOpts.convertEntities = true; console.log( `1105 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`applicableOpts.convertEntities`}\u001b[${39}m`} = true` ); } } // 2. if ( !applicableOpts.convertEntities && widowFixes.whatWasDone.convertEntities ) { applicableOpts.convertEntities = true; console.log( `1116 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`applicableOpts.convertEntities`}\u001b[${39}m`} = true` ); } // 3. if option is enabled, apply it: if (opts.removeWidows) { str = widowFixes.res; console.log( `1124 after fixing widows, str = ${JSON.stringify(str, null, 0)}` ); } } // --------------------------------------------------------------------------- // NEXT STEP. console.log( `1133 ${`\u001b[${90}m${`================= NEXT STEP. linebreaks =================`}\u001b[${39}m`}` ); console.log("\n\n\n"); console.log( `1138 STEP#6 ${`\u001b[${33}m${`brClosingBracketIndexesArr`}\u001b[${39}m`} = ${JSON.stringify( brClosingBracketIndexesArr, null, 4 )}\n\n\n` ); // replace line breaks console.log( `1147 ███████████████████████████████████████ ${`\u001b[${33}m${`str`}\u001b[${39}m`} = ${JSON.stringify( str, null, 4 )}` ); if (str.trim() !== str.replace(/\r\n|\r|\n/gm, " ").trim()) { // 1. report opts.removeLineBreaks might be applicable applicableOpts.removeLineBreaks = true; console.log( `1157 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`applicableOpts.removeLineBreaks`}\u001b[${39}m`} = ${ applicableOpts.removeLineBreaks }` ); // 2. apply if option is on if (opts.removeLineBreaks) { str = str.replace(/\r\n|\r|\n/gm, " "); } } // --------------------------------------------------------------------------- // NEXT STEP. console.log( `1172 ${`\u001b[${90}m${`================= NEXT STEP. collapse =================`}\u001b[${39}m`}` ); console.log(`1175 str before collapsing: ${JSON.stringify(str, null, 0)}`); str = collapse(str, { trimLines: true, }).result; console.log(`1180 str after collapsing: ${JSON.stringify(str, null, 0)}`); // --------------------------------------------------------------------------- // NEXT STEP. console.log( `1186 ${`\u001b[${90}m${`================= NEXT STEP. final =================`}\u001b[${39}m`}` ); rApply(str, finalIndexesToDelete.current()) .split("") .forEach((key, idx) => { console.log( `1193 - #${idx}: ${`\u001b[${33}m${`key`}\u001b[${39}m`} = ${JSON.stringify( key, null, 4 )} (charcode ${`\u001b[${35}m${key.charCodeAt(0)}\u001b[${39}m`})` ); }); console.log( `1202 FINAL RESULT:\n${JSON.stringify( { res: rApply(str, finalIndexesToDelete.current()), applicableOpts, }, null, 4 )}` ); return { res: rApply(str, finalIndexesToDelete.current()), applicableOpts, }; } export { det, defaultOpts as opts, version }; // -----------------------------------------------------------------------------
the_stack
import { makeExecutableSchema } from 'apollo-server'; import { getAdditionalSchemas, queries, mutations, getResolvers, getCollections, QueryAndDescription, MutationAndDescription } from '../../../lib/vulcan-lib/graphql'; import { selectorInputTemplate, mainTypeTemplate, createInputTemplate, createDataInputTemplate, updateInputTemplate, updateDataInputTemplate, orderByInputTemplate, selectorUniqueInputTemplate, deleteInputTemplate, upsertInputTemplate, singleInputTemplate, multiInputTemplate, multiOutputTemplate, singleOutputTemplate, mutationOutputTemplate, singleQueryTemplate, multiQueryTemplate, createMutationTemplate, updateMutationTemplate, upsertMutationTemplate, deleteMutationTemplate, } from './graphqlTemplates'; import type { GraphQLScalarType } from 'graphql'; import { pluralize, camelCaseify, camelToSpaces } from '../../../lib/vulcan-lib'; import { userCanReadField } from '../../../lib/vulcan-users/permissions'; import { getSchema } from '../../../lib/utils/getSchema'; import deepmerge from 'deepmerge'; import GraphQLJSON from 'graphql-type-json'; import GraphQLDate from 'graphql-date'; import * as _ from 'underscore'; const queriesToGraphQL = (queries: QueryAndDescription[]): string => `type Query { ${queries.map(q => `${ q.description ? ` # ${q.description}\n` : '' } ${q.query} ` ) .join('\n')} } `; const mutationsToGraphQL = (mutations: MutationAndDescription[]): string => mutations.length > 0 ? ` ${ mutations.length > 0 ? `type Mutation { ${mutations .map(m => `${ m.description ? ` # ${m.description}\n` : '' } ${m.mutation}\n`) .join('\n')} } ` : '' } ` : ''; // generate GraphQL schemas for all registered collections const getTypeDefs = () => { const schemaContents: Array<string> = [ "scalar JSON", "scalar Date", getAdditionalSchemas(), ]; const allQueries = [...queries]; const allMutations = [...mutations]; const allResolvers: Array<any> = []; for (let collection of getCollections()) { const { schema, addedQueries, addedResolvers, addedMutations } = generateSchema(collection); for (let query of addedQueries) allQueries.push(query); for (let resolver of addedResolvers) allResolvers.push(resolver); for (let mutation of addedMutations) allMutations.push(mutation); schemaContents.push(schema); } schemaContents.push(queriesToGraphQL(allQueries)); schemaContents.push(mutationsToGraphQL(allMutations)); return { schemaText: schemaContents.join("\n"), addedResolvers: allResolvers, }; } // get GraphQL type for a given schema and field name const getGraphQLType = <T extends DbObject>(schema: SchemaType<T>, fieldName: string, isInput = false): string|null => { const field = schema[fieldName]; const type = field.type.singleType; const typeName = typeof type === 'object' ? 'Object' : typeof type === 'function' ? type.name : type; // LESSWRONG: Add optional property to override default input type generation if (isInput && field.inputType) { return field.inputType } switch (typeName) { case 'String': return 'String'; case 'Boolean': return 'Boolean'; case 'Number': return 'Float'; case 'SimpleSchema.Integer': return 'Int'; // for arrays, look for type of associated schema field or default to [String] case 'Array': const arrayItemFieldName = `${fieldName}.$`; // note: make sure field has an associated array if (schema[arrayItemFieldName]) { // try to get array type from associated array const arrayItemType = getGraphQLType(schema, arrayItemFieldName); return arrayItemType ? `[${arrayItemType}]` : null; } return null; case 'Object': return 'JSON'; case 'Date': return 'Date'; default: return null; } }; export type SchemaGraphQLFieldArgument = {name:string, type: string|GraphQLScalarType|null} export type SchemaGraphQLFieldDescription = { description?: string name: string args?: SchemaGraphQLFieldArgument[]|string|null|undefined type: string|GraphQLScalarType|null directive?: string required?: boolean }; type SchemaGraphQLFields = { mainType: SchemaGraphQLFieldDescription[], create: SchemaGraphQLFieldDescription[], update: SchemaGraphQLFieldDescription[], selector: SchemaGraphQLFieldDescription[], selectorUnique: SchemaGraphQLFieldDescription[], orderBy: SchemaGraphQLFieldDescription[], } // for a given schema, return main type fields, selector fields, // unique selector fields, orderBy fields, creatable fields, and updatable fields const getFields = <T extends DbObject>(schema: SchemaType<T>, typeName: string): { fields: SchemaGraphQLFields resolvers: any }=> { const fields: SchemaGraphQLFields = { mainType: [], create: [], update: [], selector: [], selectorUnique: [], orderBy: [], }; const addedResolvers: Array<any> = []; Object.keys(schema).forEach(fieldName => { const field = schema[fieldName]; const fieldType = getGraphQLType(schema, fieldName); const inputFieldType = getGraphQLType(schema, fieldName, true); // only include fields that are viewable/insertable/editable and don't contain "$" in their name // note: insertable/editable fields must be included in main schema in case they're returned by a mutation // OpenCRUD backwards compatibility if ( (field.canRead || field.canCreate || field.canUpdate || field.viewableBy || field.insertableBy || field.editableBy) && fieldName.indexOf('$') === -1 ) { const fieldDescription = field.description; const fieldDirective = ''; const fieldArguments: Array<any> = []; // if field has a resolveAs, push it to schema if (field.resolveAs) { // get resolver name from resolveAs object, or else default to field name const resolverName = field.resolveAs.fieldName || fieldName; // use specified GraphQL type or else convert schema type const fieldGraphQLType = field.resolveAs.type || fieldType; // if resolveAs is an object, first push its type definition // include arguments if there are any // note: resolved fields are not internationalized fields.mainType.push({ description: field.resolveAs.description, name: resolverName, args: field.resolveAs.arguments, type: fieldGraphQLType, }); // then build actual resolver object and pass it to addGraphQLResolvers const resolver = { [typeName]: { [resolverName]: (document: T, args: any, context: ResolverContext, info: any) => { const { currentUser } = context; // check that current user has permission to access the original non-resolved field const canReadField = userCanReadField(currentUser, field, document); return canReadField ? field.resolveAs!.resolver(document, args, context, info) : null; }, }, }; addedResolvers.push(resolver); // if addOriginalField option is enabled, also add original field to schema if (field.resolveAs.addOriginalField && fieldType) { fields.mainType.push({ description: fieldDescription, name: fieldName, args: fieldArguments, type: fieldType, directive: fieldDirective, }); } } else { // try to guess GraphQL type if (fieldType) { fields.mainType.push({ description: fieldDescription, name: fieldName, args: fieldArguments, type: fieldType, directive: fieldDirective, }); } } // OpenCRUD backwards compatibility if (field.canCreate || field.insertableBy) { fields.create.push({ name: fieldName, type: inputFieldType, required: !field.optional, }); } // OpenCRUD backwards compatibility if (field.canUpdate || field.editableBy) { fields.update.push({ name: fieldName, type: inputFieldType, }); } } }); return { fields, resolvers: addedResolvers }; }; // generate a GraphQL schema corresponding to a given collection const generateSchema = (collection: CollectionBase<DbObject>) => { let graphQLSchema = ''; const schemaFragments: Array<string> = []; const collectionName = collection.options.collectionName; const typeName = collection.typeName ? collection.typeName : camelToSpaces(_.initial(collectionName).join('')); // default to posts -> Post const schema = getSchema(collection); const { fields, resolvers: fieldResolvers } = getFields(schema, typeName); const { interfaces = [], resolvers, mutations } = collection.options; const description = collection.options.description ? collection.options.description : `Type for ${collectionName}`; const { mainType, create, update, selector, selectorUnique, orderBy } = fields; let addedQueries: Array<any> = []; let addedResolvers: Array<any> = [...fieldResolvers]; let addedMutations: Array<any> = []; if (mainType.length) { schemaFragments.push( mainTypeTemplate({ typeName, description, interfaces, fields: mainType }) ); schemaFragments.push(deleteInputTemplate({ typeName })); schemaFragments.push(singleInputTemplate({ typeName })); schemaFragments.push(multiInputTemplate({ typeName })); schemaFragments.push(singleOutputTemplate({ typeName })); schemaFragments.push(multiOutputTemplate({ typeName })); schemaFragments.push(mutationOutputTemplate({ typeName })); if (create.length) { schemaFragments.push(createInputTemplate({ typeName })); schemaFragments.push(createDataInputTemplate({ typeName, fields: create })); } if (update.length) { schemaFragments.push(updateInputTemplate({ typeName })); schemaFragments.push(upsertInputTemplate({ typeName })); schemaFragments.push(updateDataInputTemplate({ typeName, fields: update })); } schemaFragments.push(selectorInputTemplate({ typeName, fields: selector })); schemaFragments.push(selectorUniqueInputTemplate({ typeName, fields: selectorUnique })); schemaFragments.push(orderByInputTemplate({ typeName, fields: orderBy })); if (!_.isEmpty(resolvers)) { const queryResolvers: Partial<Record<string,any>> = {}; // single if (resolvers.single) { addedQueries.push({query: singleQueryTemplate({ typeName }), description: resolvers.single.description}); queryResolvers[camelCaseify(typeName)] = resolvers.single.resolver.bind( resolvers.single ); } // multi if (resolvers.multi) { addedQueries.push({query: multiQueryTemplate({ typeName }), description: resolvers.multi.description}); queryResolvers[ camelCaseify(pluralize(typeName)) ] = resolvers.multi.resolver.bind(resolvers.multi); } addedResolvers.push({ Query: { ...queryResolvers } }); } if (!_.isEmpty(mutations)) { const mutationResolvers: Partial<Record<string,any>> = {}; // create if (mutations.create) { // e.g. "createMovie(input: CreateMovieInput) : Movie" if (create.length === 0) { // eslint-disable-next-line no-console console.log( `// Warning: you defined a "create" mutation for collection ${collectionName}, but it doesn't have any mutable fields, so no corresponding mutation types can be generated. Remove the "create" mutation or define a "canCreate" property on a field to disable this warning` ); } else { addedMutations.push({mutation: createMutationTemplate({ typeName }), description: mutations.create.description}); mutationResolvers[`create${typeName}`] = mutations.create.mutation.bind( mutations.create ); } } // update if (mutations.update) { // e.g. "updateMovie(input: UpdateMovieInput) : Movie" if (update.length === 0) { // eslint-disable-next-line no-console console.log( `// Warning: you defined an "update" mutation for collection ${collectionName}, but it doesn't have any mutable fields, so no corresponding mutation types can be generated. Remove the "update" mutation or define a "canUpdate" property on a field to disable this warning` ); } else { addedMutations.push({mutation: updateMutationTemplate({ typeName }), description: mutations.update.description}); mutationResolvers[`update${typeName}`] = mutations.update.mutation.bind( mutations.update ); } } // upsert if (mutations.upsert) { // e.g. "upsertMovie(input: UpsertMovieInput) : Movie" if (update.length === 0) { // eslint-disable-next-line no-console console.log( `// Warning: you defined an "upsert" mutation for collection ${collectionName}, but it doesn't have any mutable fields, so no corresponding mutation types can be generated. Remove the "upsert" mutation or define a "canUpdate" property on a field to disable this warning` ); } else { addedMutations.push({mutation: upsertMutationTemplate({ typeName }), description: mutations.upsert.description}); mutationResolvers[`upsert${typeName}`] = mutations.upsert.mutation.bind( mutations.upsert ); } } // delete if (mutations.delete) { // e.g. "deleteMovie(input: DeleteMovieInput) : Movie" addedMutations.push({mutation: deleteMutationTemplate({ typeName }), description: mutations.delete.description}); mutationResolvers[`delete${typeName}`] = mutations.delete.mutation.bind(mutations.delete); } addedResolvers.push({ Mutation: { ...mutationResolvers } }); } graphQLSchema = schemaFragments.join('\n\n') + '\n\n\n'; } else { // eslint-disable-next-line no-console console.log( `// Warning: collection ${collectionName} doesn't have any GraphQL-enabled fields, so no corresponding type can be generated. Pass generateGraphQLSchema = false to createCollection() to disable this warning` ); } return { schema: graphQLSchema, addedQueries, addedResolvers, addedMutations }; }; export const initGraphQL = () => { const { schemaText, addedResolvers } = getTypeDefs(); let allResolvers = deepmerge( getResolvers(), { JSON: GraphQLJSON, Date: GraphQLDate, } ); for (let addedResolverGroup of addedResolvers) { allResolvers = deepmerge(allResolvers, addedResolverGroup); } executableSchema = makeExecutableSchema({ typeDefs: schemaText, resolvers: allResolvers, }); return executableSchema; }; let executableSchema: any = null; export const getExecutableSchema = () => { if (!executableSchema) { throw new Error('Warning: trying to access executable schema before it has been created by the server.'); } return executableSchema; };
the_stack
import { ComponentInfoForMerge, ComponentSkeletonModel, mergeFiles, ProjectSyncMetadataModel, renameAndSerializePlasmicASTNode, WarningInfo, } from "../index"; import { CodeVersion } from "../plasmic-parser"; import { code, formatted } from "../utils"; describe("Test CodeMerger", function () { it("no change", function () { const nameInIdToUuid = new Map([["Root", "Root"]]); const base = new CodeVersion( "<div className={rh.clsRoot()}>Hello World</div>", nameInIdToUuid ); const edited = new CodeVersion( "<div className={rh.clsRoot()}>Hello World</div>", nameInIdToUuid ); const newV = new CodeVersion( "<div className={rh.clsRoot()}>Hello World</div>", nameInIdToUuid ); expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual(formatted("<div className={rh.clsRoot()}>Hello World</div>")); }); it("attribute without value, with null, tag with member reference", function () { const nameInIdToUuid = new Map([["Root", "Root"]]); const base = new CodeVersion( "<div className={rh.clsRoot()}>Hello World</div>", nameInIdToUuid ); const edited = new CodeVersion( "<MyTags.div className={rh.clsRoot()} disabled nulled={null} empty={{}}>Hello World</MyTags.div>", nameInIdToUuid ); const newV = new CodeVersion( "<MyTags.div className={rh.clsRoot()}>Hello World</MyTags.div>", nameInIdToUuid ); expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted(` <MyTags.div className={rh.clsRoot()} disabled nulled={null} empty={{}}> Hello World </MyTags.div>`) ); }); it("tag name conflicts", function () { const nameInIdToUuid = new Map([["Root", "Root"]]); const base = new CodeVersion( "<div className={rh.clsRoot()}>Hello World</div>", nameInIdToUuid ); const edited = new CodeVersion( "<MyTags.div className={rh.clsRoot()}>Hello World</MyTags.div>", nameInIdToUuid ); const newV = new CodeVersion( "<Button className={rh.clsRoot()}>Hello World</Button>", nameInIdToUuid ); expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted(` <MyTags.div___Button className={rh.clsRoot()}> Hello World </MyTags.div___Button>`) ); }); it("User added attribute preserved", function () { const nameInIdToUuid = new Map([["Root", "Root"]]); const base = new CodeVersion( "<div className={rh.clsRoot()}>Hello World</div>", nameInIdToUuid ); const edited = new CodeVersion( "<div className={rh.clsRoot()} width={1}>Hello World</div>", nameInIdToUuid ); const newV = new CodeVersion( "<div className={rh.clsRoot()}>Hello World</div>", nameInIdToUuid ); expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted(`<div className={rh.clsRoot()} width={1}>Hello World</div>`) ); }); it(`id function upgrade, downgrade, downgrade preserving rh.propsXXX(modifier)`, function () { const nameInIdToUuid = new Map([ ["Root", "Root"], ["MyLink", "MyLink"], ["MyButton", "MyButton"], ]); const base = new CodeVersion( `<div className={rh.clsRoot()}> <a className={rh.clsMyLink()} {...rh.propsMyLink()}>Google</a> <button className={rh.clsMyButton()} {...rh.propsMyButton()}/> </div>`, nameInIdToUuid ); const edited = new CodeVersion( `<div className={rh.clsRoot()} width={1}> <a className={rh.clsMyLink()} {...rh.propsMyLink()}>Google</a> <button className={rh.clsMyButton()} {...rh.propsMyButton(modifier)}/> </div>`, nameInIdToUuid ); const newV = new CodeVersion( `<div className={rh.clsRoot()} {...rh.propsRoot()}> <a className={rh.clsMyLink()}>Google</a> <button className={rh.clsMyButton()}/> </div>`, nameInIdToUuid ); expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted(`<div className={rh.clsRoot()} {...rh.propsRoot()} width={1}> <a className={rh.clsMyLink()}>Google</a> <button className={rh.clsMyButton()} {...rh.propsMyButton(modifier)} /> </div>`) ); }); it(`className changed`, function () { const nameInIdToUuid = new Map([["Root", "Root"]]); const base = new CodeVersion( "<div className={rh.clsRoot()} />", nameInIdToUuid ); const edited = new CodeVersion( "<div className={rh.clsRoot()} />", nameInIdToUuid ); const newV = new CodeVersion( "<div className={rh.clsNewRoot()}/>", new Map([["NewRoot", "Root"]]) ); expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual(formatted(`<div className={rh.clsNewRoot()} />`)); }); it(`className appended`, function () { const nameInIdToUuid = new Map([["Root", "Root"]]); const base = new CodeVersion( "<div className={rh.clsRoot()} />", nameInIdToUuid ); const edited = new CodeVersion( "<div className={rh.clsRoot() + ' myClass'} />", nameInIdToUuid ); const newV = new CodeVersion( "<div className={rh.clsNewRoot()}/>", new Map([["NewRoot", "Root"]]) ); expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual(formatted(`<div className={rh.clsNewRoot() + ' myClass'} />`)); }); it(`className edited, but then deleted with id changed`, function () { const nameInIdToUuid = new Map([["Root", "Root"]]); const base = new CodeVersion( "<div className={rh.clsRoot()} />", nameInIdToUuid ); const edited = new CodeVersion( "<div className={rh.clsRoot() + ' myClass'} />", nameInIdToUuid ); const newV = new CodeVersion( "<div {...rh.propsNewRoot()}/>", new Map([["NewRoot", "Root"]]) ); expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted( `<div className={rh.clsNewRoot() + ' myClass'} {...rh.propsNewRoot()}/>` ) ); }); it("add show func; remove show func", function () { const nameInIdToUuid = new Map([ ["Root", "Root"], ["MyLink", "MyLink"], ["MyButton", "MyButton"], ]); const base = new CodeVersion( `<div className={rh.clsRoot()}> {rh.showMyLink() && <a {...rh.propsMyLink()}>Google</a>} <button {...rh.propsMyButton()}/> </div>`, nameInIdToUuid ); const edited = new CodeVersion( `<div className={rh.clsRoot()}> {rh.showMyLink() && <a {...rh.propsMyLink()}>Google</a>} <button {...rh.propsMyButton(modifier)}/> </div>`, nameInIdToUuid ); const newV = new CodeVersion( `<div className={rh.clsRoot()}> <a {...rh.propsMyLink()}>Google</a> {rh.showMyButton() && <button {...rh.propsMyButton()}/>} </div>`, nameInIdToUuid ); expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted(`<div className={rh.clsRoot()}> {true && <a {...rh.propsMyLink()}>Google</a>} {rh.showMyButton() && <button {...rh.propsMyButton(modifier)}/>} </div>`) ); }); it("node deleted", function () { const nameInIdToUuid = new Map([ ["Root", "Root"], ["MyLink", "MyLink"], ["MyButton", "MyButton"], ]); const base = new CodeVersion( "<div className={rh.clsRoot()}><a {...rh.propsMyLink()}>Google</a><button className={rh.clsMyButton()} {...rh.propsMyButton()}/></div>", nameInIdToUuid ); const edited = new CodeVersion( "<div className={rh.clsRoot()} width={1}><button className={rh.clsMyButton()} {...rh.propsMyButton(modifier)}/></div>", nameInIdToUuid ); const newV = new CodeVersion( "<div className={rh.clsRoot()} {...rh.propsRoot()}><a className={rh.clsMyLink()}>Google</a><button className={rh.clsMyButton()}/></div>", nameInIdToUuid ); expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted(`<div className={rh.clsRoot()} {...rh.propsRoot()} width={1}> <button className={rh.clsMyButton()} {...rh.propsMyButton(modifier)} /> </div>`) ); }); it("nodes reordered", function () { const nameInIdToUuid = new Map([ ["Root", "Root"], ["MyLink", "MyLink"], ["MyButton", "MyButton"], ]); const base = new CodeVersion( `<div className={rh.clsRoot()}> <a className={rh.clsMyLink()} {...rh.propsMyLink()}>Google</a> <button className={rh.clsMyButton()} {...rh.propsMyButton()}/> </div>`, nameInIdToUuid ); const edited = new CodeVersion( `<div className={rh.clsRoot()} width={1}> <button className={rh.clsMyButton()} {...rh.propsMyButton(modifier)}/> <a className={rh.clsMyLink()} {...rh.propsMyLink()}>Google</a> </div>`, nameInIdToUuid ); const newV = new CodeVersion( "<div className={rh.clsRoot()} {...rh.propsRoot()}><button className={rh.clsMyButton()}/><a className={rh.clsMyLink()}>Google</a></div>", nameInIdToUuid ); expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted(`<div className={rh.clsRoot()} {...rh.propsRoot()} width={1}> <button className={rh.clsMyButton()} {...rh.propsMyButton(modifier)} /> <a className={rh.clsMyLink()}>Google</a> </div>`) ); }); it("merge with old code that doesn't always generate className", function () { const nameInIdToUuid = new Map([ ["Root", "Root"], ["MyLink", "MyLink"], ["MyButton", "MyButton"], ]); const base = new CodeVersion( `<div className={rh.clsRoot()}> <a {...rh.propsMyLink()}>Google</a> <button {...rh.propsMyButton()}/> </div>`, nameInIdToUuid ); const edited = new CodeVersion( `<div className={rh.clsRoot()} width={1}> <button {...rh.propsMyButton(modifier)}/> <a {...rh.propsMyLink()}>Google</a> </div>`, nameInIdToUuid ); const newV = new CodeVersion( "<div className={rh.clsRoot()} {...rh.propsRoot()}><button className={rh.clsMyButton()}/><a className={rh.clsMyLink()}>Google</a></div>", nameInIdToUuid ); expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted(`<div className={rh.clsRoot()} {...rh.propsRoot()} width={1}> <button className={rh.clsMyButton()} {...rh.propsMyButton(modifier)} /> <a className={rh.clsMyLink()}>Google</a> </div>`) ); }); it("nodes wrapped", function () { const nameInIdToUuid = new Map([ ["Root", "Root"], ["MyLink", "MyLink"], ["MyButton", "MyButton"], ]); const base = new CodeVersion( `<div className={rh.clsRoot()}> <button {...rh.propsMyButton()}/> <a className={rh.clsMyLink()}>Google</a> </div>`, nameInIdToUuid ); const edited = new CodeVersion( `<div className={rh.clsRoot()} width={1}> {myGuard() && <button {...rh.propsMyButton()} tabIndex={1}/>} <Wrapper> <a className={rh.clsMyLink()} tabIndex={2}>Google</a> </Wrapper> </div>`, nameInIdToUuid ); const newV = new CodeVersion( `<div className={rh.clsRoot()} {...rh.propsRoot()}> <button className={rh.clsMyButton()}/> <a className={rh.clsMyLink()}>Google</a> </div>`, nameInIdToUuid ); expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted(`<div className={rh.clsRoot()} {...rh.propsRoot()} width={1}> {myGuard() && <button className={rh.clsMyButton()} tabIndex={1}/>} <Wrapper> <a className={rh.clsMyLink()} tabIndex={2}>Google</a> </Wrapper> </div>`) ); }); it("nodes wrapped for repetition", function () { const nameInIdToUuid = new Map([ ["Root", "Root"], ["MyLink", "MyLink"], ["MyButton", "MyButton"], ]); const base = new CodeVersion( `<div className={rh.clsRoot()}> <button {...rh.propsMyButton()}/> </div>`, nameInIdToUuid ); const edited = new CodeVersion( `<div className={rh.clsRoot()} width={1}> {items.map(() => { return (myGuard() && <button {...rh.propsMyButton()} tabIndex={1}/>); }) } </div>`, nameInIdToUuid ); const newV = new CodeVersion( `<div className={rh.clsRoot()} {...rh.propsRoot()}> <button className={rh.clsMyButton()}/> </div>`, nameInIdToUuid ); expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted(`<div className={rh.clsRoot()} {...rh.propsRoot()} width={1}> {items.map(() => { return (myGuard() && <button className={rh.clsMyButton()} tabIndex={1}/>); }) } </div>`) ); }); it("nodes moved around", function () { const nameInIdToUuid = new Map([ ["Root", "Root"], ["C1", "C1"], ["C2", "C2"], ["MyButton", "MyButton"], ]); const base = new CodeVersion( `<div className={rh.clsRoot()}> <div className={rh.clsC1()}> <button {...rh.propsMyButton()}/> </div> <div className={rh.clsC2()}> </div> </div>`, nameInIdToUuid ); const edited = new CodeVersion( `<div className={rh.clsRoot()}> <div className={rh.clsC1()}> <button {...rh.propsMyButton()} tabIndex={1}/> </div> <div className={rh.clsC2()}> </div> </div>`, nameInIdToUuid ); const newV = new CodeVersion( `<div className={rh.clsRoot()}> <div className={rh.clsC1()}> {args.text || "default"} </div> <div className={rh.clsC2()}> <button {...rh.propsMyButton()}/> </div> </div>`, nameInIdToUuid ); expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted(`<div className={rh.clsRoot()}> <div className={rh.clsC1()}> {args.text || "default"} </div> <div className={rh.clsC2()}> <button {...rh.propsMyButton()} tabIndex={1}/> </div> </div>`) ); }); it("merge children", function () { const nameInIdToUuid = new Map([ ["Root", "Root"], ["Img", "Img"], ]); const base = new CodeVersion( `<div className={rh.clsRoot()}> Hello World <div className={rh.clsImg()}></div> </div>`, nameInIdToUuid ); const edited = new CodeVersion( `<div className={rh.clsRoot()}> {"Added text node"} Hello World <div>Opaque node 1</div> <div className={rh.clsImg()} onClick={xxx}></div> {"Second text"} {showThis() && <div>Opaque node 2</div>} </div>`, nameInIdToUuid ); const newV = new CodeVersion( `<div className={rh.clsRoot()}> Hello World Edited <div className={rh.clsImg()}></div> </div>`, nameInIdToUuid ); expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted(` <div className={rh.clsRoot()}> {"Added text node"} Hello World Edited <div>Opaque node 1</div> <div className={rh.clsImg()} onClick={xxx}></div> {"Second text"} {showThis() && <div>Opaque node 2</div>} </div>`) ); }); it("single text child edited", function () { const nameInIdToUuid = new Map([ ["Root", "Root"], ["Img", "Img"], ]); const base = new CodeVersion( `<div className={rh.clsRoot()}> Hello World <div className={rh.clsImg()}></div> </div>`, nameInIdToUuid ); const edited = new CodeVersion( `<div className={rh.clsRoot()}> Hello World Edited </div>`, nameInIdToUuid ); const newV = new CodeVersion( `<div className={rh.clsRoot()}> Hello World </div>`, nameInIdToUuid ); expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted(` <div className={rh.clsRoot()}> Hello World Edited </div>`) ); }); it("multiple text children edited", function () { const nameInIdToUuid = new Map([ ["Root", "Root"], ["Img", "Img"], ]); const base = new CodeVersion( `<div className={rh.clsRoot()}> {"Hello"} {"World"} {"My"} {"Friends"} <div className={rh.clsImg()}></div> </div>`, nameInIdToUuid ); const edited = new CodeVersion( `<div className={rh.clsRoot()}> {"Hello1"} {"World"} {"My2"} {"Friends"} </div>`, nameInIdToUuid ); const newV = new CodeVersion( `<div className={rh.clsRoot()}> {"Hello"} {"World"} {"My3"} {"Friends"} </div>`, nameInIdToUuid ); expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted(` <div className={rh.clsRoot()}> {"Hello1"} {"World"} {"My3"} {"My2"} {"Friends"} </div>`) ); }); it("conflict attributes are both preserved", function () { const nameInIdToUuid = new Map([["Root", "Root"]]); const base = new CodeVersion( `<div className={rh.clsRoot()}> </div>`, nameInIdToUuid ); const edited = new CodeVersion( `<div className={rh.clsRoot()} tabindex={123}> Hello World </div>`, nameInIdToUuid ); const newV = new CodeVersion( `<div className={rh.clsRoot()} tabindex={234}> </div>`, nameInIdToUuid ); expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted(`<div className={rh.clsRoot()} tabindex={<>{123}{234}</>}> Hello World </div>`) ); }); it("event handlers edited and/or deleted", function () { const nameInIdToUuid = new Map([["Root", "Root"]]); const base = new CodeVersion( `<div className={ rh.clsRoot() } onMouseEnter={ rh.onMouseEnterRoot } onMouseLeave={rh.onMouseLeaveRoot} onMouseDown={rh.onMouseDownRoot}> </div>`, nameInIdToUuid ); const edited = new CodeVersion( `<div className={rh.clsRoot() } onMouseEnter={ rh.onMouseEnterRoot} onMouseLeave={() => { rh.onMouseLeaveRoot(); myEventHandler(); }} onClick={handleClick}> Hello World </div>`, nameInIdToUuid ); const newV = new CodeVersion( `<div className={ rh.clsNewRoot()} onMouseEnter={ rh.onMouseEnterNewRoot} onMouseLeave={rh.onMouseLeaveNewRoot} onMouseDown={rh.onMouseDownNewRoot}> </div>`, new Map([["NewRoot", "Root"]]) ); // Developer would have to fix rh.onRootMouseLeave to // rh.onNewRootMouseLeave. expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted(`<div className={rh.clsNewRoot()} onMouseEnter={rh.onMouseEnterNewRoot} onMouseLeave={() => { rh.onMouseLeaveNewRoot(); myEventHandler(); }} onClick={handleClick}> Hello World </div>`) ); }); it("add children", function () { const nameInIdToUuid = new Map([["Root", "Root"]]); const base = new CodeVersion( `<div className={rh.clsRoot()} />`, nameInIdToUuid ); const edited = new CodeVersion( `<div className={rh.clsRoot()} />`, nameInIdToUuid ); const newV = new CodeVersion( `<div className={rh.clsRoot()}> <div className={rh.clsBox()}/> </div>`, new Map([ ["Root", "Root"], ["Box", "Box"], ]) ); expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted(`<div className={rh.clsRoot()}> <div className={rh.clsBox()}/> </div>`) ); }); it("attribute changed in Plasmic", function () { const nameInIdToUuid = new Map([ ["Root", "Root"], ["Img", "Img"], ]); const base = new CodeVersion( `<div className={rh.clsRoot()} icon={<img className={rh.clsImg()}></img>} />`, nameInIdToUuid ); const edited = new CodeVersion( `<div className={rh.clsRoot()} icon={<img className={rh.clsImg()}></img>} />`, nameInIdToUuid ); const newV = new CodeVersion( `<div className={rh.clsRoot()} icon={<img className={rh.clsImg()} {...rh.propsImg()}></img>} />`, nameInIdToUuid ); expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted( `<div className={rh.clsRoot()} icon={<img className={rh.clsImg()} {...rh.propsImg()}></img>} />` ) ); }); it("text node not changed", function () { const nameInIdToUuid = new Map([ ["Root", "Root"], ["Btn", "Btn"], ]); const base = new CodeVersion( `<div className={rh.clsRoot()}> <button className={rh.clsBtn()}>Click Me</button> </div>`, nameInIdToUuid ); const edited = new CodeVersion( `<div className={rh.clsRoot()}> <button className={rh.clsBtn()}> Click Me </button> </div>`, nameInIdToUuid ); const newV = new CodeVersion( `<div className={rh.clsRoot()}> <button className={rh.clsBtn()}>Click Me</button> </div>`, nameInIdToUuid ); expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted( `<div className={rh.clsRoot()}> <button className={rh.clsBtn()}> Click Me </button> </div>` ) ); }); it("text node changed from JSXText to function call", function () { const nameInIdToUuid = new Map([ ["Root", "Root"], ["Btn", "Btn"], ]); const base = new CodeVersion( `<div className={rh.clsRoot()}> <button className={rh.clsBtn()}>Click Me</button> </div>`, nameInIdToUuid ); const edited = new CodeVersion( `<div className={rh.clsRoot()}> <button className={rh.clsBtn()}> Click Me </button> </div>`, nameInIdToUuid ); const newV = new CodeVersion( `<div className={rh.clsRoot()}> <button className={rh.clsBtn()}>{rh.childStrBtn()}</button> </div>`, nameInIdToUuid ); expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted( `<div className={rh.clsRoot()}> <button className={rh.clsBtn()}> {rh.childStrBtn()} </button> </div>` ) ); }); it("text node changed function call to JSXText", function () { const nameInIdToUuid = new Map([ ["Root", "Root"], ["Btn", "Btn"], ]); const base = new CodeVersion( `<div className={rh.clsRoot()}> <button className={rh.clsBtn()}>{rh.childStrBtn()}</button> </div>`, nameInIdToUuid ); const edited = new CodeVersion( `<div className={rh.clsRoot()}> <button className={rh.clsBtn()}> {rh.childStrBtn()} </button> </div>`, nameInIdToUuid ); const newV = new CodeVersion( `<div className={rh.clsRoot()}> <button className={rh.clsBtn()}>Click Me</button> </div>`, nameInIdToUuid ); expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted( `<div className={rh.clsRoot()}> <button className={rh.clsBtn()}> Click Me </button> </div>` ) ); }); it("tag change in new version", function () { const nameInIdToUuid = new Map([["Root", "Root"]]); const base = new CodeVersion( `<div className={rh.clsRoot()}> </div>`, nameInIdToUuid ); const edited = new CodeVersion( `<div className={rh.clsRoot()}> </div>`, nameInIdToUuid ); const newV = new CodeVersion( `<button className={rh.clsRoot()}> </button>`, nameInIdToUuid ); expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted( `<button className={rh.clsRoot()}> </button>` ) ); }); it("slot node name changed and wrapper edited", function () { const nameInIdToUuid = new Map([ ["Root", "Root"], ["$slotText", "1234"], ]); const base = new CodeVersion( `<div className={rh.clsRoot()}> <PlasmicSlot className={rh.cls$slotText()} value={args.text} defaultContent={"Abc"} /> </div>`, nameInIdToUuid ); const edited = new CodeVersion( `<div className={rh.clsRoot()}> <PlasmicSlot className={rh.cls$slotText()} value={args.text} defaultContent={<a>"Abc"</a>} /> </div>`, nameInIdToUuid ); const newV = new CodeVersion( `<div className={rh.clsRoot()}> <PlasmicSlot className={rh.cls$slotText2()} value={args.text2} defaultContent={"Abc"} /> </div>`, new Map([ ["Root", "Root"], ["$slotText2", "1234"], ]) ); expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted( `<div className={rh.clsRoot()}> <PlasmicSlot className={rh.cls$slotText2()} value={args.text2} defaultContent={<a>"Abc"</a>} /> </div>` ) ); }); it("slot node name changed and default node edited", function () { const nameInIdToUuid = new Map([ ["Root", "Root"], ["$slotText", "1234"], ]); const base = new CodeVersion( `<div className={rh.clsRoot()}> <PlasmicSlot value={args.text} className={rh.cls$slotText()} defaultContent={"Hello"} /> </div>`, nameInIdToUuid ); const edited = new CodeVersion( `<div className={rh.clsRoot()}> <PlasmicSlot value={args.text} className={rh.cls$slotText()} defaultContent={"Hello World"} /> </div>`, nameInIdToUuid ); const newV = new CodeVersion( `<div className={rh.clsRoot()}> <PlasmicSlot value={args.text2} className={rh.cls$slotText2()} defaultContent={"Hello"} /> </div>`, new Map([ ["Root", "Root"], ["$slotText2", "1234"], ]) ); expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted( `<div className={rh.clsRoot()}> <PlasmicSlot value={args.text2} className={rh.cls$slotText2()} defaultContent={"Hello World"} /> </div>` ) ); }); it("apply slot style via inheritance works for non text slot - always has a wrapper", function () { const nameInIdToUuid = new Map([ ["Root", "Root"], ["Img0", "1234"], ["$slotIconSlot", "2345"], ]); const base = new CodeVersion( `<div className={rh.clsRoot()}> <PlasmicSlot className={rh.cls$slotIconSlot()} value={args.iconSlot} defaultContent={<img className={rh.clsImg0()}></img>} > </PlasmicSlot> </div>`, nameInIdToUuid ); const edited = new CodeVersion( `<div className={rh.clsRoot()}> <PlasmicSlot className={rh.cls$slotIconSlot()} value={args.iconSlot} defaultContent={<img className={rh.clsImg0() + " my"}></img>} > </PlasmicSlot> </div>`, nameInIdToUuid ); const newV = new CodeVersion( `<div className={rh.clsRoot()}> <PlasmicSlot className={rh.cls$slotIconSlot2()} value={args.iconSlot2} defaultContent={<img className={rh.clsImg0()}></img>} > </PlasmicSlot> </div>`, new Map([ ["Root", "Root"], ["Img0", "1234"], ["$slotIconSlot2", "2345"], ]) ); expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted( `<div className={rh.clsRoot()}> <PlasmicSlot className={rh.cls$slotIconSlot2()} value={args.iconSlot2} defaultContent={<img className={rh.clsImg0() + " my"}></img>} > </PlasmicSlot> </div>` ) ); }); it("apply slot style via inheritance works for non text slot - adding a wrapper", function () { const nameInIdToUuid = new Map([ ["Root", "Root"], ["Img0", "1234"], ]); const base = new CodeVersion( `<div className={rh.clsRoot()}> {args.iconSlot || <img className={rh.clsImg0()}></img>} </div>`, nameInIdToUuid ); const edited = new CodeVersion( `<div className={rh.clsRoot()}> {args.iconSlot || <img className={rh.clsImg0() + " my"}></img>} </div>`, nameInIdToUuid ); const newV = new CodeVersion( `<div className={rh.clsRoot()}> <div className={rh.cls$slotIconSlot()}> {args.iconSlot || <img className={rh.clsImg0()}></img>} </div> </div>`, new Map([ ["Root", "Root"], ["Img0", "1234"], ["$slotIconSlot", "2345"], ]) ); expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted( `<div className={rh.clsRoot()}> <div className={rh.cls$slotIconSlot()}> {args.iconSlot || <img className={rh.clsImg0() + " my"}></img>} </div> </div>` ) ); }); it("apply slot style via inheritance works for non text slot - removing the wrapper", function () { const nameInIdToUuid = new Map([ ["Root", "Root"], ["Img0", "1234"], ["$slotIconSlot", "2345"], ]); const base = new CodeVersion( `<div className={rh.clsRoot()}> <div className={rh.cls$slotIconSlot()}> {args.iconSlot || <img className={rh.clsImg0()}></img>} </div> </div>`, nameInIdToUuid ); const edited = new CodeVersion( `<div className={rh.clsRoot()}> <div className={rh.cls$slotIconSlot()}> {args.iconSlot || <img className={rh.clsImg0() + " my"}></img>} </div> </div>`, nameInIdToUuid ); const newV = new CodeVersion( `<div className={rh.clsRoot()}> {args.iconSlot2 || <img className={rh.clsImg0()}></img>} </div>`, new Map([ ["Root", "Root"], ["Img0", "1234"], ["$slotIconSlot2", "2345"], ]) ); expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted( `<div className={rh.clsRoot()}> {args.iconSlot2 || <img className={rh.clsImg0() + " my"}></img>} </div>` ) ); }); it("merge two slots's defaultContent - 1 node and 2 nodes", function () { const nameInIdToUuid = new Map([ ["Root", "Root"], ["Img0", "1234"], ["$slotIconSlot", "2345"], ]); const base = new CodeVersion( `<div className={rh.clsRoot()}> <PlasmicSlot className={rh.cls$slotIconSlot()} value={args.iconSlot} defaultContent={<img className={rh.clsImg0()}></img>}/> </div>`, nameInIdToUuid ); const edited = new CodeVersion( `<div className={rh.clsRoot()}> <PlasmicSlot className={rh.cls$slotIconSlot()} value={args.iconSlot} defaultContent={<img className={rh.clsImg0()} tabIndex={1}></img>}/> </div>`, nameInIdToUuid ); const newV = new CodeVersion( `<div className={rh.clsRoot()}> <PlasmicSlot className={rh.cls$slotIconSlot2()} value={args.iconSlot} defaultContent={ <> <img className={rh.clsImg1()}></img> <img className={rh.clsImg0()}></img> </>}/> </div>`, new Map([ ["Root", "Root"], ["Img0", "1234"], ["Img1", "4567"], ["$slotIconSlot2", "2345"], ]) ); expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted( `<div className={rh.clsRoot()}> <PlasmicSlot className={rh.cls$slotIconSlot2()} value={args.iconSlot} defaultContent={ <> <img className={rh.clsImg1()}></img> <img className={rh.clsImg0()} tabIndex={1}></img> </>}/> </div>` ) ); }); it("merge two slots's defaultContent - 1 node and 1 node", function () { const nameInIdToUuid = new Map([ ["Root", "Root"], ["Img0", "1234"], ["$slotIconSlot", "2345"], ]); const base = new CodeVersion( `<div className={rh.clsRoot()}> <PlasmicSlot className={rh.cls$slotIconSlot()} value={args.iconSlot} defaultContent={<img className={rh.clsImg0()}></img>}/> </div>`, nameInIdToUuid ); const edited = new CodeVersion( `<div className={rh.clsRoot()}> <PlasmicSlot className={rh.cls$slotIconSlot()} value={args.iconSlot} defaultContent={<><img className={rh.clsImg0()} tabIndex={1}></img></>}/> </div>`, nameInIdToUuid ); const newV = new CodeVersion( `<div className={rh.clsRoot()}> <PlasmicSlot className={rh.cls$slotIconSlot2()} value={args.iconSlot} defaultContent={ <img className={rh.clsImg1()}></img> }/> </div>`, new Map([ ["Root", "Root"], ["Img1", "1234"], ["$slotIconSlot2", "2345"], ]) ); // When the result is only one node, we follow edited version to add the // fragment or not. expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted( `<div className={rh.clsRoot()}> <PlasmicSlot className={rh.cls$slotIconSlot2()} value={args.iconSlot} defaultContent={ <><img className={rh.clsImg1()} tabIndex={1}></img></> }/> </div>` ) ); }); it("renaming of argsRef", function () { const nameInIdToUuid = new Map([ ["Root", "Root"], ["$slotIconSlot", "2345"], ]); const base = new CodeVersion( `<div className={rh.clsRoot()}> <PlasmicSlot className={rh.cls$slotIconSlot()} value={args.iconSlot} defaultContent={<></>}/> </div>`, nameInIdToUuid ); const edited = new CodeVersion( `<div className={rh.clsRoot()}> <PlasmicSlot className={rh.cls$slotIconSlot()} value={args.iconSlot || "abc"} defaultContent={<></>}/> </div>`, nameInIdToUuid ); const newV = new CodeVersion( `<div className={rh.clsRoot()}> <PlasmicSlot className={rh.cls$slotIconSlot2()} value={args.iconSlot2} defaultContent={ <></> }/> </div>`, new Map([ ["Root", "Root"], ["$slotIconSlot2", "2345"], ]) ); // When the result is only one node, we follow edited version to add the // fragment or not. expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted( `<div className={rh.clsRoot()}> <PlasmicSlot className={rh.cls$slotIconSlot2()} value={args.iconSlot2 || "abc"} defaultContent={<></>}/> </div>` ) ); }); it("renaming of args in non argsRef", function () { const nameInIdToUuid = new Map([ ["Root", "Root"], ["$slotIconSlot", "2345"], ]); const base = new CodeVersion( `<div className={rh.clsRoot()}> <PlasmicSlot className={rh.cls$slotIconSlot()} value={args.iconSlot} defaultContent={<></>}/> </div>`, nameInIdToUuid ); const edited = new CodeVersion( `<div className={rh.clsRoot()}> <PlasmicSlot className={rh.cls$slotIconSlot()} value={args.iconSlot || "abc"} defaultContent={<></>}/> {showArgsAgain() && args.iconSlot} </div>`, nameInIdToUuid ); const newV = new CodeVersion( `<div className={rh.clsRoot()}> <PlasmicSlot className={rh.cls$slotIconSlot2()} value={args.iconSlot2} defaultContent={ <></> }/> </div>`, new Map([ ["Root", "Root"], ["$slotIconSlot2", "2345"], ]) ); // When the result is only one node, we follow edited version to add the // fragment or not. expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted( `<div className={rh.clsRoot()}> <PlasmicSlot className={rh.cls$slotIconSlot2()} value={args.iconSlot2 || "abc"} defaultContent={<></>}/> {showArgsAgain() && args.iconSlot2} </div>` ) ); }); it("serialize nodes in user added attributes and handle moved node", function () { const nameInIdToUuid = new Map([ ["Root", "Root"], ["Btn", "2345"], ["Img", "3456"], ]); const base = new CodeVersion( `<div className={rh.clsRoot()}> <Button className={rh.clsBtn()}/> <img className={rh.clsImg()}></img> </div>`, nameInIdToUuid ); const edited = new CodeVersion( `<div className={rh.clsRoot()}> <Button className={rh.clsBtn()} icon={<img className={rh.clsImg()} tabIndex={1}></img>}/> </div>`, nameInIdToUuid ); const newV = new CodeVersion( `<div className={rh.clsRoot()}> <Button className={rh.clsBtn()}/> <img className={rh.clsImg2()}></img> </div>`, new Map([ ["Root", "Root"], ["Btn", "2345"], ["Img2", "3456"], ]) ); // When the result is only one node, we follow edited version to add the // fragment or not. expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted( `<div className={rh.clsRoot()}> <Button className={rh.clsBtn()} icon={<img className={rh.clsImg2()} tabIndex={1}></img>}/> </div>` ) ); }); it("parse and serialize nodes in spreador attribute", function () { const nameInIdToUuid = new Map([ ["Root", "Root"], ["Btn", "2345"], ["Img", "3456"], ]); const base = new CodeVersion( `<div className={rh.clsRoot()}> <Button className={rh.clsBtn()} {...rh.propsBtn()}/> <img className={rh.clsImg()}></img> </div>`, nameInIdToUuid ); const edited = new CodeVersion( `<div className={rh.clsRoot()}> <Button className={rh.clsBtn()} {...{icon: <img className={rh.clsImg()} tabIndex={1}></img>}}/> </div>`, nameInIdToUuid ); const newV = new CodeVersion( `<div className={rh.clsRoot()}> <Button className={rh.clsBtn()}/> <img className={rh.clsImg2()}></img> </div>`, new Map([ ["Root", "Root"], ["Btn", "2345"], ["Img2", "3456"], ]) ); expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted( `<div className={rh.clsRoot()}> <Button className={rh.clsBtn()} {...{ icon: <img className={rh.clsImg2()} tabIndex={1}></img> }}/> </div>` ) ); }); it("parse, preserve and merge secondary nodes when primary node remains", function () { const nameInIdToUuid = new Map([ ["Root", "Root"], ["Btn", "2345"], ["Img", "3456"], ["Link", "4567"], ]); const base = new CodeVersion( `<div className={rh.clsRoot()}> <Button className={rh.clsBtn()} {...rh.propsBtn()}/> {rh.showImg() && <img className={rh.clsImg()}></img>} {rh.showLink() && <a className={rh.clsLink()}></a>} </div>`, nameInIdToUuid ); const edited = new CodeVersion( `<div className={rh.clsRoot()}> {(() => { return (<> <Button className={rh.clsBtn()} {...rh.propsBtn()}/> {rh.showImg() && <img className={rh.clsImg() + " myClass"} tabIndex={1}></img>} {rh.showLink() && <a className={rh.clsLink()}></a>} </>); })()} </div>`, nameInIdToUuid ); const newV = new CodeVersion( `<div className={rh.clsRoot()}> <Button className={rh.clsBtn()} {...rh.propsBtn()}/> {rh.showImg2() && <img className={rh.clsImg2()} {...rh.propsImg2()}></img>} <a className={rh.clsLink2()}></a> </div>`, new Map([ ["Root", "Root"], ["Btn", "2345"], ["Img2", "3456"], ["Link2", "4567"], ]) ); expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual( formatted( `<div className={rh.clsRoot()}> {(() => { return (<> <Button className={rh.clsBtn()} {...rh.propsBtn()}/> {rh.showImg2() && <img className={rh.clsImg2() + " myClass"} {...rh.propsImg2()} tabIndex={1}></img>} {true && <a className={rh.clsLink2()}></a>} </>); })()} </div>` ) ); }); it("parse but delete secondary nodes when primary node was deleted", function () { const nameInIdToUuid = new Map([ ["Root", "Root"], ["Btn", "2345"], ["Img", "3456"], ]); const base = new CodeVersion( `<div className={rh.clsRoot()}> <Button className={rh.clsBtn()} {...rh.propsBtn()}/> <img className={rh.clsImg()}></img> </div>`, nameInIdToUuid ); const edited = new CodeVersion( `<div className={rh.clsRoot()}> {(() => { return (<> <Button className={rh.clsBtn()} {...rh.propsBtn()}/> <img className={rh.clsImg() + " myClass"} tabIndex={1}></img> </>); })()} </div>`, nameInIdToUuid ); const newV = new CodeVersion( `<div className={rh.clsRoot()}> {rh.showImg2() && <img className={rh.clsImg2()} {...rh.propsImg2()}></img>} </div>`, new Map([ ["Root", "Root"], ["Btn", "2345"], ["Img2", "3456"], ]) ); // When the result is only one node, we follow edited version to add the // fragment or not. expect( code( renameAndSerializePlasmicASTNode(newV.root, { newVersion: newV, editedVersion: edited, baseVersion: base, }) ) ).toEqual(formatted(`<div className={rh.clsRoot()}></div>`)); }); it("projectSyncMetadataModel", function () { const m = new ProjectSyncMetadataModel([ new ComponentSkeletonModel( "001", new Map<string, string>([ ["a", "1"], ["b", "2"], ]), "content 001" ), new ComponentSkeletonModel( "002", new Map<string, string>([ ["c", "3"], ["d", "4"], ]), "content 002" ), ]); expect(JSON.stringify(m)).toEqual( `[{"uuid":"001","nameInIdToUuid":[["a","1"],["b","2"]],"fileContent":"content 001"},{"uuid":"002","nameInIdToUuid":[["c","3"],["d","4"]],"fileContent":"content 002"}]` ); const deser = ProjectSyncMetadataModel.fromJson(JSON.stringify(m)); expect(deser.components.length).toBe(2); expect(deser.components[0].uuid).toEqual("001"); expect(deser.components[0].fileContent).toEqual("content 001"); expect(deser.components[0].nameInIdToUuid).toEqual( m.components[0].nameInIdToUuid ); expect(deser.components[1].uuid).toEqual("002"); expect(deser.components[1].fileContent).toEqual("content 002"); expect(deser.components[1].nameInIdToUuid).toEqual( m.components[1].nameInIdToUuid ); }); it("mergeFiles should work", async function () { const componentByUuid = new Map<string, ComponentInfoForMerge>(); componentByUuid.set("comp1", { // edited version of the code, i.e. the entire file. editedFile: ` import React, { ReactNode } from "react"; import { hasVariant, DefaultFlexStack, FlexStack } from "@plasmicapp/react-web"; import { PlasmicCodeSandboxDialogContent__RenderHelper, PlasmicCodeSandboxDialogContent__VariantsArgs, PlasmicCodeSandboxDialogContent__VariantsType, PlasmicCodeSandboxDialogContent__TriggerStateType } from "./PP__CodeSandboxDialogContent"; // plasmic-import: f68b061e-0f85-41c1-8707-3ba9f634f1af/render import Button from "../Button"; // plasmic-import: 4SYnkOQLd5/component import { PlasmicButton__VariantsArgs } from "../../../plasmic/PlasmicButton"; // plasmic-import: 4SYnkOQLd5/renderer import Dropdown from "./Dropdown"; // plasmic-import: a200b79f-288d-4306-be99-e5fd221b8ba6/component import { PlasmicDropdown__VariantsArgs } from "./PP__Dropdown"; // plasmic-import: a200b79f-288d-4306-be99-e5fd221b8ba6/renderer import DropdownItem from "./DropdownItem"; // plasmic-import: f4c2f0bb-8dce-49c7-a106-65abe9e70e51/component import { PlasmicDropdownItem__VariantsArgs } from "./PP__DropdownItem"; // plasmic-import: f4c2f0bb-8dce-49c7-a106-65abe9e70e51/renderer import IconButton from "../../IconButton"; // plasmic-import: cfe92-5RW/component import { PlasmicIconButton__VariantsArgs } from "../../../plasmic/PlasmicIconButton"; // plasmic-import: cfe92-5RW/renderer import * as antd from "antd"; // plasmic-import: the-uuid/jsBundle function Comp1() { // plasmic-managed-start const rh = new PlasmicTreeRow__RenderHelper(variants, args, props.className); // plasmic-managed-end // plasmic-managed-jsx/2 return <div className={rh.clsRoot()} onMouseEnter={ rh.onMouseEnterRoot} onMouseLeave={() => { rh.onMouseLeaveRoot(); myEventHandler(); }} onClick={handleClick}> Hello World <div className={rh.clsHint()}>{rh.childStrHint()}</div> </div>; }`, newFile: ` import { hasVariant, DefaultFlexStack, FlexStack } from "@plasmicapp/react-web"; import { PlasmicCodeSandboxDialogContent__RenderHelper, PlasmicCodeSandboxDialogContent__VariantsArgs, PlasmicCodeSandboxDialogContent__VariantsType, PlasmicCodeSandboxDialogContent__TriggerStateType } from "./PP__CodeSandboxDialogContent"; // plasmic-import: f68b061e-0f85-41c1-8707-3ba9f634f1af/render import Button from "../Button"; // plasmic-import: 4SYnkOQLd5/component import { PlasmicButton__VariantsArgs } from "../../../plasmic/PlasmicButton"; // plasmic-import: 4SYnkOQLd5/renderer import Dropdown from "./Dropdown"; // plasmic-import: a200b79f-288d-4306-be99-e5fd221b8ba6/component import { PlasmicDropdown__VariantsArgs } from "./PP__Dropdown"; // plasmic-import: a200b79f-288d-4306-be99-e5fd221b8ba6/renderer import DropdownItem from "./DropdownItem"; // plasmic-import: f4c2f0bb-8dce-49c7-a106-65abe9e70e51/component import { PlasmicDropdownItem__VariantsArgs } from "./PP__DropdownItem"; // plasmic-import: f4c2f0bb-8dce-49c7-a106-65abe9e70e51/renderer import IconButton from "../../IconButton"; // plasmic-import: cfe92-5RW/component import { PlasmicIconButton__VariantsArgs } from "../../../plasmic/PlasmicIconButton"; // plasmic-import: cfe92-5RW/renderer import * as antd from "antd"; // plasmic-import: the-uuid/jsBundle function Comp1() { // plasmic-managed-start const rh = new PlasmicTreeRow__RenderHelper(variants, args, props.className); // plasmic-managed-end // plasmic-managed-jsx/3 return <div className={ rh.clsNewRoot()} onMouseEnter={ rh.onMouseEnterNewRoot} onMouseLeave={rh.onMouseLeaveNewRoot} onMouseDown={rh.onMouseDownNewRoot}> <div className={rh.clsHint()}>{rh.childStrHint()}</div> </div>; }`, // map for newCode newNameInIdToUuid: new Map([ ["NewRoot", "Root"], ["Hint", "Hint"], ]), }); const baseInfo = new ProjectSyncMetadataModel([ new ComponentSkeletonModel( "comp1", new Map([ ["Root", "Root"], ["Hint", "Hint"], ]), ` import { hasVariant, DefaultFlexStack, FlexStack } from "@plasmicapp/react-web"; import { PlasmicCodeSandboxDialogContent__RenderHelper, PlasmicCodeSandboxDialogContent__VariantsArgs, PlasmicCodeSandboxDialogContent__VariantsType, PlasmicCodeSandboxDialogContent__TriggerStateType } from "./PP__CodeSandboxDialogContent"; // plasmic-import: f68b061e-0f85-41c1-8707-3ba9f634f1af/render import Button from "../Button"; // plasmic-import: 4SYnkOQLd5/component import { PlasmicButton__VariantsArgs } from "../../../plasmic/PlasmicButton"; // plasmic-import: 4SYnkOQLd5/renderer import Dropdown from "./Dropdown"; // plasmic-import: a200b79f-288d-4306-be99-e5fd221b8ba6/component import { PlasmicDropdown__VariantsArgs } from "./PP__Dropdown"; // plasmic-import: a200b79f-288d-4306-be99-e5fd221b8ba6/renderer import DropdownItem from "./DropdownItem"; // plasmic-import: f4c2f0bb-8dce-49c7-a106-65abe9e70e51/component import { PlasmicDropdownItem__VariantsArgs } from "./PP__DropdownItem"; // plasmic-import: f4c2f0bb-8dce-49c7-a106-65abe9e70e51/renderer import IconButton from "../../IconButton"; // plasmic-import: cfe92-5RW/component import { PlasmicIconButton__VariantsArgs } from "../../../plasmic/PlasmicIconButton"; // plasmic-import: cfe92-5RW/renderer import * as antd from "antd"; // plasmic-import: the-uuid/jsBundle function Comp1() { // plasmic-managed-start const rh = new PlasmicTreeRow__RenderHelper(variants, args, props.className); // plasmic-managed-end // plasmic-managed-jsx/2 return <div className={ rh.clsRoot() } onMouseEnter={ rh.onMouseEnterRoot } onMouseLeave={rh.onMouseLeaveRoot} onMouseDown={rh.onMouseDownRoot}> <div className={rh.clsHint()}>{rh.childStrHint()}</div> </div>; }` ), ]); const merged = await mergeFiles(componentByUuid, "pid", () => Promise.resolve(baseInfo) ); expect(merged?.size).toEqual(1); expect(merged?.get("comp1")).toEqual( formatted(` import React, {ReactNode} from "react"; import { hasVariant, DefaultFlexStack, FlexStack } from "@plasmicapp/react-web"; import { PlasmicCodeSandboxDialogContent__RenderHelper, PlasmicCodeSandboxDialogContent__VariantsArgs, PlasmicCodeSandboxDialogContent__VariantsType, PlasmicCodeSandboxDialogContent__TriggerStateType } from "./PP__CodeSandboxDialogContent"; // plasmic-import: f68b061e-0f85-41c1-8707-3ba9f634f1af/render import Button from "../Button"; // plasmic-import: 4SYnkOQLd5/component import { PlasmicButton__VariantsArgs } from "../../../plasmic/PlasmicButton"; // plasmic-import: 4SYnkOQLd5/renderer import Dropdown from "./Dropdown"; // plasmic-import: a200b79f-288d-4306-be99-e5fd221b8ba6/component import { PlasmicDropdown__VariantsArgs } from "./PP__Dropdown"; // plasmic-import: a200b79f-288d-4306-be99-e5fd221b8ba6/renderer import DropdownItem from "./DropdownItem"; // plasmic-import: f4c2f0bb-8dce-49c7-a106-65abe9e70e51/component import { PlasmicDropdownItem__VariantsArgs } from "./PP__DropdownItem"; // plasmic-import: f4c2f0bb-8dce-49c7-a106-65abe9e70e51/renderer import IconButton from "../../IconButton"; // plasmic-import: cfe92-5RW/component import { PlasmicIconButton__VariantsArgs } from "../../../plasmic/PlasmicIconButton"; // plasmic-import: cfe92-5RW/renderer import * as antd from "antd"; // plasmic-import: the-uuid/jsBundle function Comp1() { // plasmic-managed-start const rh = new PlasmicTreeRow__RenderHelper(variants, args, props.className); // plasmic-managed-end // plasmic-managed-jsx/3 return <div className={rh.clsNewRoot()} onMouseEnter={rh.onMouseEnterNewRoot} onMouseLeave={() => { rh.onMouseLeaveNewRoot(); myEventHandler(); }} onClick={handleClick}> Hello World <div className={rh.clsHint()}>{rh.childStrHint()}</div> </div>; }`) ); }); it("mergeFiles should work when base is missing", async function () { const componentByUuid = new Map<string, ComponentInfoForMerge>(); componentByUuid.set("comp1", { // edited version of the code, i.e. the entire file. editedFile: ` import React, { ReactNode } from "react"; import { hasVariant, DefaultFlexStack, FlexStack } from "@plasmicapp/react-web"; function Comp1() { const rh = new PlasmicTreeRow__RenderHelper(variants, args, props.className); // plasmic-managed-jsx/2 return (<div className={rh.clsRoot()} onClick={handleClick}> Hello </div>); }`, newFile: ` import { hasVariant, DefaultFlexStack, FlexStack } from "@plasmicapp/react-web"; function Comp1() { const rh = new PlasmicTreeRow__RenderHelper(variants, args, props.className); // plasmic-managed-jsx/3 return (<div className={rh.clsRoot()}> World </div>); }`, // map for newCode newNameInIdToUuid: new Map([["NewRoot", "Root"]]), }); const warningInfos = new Map<string, WarningInfo>(); const merged = await mergeFiles( componentByUuid, "pid", () => Promise.reject("no metadata"), undefined, true, warningInfos ); expect(merged?.size).toEqual(1); expect(merged?.get("comp1")).toEqual( formatted(` import React, {ReactNode} from "react"; import { hasVariant, DefaultFlexStack, FlexStack } from "@plasmicapp/react-web"; function Comp1() { const rh = new PlasmicTreeRow__RenderHelper(variants, args, props.className); // plasmic-managed-jsx/2 return (<div className={rh.clsRoot()} onClick={handleClick}> Hello </div>); } // Please perform merge with the following JSX manually. \`// plasmic-managed-jsx/3 return (<div className={rh.clsRoot()}>World</div>;);\` `) ); expect(warningInfos.size).toBe(1); expect(warningInfos.get("comp1")?.rawWarnings().length).toBe(1); }); it("mergeFiles should generate warning for secondary nodes", async function () { const componentByUuid = new Map<string, ComponentInfoForMerge>(); componentByUuid.set("comp1", { // edited version of the code, i.e. the entire file. editedFile: ` import React, { ReactNode } from "react"; import { hasVariant, DefaultFlexStack, FlexStack } from "@plasmicapp/react-web"; function Comp1() { const rh = new PlasmicTreeRow__RenderHelper(variants, args, props.className); // plasmic-managed-jsx/2 return (<div className={rh.clsRoot()} onClick={handleClick}> <> <img className={rh.clsImg1()} /> <img className={rh.clsImg2()} /> </> </div>); }`, newFile: ` import { hasVariant, DefaultFlexStack, FlexStack } from "@plasmicapp/react-web"; function Comp1() { const rh = new PlasmicTreeRow__RenderHelper(variants, args, props.className); // plasmic-managed-jsx/3 return (<div className={rh.clsRoot()}> <img className={rh.clsImg1()} {...rh.propsImg1()}/> <img className={rh.clsImg2()} {...rh.propsImg2()}/> </div>); }`, // map for newCode newNameInIdToUuid: new Map([ ["Root", "1"], ["Img1", "2"], ["Img2", "3"], ]), }); const baseInfo = new ProjectSyncMetadataModel([ new ComponentSkeletonModel( "comp1", new Map([ ["Root", "1"], ["Img1", "2"], ["Img2", "3"], ]), ` import React, { ReactNode } from "react"; import { hasVariant, DefaultFlexStack, FlexStack } from "@plasmicapp/react-web"; function Comp1() { const rh = new PlasmicTreeRow__RenderHelper(variants, args, props.className); // plasmic-managed-jsx/2 return (<div className={rh.clsRoot()}> <img className={rh.clsImg1()} /> <img className={rh.clsImg2()} /> </div>); }` ), ]); const warningInfos = new Map<string, WarningInfo>(); const merged = await mergeFiles( componentByUuid, "pid", () => Promise.resolve(baseInfo), undefined, true, warningInfos ); expect(merged?.size).toEqual(1); expect(merged?.get("comp1")).toEqual( formatted(` import React, { ReactNode } from "react"; import { hasVariant, DefaultFlexStack, FlexStack } from "@plasmicapp/react-web"; function Comp1() { const rh = new PlasmicTreeRow__RenderHelper(variants, args, props.className); // plasmic-managed-jsx/3 return (<div className={rh.clsRoot()} onClick={handleClick}> <> <img className={rh.clsImg1()} {...rh.propsImg1()} /> <img className={rh.clsImg2()} {...rh.propsImg2()} /> </> </div>); }`) ); expect(warningInfos.size).toBe(1); expect( warningInfos.get("comp1")?.secondaryNodes()[0]?.jsxElement.nameInId ).toEqual("Img2"); }); it("mergeFiles should work for real case", async function () { const componentByUuid = new Map<string, ComponentInfoForMerge>(); const nameInIdToUuid = new Map<string, string>([ ["Root", "Oz-F5C0WGXN"], ["LeftIconSlots", "sKbPJ8fWkM1"], ["Triangle", "i6n7PKYuGNj"], ["9MoAVl56zyD", "9MoAVl56zyD"], ["Type", "_QNTnDc_j61"], ["TZ4YvnJs1m0", "TZ4YvnJs1m0"], ["WJT3dUu2L1W", "WJT3dUu2L1W"], ["LabelSlot", "9lGLLbeby4I"], ["$slotLabel", "Gq5p747FfXZ"], ["8931QcJ2RU2", "8931QcJ2RU2"], ["RightIconSlots", "y1kg2VDXYYI"], ["Display", "hc8CIIePquV"], ["GgSsc5c_XYW", "ggSsc5c_XYW"], ["More", "ZlFyfu63cGO"], ["NskLZmZ2M3D", "NskLZmZ2M3D"], ]); componentByUuid.set("comp1", { // edited version of the code, i.e. the entire file. editedFile: ` // This is a skeleton starter React component generated by Plasmic. import React, { ReactNode } from "react"; import PlasmicTreeRow, { PlasmicTreeRow__RenderHelper, PlasmicTreeRow__VariantsArgs, PlasmicTreeRow__VariantsType, PlasmicTreeRow__TriggerStateType as TriggerStateType } from "../gen/PlasmicTreeRow"; import { hasVariant, DefaultFlexStack, FlexStack } from "@plasmicapp/react-web"; interface TreeRowProps { label?: ReactNode; type?: ReactNode; triangle?: ReactNode; display?: ReactNode; more?: ReactNode; types?: PlasmicTreeRow__VariantsArgs["types"]; states?: PlasmicTreeRow__VariantsArgs["states"]; // Required className prop is used for positioning this component className?: string; } function TreeRow(props: TreeRowProps) { const variants = { types: props.types, states: props.states }; const args = { label: props.label, type: props.type, triangle: props.triangle, display: props.display, more: props.more }; const myVar = 1; const rh = new PlasmicTreeRow__RenderHelper(variants, args, props.className); // plasmic-managed-jsx/66 return ( <DefaultFlexStack {...rh.propsRoot()}> <div className={rh.clsLeftIconSlots()}> {args.triangle || <div {...rh.props9MoAVl56zyD()} />} {args.type || ( <> {rh.showTZ4YvnJs1m0() && <div {...rh.propsTZ4YvnJs1m0()} />} {rh.showWJT3dUu2L1W() && <div {...rh.propsWJT3dUu2L1W()} />} </> )} </div> <PlasmicSlot className={rh.cls$slotLabel()} value={args.label} defaultContent={"Tree Row Label"}> </PlasmicSlot> <DefaultFlexStack className={rh.clsRightIconSlots()}> {args.display || <div {...rh.propsGgSsc5c_XYW()} />} {args.more || <div {...rh.propsNskLZmZ2M3D()} />} </DefaultFlexStack> </DefaultFlexStack> ); } export default TreeRow as React.FunctionComponent<TreeRowProps>;`, newFile: ` // This is a skeleton starter React component generated by Plasmic. import React, { ReactNode } from "react"; import { PlasmicTreeRow__RenderHelper, PlasmicTreeRow__VariantsArgs, PlasmicTreeRow__VariantsType, PlasmicTreeRow__TriggerStateType } from "../gen/PlasmicTreeRow"; import {PersonalAccessToken} from "../gen/PersonalAccessToken"; import { hasVariant, DefaultFlexStack, FlexStack } from "@plasmicapp/react-web"; interface TreeRowProps { label?: ReactNode; type?: ReactNode; triangle?: ReactNode; display?: ReactNode; more?: ReactNode; types?: PlasmicTreeRow__VariantsArgs["types"]; states?: PlasmicTreeRow__VariantsArgs["states"]; // Required className prop is used for positioning this component className?: string; } function TreeRow(props: TreeRowProps) { const variants = { types: props.types, states: props.states }; const args = { label: props.label, type: props.type, triangle: props.triangle, display: props.display, more: props.more }; const rh = new PlasmicTreeRow__RenderHelper(variants, args, props.className); // plasmic-managed-jsx/66 return ( <DefaultFlexStack {...rh.propsRoot()}> <div className={rh.clsLeftIconSlots()}> {args.triangle || <div {...rh.props9MoAVl56zyD()} />} {args.type || ( <> {rh.showTZ4YvnJs1m0() && <div {...rh.propsTZ4YvnJs1m0()} />} {rh.showWJT3dUu2L1W() && <div {...rh.propsWJT3dUu2L1W()} />} </> )} </div> <PlasmicSlot className={rh.cls$slotLabel()} value={args.label} defaultContent={"Tree Row Label"}> </PlasmicSlot> <DefaultFlexStack className={rh.clsRightIconSlots()}> {args.display || <div {...rh.propsGgSsc5c_XYW()} />} {args.more || <div {...rh.propsNskLZmZ2M3D()} />} </DefaultFlexStack> </DefaultFlexStack> ); } export default TreeRow as React.FunctionComponent<TreeRowProps>;`, // map for newCode newNameInIdToUuid: nameInIdToUuid, }); const baseInfo = new ProjectSyncMetadataModel([ new ComponentSkeletonModel( "comp1", nameInIdToUuid, ` // This is a skeleton starter React component generated by Plasmic. import React, { ReactNode } from "react"; import { PlasmicTreeRow__RenderHelper, PlasmicTreeRow__VariantsArgs, PlasmicTreeRow__VariantsType, PlasmicTreeRow__TriggerStateType } from "../gen/PlasmicTreeRow"; // plasmic-import: rxCVTHM-KfP/render import { hasVariant, DefaultFlexStack, FlexStack } from "@plasmicapp/react-web"; interface TreeRowProps { label?: ReactNode; type?: ReactNode; triangle?: ReactNode; display?: ReactNode; more?: ReactNode; types?: PlasmicTreeRow__VariantsArgs["types"]; states?: PlasmicTreeRow__VariantsArgs["states"]; // Required className prop is used for positioning this component className?: string; } function TreeRow(props: TreeRowProps) { const variants = { types: props.types, states: props.states }; const args = { label: props.label, type: props.type, triangle: props.triangle, display: props.display, more: props.more }; const rh = new PlasmicTreeRow__RenderHelper(variants, args, props.className); // plasmic-managed-jsx/66 return ( <DefaultFlexStack {...rh.propsRoot()}> <div className={rh.clsLeftIconSlots()}> {args.triangle || <div {...rh.props9MoAVl56zyD()} />} {args.type || ( <> {rh.showTZ4YvnJs1m0() && <div {...rh.propsTZ4YvnJs1m0()} />} {rh.showWJT3dUu2L1W() && <div {...rh.propsWJT3dUu2L1W()} />} </> )} </div> <PlasmicSlot className={rh.cls$slotLabel()} value={args.label} defaultContent={"Tree Row Label"}> </PlasmicSlot> <DefaultFlexStack className={rh.clsRightIconSlots()}> {args.display || <div {...rh.propsGgSsc5c_XYW()} />} {args.more || <div {...rh.propsNskLZmZ2M3D()} />} </DefaultFlexStack> </DefaultFlexStack> ); } export default TreeRow as React.FunctionComponent<TreeRowProps>;` ), ]); const merged = await mergeFiles(componentByUuid, "pid", () => Promise.resolve(baseInfo) ); expect(merged?.size).toEqual(1); expect(merged?.get("comp1")).toEqual( formatted(` // This is a skeleton starter React component generated by Plasmic. import React, { ReactNode } from "react"; import PlasmicTreeRow, { PlasmicTreeRow__RenderHelper, PlasmicTreeRow__VariantsArgs, PlasmicTreeRow__VariantsType, PlasmicTreeRow__TriggerStateType as TriggerStateType, PlasmicTreeRow__TriggerStateType } from "../gen/PlasmicTreeRow"; import { hasVariant, DefaultFlexStack, FlexStack } from "@plasmicapp/react-web"; import {PersonalAccessToken} from "../gen/PersonalAccessToken"; interface TreeRowProps { label?: ReactNode; type?: ReactNode; triangle?: ReactNode; display?: ReactNode; more?: ReactNode; types?: PlasmicTreeRow__VariantsArgs["types"]; states?: PlasmicTreeRow__VariantsArgs["states"]; // Required className prop is used for positioning this component className?: string; } function TreeRow(props: TreeRowProps) { const variants = { types: props.types, states: props.states }; const args = { label: props.label, type: props.type, triangle: props.triangle, display: props.display, more: props.more }; const myVar = 1; const rh = new PlasmicTreeRow__RenderHelper(variants, args, props.className); // plasmic-managed-jsx/66 return ( <DefaultFlexStack {...rh.propsRoot()}> <div className={rh.clsLeftIconSlots()}> {args.triangle || <div {...rh.props9MoAVl56zyD()} />} {args.type || ( <> {rh.showTZ4YvnJs1m0() && <div {...rh.propsTZ4YvnJs1m0()} />} {rh.showWJT3dUu2L1W() && <div {...rh.propsWJT3dUu2L1W()} />} </> )} </div> <PlasmicSlot className={rh.cls$slotLabel()} value={args.label} defaultContent={"Tree Row Label"}> </PlasmicSlot> <DefaultFlexStack className={rh.clsRightIconSlots()}> {args.display || <div {...rh.propsGgSsc5c_XYW()} />} {args.more || <div {...rh.propsNskLZmZ2M3D()} />} </DefaultFlexStack> </DefaultFlexStack> ); } export default TreeRow as React.FunctionComponent<TreeRowProps>;`) ); }); });
the_stack
export type DateTime = any; /* The &#x60;BigDecimal&#x60; scalar type represents signed fractional values with arbitrary precision. */ export type BigDecimal = any; /* The &#x60;BigInt&#x60; scalar type represents non-fractional signed whole numeric values. BigInt can represent arbitrary big values. */ export type BigInt = any; /* The &#x60;Long&#x60; scalar type represents non-fractional signed whole numeric values. Long can represent values between -(2^63) and 2^63 - 1. */ export type Long = any; /* An object with an ID */ export interface Node { id: string; /* The id of the object. */ } export interface Query { allCars: Car[]; allFiles: File[]; allUsers: User[]; _allCarsMeta: _QueryMeta; _allFilesMeta: _QueryMeta; _allUsersMeta: _QueryMeta; Car: Car | null; File: File | null; User: User | null; user: User | null; node: Node | null; /* Fetches an object given its ID */ } export interface Car extends Node { createdAt: DateTime; id: string; make: string | null; model: string | null; photoURL: string | null; price: number | null; updatedAt: DateTime; year: number | null; } export interface File extends Node { contentType: string; createdAt: DateTime; id: string; name: string; secret: string; size: number; updatedAt: DateTime; url: string; } export interface User extends Node { createdAt: DateTime; id: string; updatedAt: DateTime; } /* Meta information about the query. */ export interface _QueryMeta { count: number; } export interface Mutation { createCar: Car | null; createFile: File | null; updateCar: Car | null; updateFile: File | null; updateUser: User | null; updateOrCreateCar: Car | null; updateOrCreateFile: File | null; updateOrCreateUser: User | null; deleteCar: Car | null; deleteFile: File | null; deleteUser: User | null; createUser: User | null; } export interface Subscription { Car: CarSubscriptionPayload | null; File: FileSubscriptionPayload | null; User: UserSubscriptionPayload | null; } export interface CarSubscriptionPayload { mutation: _ModelMutationType; node: Car | null; updatedFields: string[]; previousValues: CarPreviousValues | null; } export interface CarPreviousValues { createdAt: DateTime; id: string; make: string | null; model: string | null; photoURL: string | null; price: number | null; updatedAt: DateTime; year: number | null; } export interface FileSubscriptionPayload { mutation: _ModelMutationType; node: File | null; updatedFields: string[]; previousValues: FilePreviousValues | null; } export interface FilePreviousValues { contentType: string; createdAt: DateTime; id: string; name: string; secret: string; size: number; updatedAt: DateTime; url: string; } export interface UserSubscriptionPayload { mutation: _ModelMutationType; node: User | null; updatedFields: string[]; previousValues: UserPreviousValues | null; } export interface UserPreviousValues { createdAt: DateTime; id: string; updatedAt: DateTime; } export interface CarFilter { AND: CarFilter[]; /* Logical AND on all given filters. */ OR: CarFilter[]; /* Logical OR on all given filters. */ createdAt: DateTime | null; createdAt_not: DateTime | null; /* All values that are not equal to given value. */ createdAt_in: DateTime[]; /* All values that are contained in given list. */ createdAt_not_in: DateTime[]; /* All values that are not contained in given list. */ createdAt_lt: DateTime | null; /* All values less than the given value. */ createdAt_lte: DateTime | null; /* All values less than or equal the given value. */ createdAt_gt: DateTime | null; /* All values greater than the given value. */ createdAt_gte: DateTime | null; /* All values greater than or equal the given value. */ id: string | null; id_not: string | null; /* All values that are not equal to given value. */ id_in: string[]; /* All values that are contained in given list. */ id_not_in: string[]; /* All values that are not contained in given list. */ id_lt: string | null; /* All values less than the given value. */ id_lte: string | null; /* All values less than or equal the given value. */ id_gt: string | null; /* All values greater than the given value. */ id_gte: string | null; /* All values greater than or equal the given value. */ id_contains: string | null; /* All values containing the given string. */ id_not_contains: string | null; /* All values not containing the given string. */ id_starts_with: string | null; /* All values starting with the given string. */ id_not_starts_with: string | null; /* All values not starting with the given string. */ id_ends_with: string | null; /* All values ending with the given string. */ id_not_ends_with: string | null; /* All values not ending with the given string. */ make: string | null; make_not: string | null; /* All values that are not equal to given value. */ make_in: string[]; /* All values that are contained in given list. */ make_not_in: string[]; /* All values that are not contained in given list. */ make_lt: string | null; /* All values less than the given value. */ make_lte: string | null; /* All values less than or equal the given value. */ make_gt: string | null; /* All values greater than the given value. */ make_gte: string | null; /* All values greater than or equal the given value. */ make_contains: string | null; /* All values containing the given string. */ make_not_contains: string | null; /* All values not containing the given string. */ make_starts_with: string | null; /* All values starting with the given string. */ make_not_starts_with: string | null; /* All values not starting with the given string. */ make_ends_with: string | null; /* All values ending with the given string. */ make_not_ends_with: string | null; /* All values not ending with the given string. */ model: string | null; model_not: string | null; /* All values that are not equal to given value. */ model_in: string[]; /* All values that are contained in given list. */ model_not_in: string[]; /* All values that are not contained in given list. */ model_lt: string | null; /* All values less than the given value. */ model_lte: string | null; /* All values less than or equal the given value. */ model_gt: string | null; /* All values greater than the given value. */ model_gte: string | null; /* All values greater than or equal the given value. */ model_contains: string | null; /* All values containing the given string. */ model_not_contains: string | null; /* All values not containing the given string. */ model_starts_with: string | null; /* All values starting with the given string. */ model_not_starts_with: string | null; /* All values not starting with the given string. */ model_ends_with: string | null; /* All values ending with the given string. */ model_not_ends_with: string | null; /* All values not ending with the given string. */ photoURL: string | null; photoURL_not: string | null; /* All values that are not equal to given value. */ photoURL_in: string[]; /* All values that are contained in given list. */ photoURL_not_in: string[]; /* All values that are not contained in given list. */ photoURL_lt: string | null; /* All values less than the given value. */ photoURL_lte: string | null; /* All values less than or equal the given value. */ photoURL_gt: string | null; /* All values greater than the given value. */ photoURL_gte: string | null; /* All values greater than or equal the given value. */ photoURL_contains: string | null; /* All values containing the given string. */ photoURL_not_contains: string | null; /* All values not containing the given string. */ photoURL_starts_with: string | null; /* All values starting with the given string. */ photoURL_not_starts_with: string | null; /* All values not starting with the given string. */ photoURL_ends_with: string | null; /* All values ending with the given string. */ photoURL_not_ends_with: string | null; /* All values not ending with the given string. */ price: number | null; price_not: number | null; /* All values that are not equal to given value. */ price_in: number[]; /* All values that are contained in given list. */ price_not_in: number[]; /* All values that are not contained in given list. */ price_lt: number | null; /* All values less than the given value. */ price_lte: number | null; /* All values less than or equal the given value. */ price_gt: number | null; /* All values greater than the given value. */ price_gte: number | null; /* All values greater than or equal the given value. */ updatedAt: DateTime | null; updatedAt_not: DateTime | null; /* All values that are not equal to given value. */ updatedAt_in: DateTime[]; /* All values that are contained in given list. */ updatedAt_not_in: DateTime[]; /* All values that are not contained in given list. */ updatedAt_lt: DateTime | null; /* All values less than the given value. */ updatedAt_lte: DateTime | null; /* All values less than or equal the given value. */ updatedAt_gt: DateTime | null; /* All values greater than the given value. */ updatedAt_gte: DateTime | null; /* All values greater than or equal the given value. */ year: number | null; year_not: number | null; /* All values that are not equal to given value. */ year_in: number[]; /* All values that are contained in given list. */ year_not_in: number[]; /* All values that are not contained in given list. */ year_lt: number | null; /* All values less than the given value. */ year_lte: number | null; /* All values less than or equal the given value. */ year_gt: number | null; /* All values greater than the given value. */ year_gte: number | null; /* All values greater than or equal the given value. */ } export interface FileFilter { AND: FileFilter[]; /* Logical AND on all given filters. */ OR: FileFilter[]; /* Logical OR on all given filters. */ contentType: string | null; contentType_not: string | null; /* All values that are not equal to given value. */ contentType_in: string[]; /* All values that are contained in given list. */ contentType_not_in: string[]; /* All values that are not contained in given list. */ contentType_lt: string | null; /* All values less than the given value. */ contentType_lte: string | null; /* All values less than or equal the given value. */ contentType_gt: string | null; /* All values greater than the given value. */ contentType_gte: string | null; /* All values greater than or equal the given value. */ contentType_contains: string | null; /* All values containing the given string. */ contentType_not_contains: string | null; /* All values not containing the given string. */ contentType_starts_with: string | null; /* All values starting with the given string. */ contentType_not_starts_with: string | null; /* All values not starting with the given string. */ contentType_ends_with: string | null; /* All values ending with the given string. */ contentType_not_ends_with: string | null; /* All values not ending with the given string. */ createdAt: DateTime | null; createdAt_not: DateTime | null; /* All values that are not equal to given value. */ createdAt_in: DateTime[]; /* All values that are contained in given list. */ createdAt_not_in: DateTime[]; /* All values that are not contained in given list. */ createdAt_lt: DateTime | null; /* All values less than the given value. */ createdAt_lte: DateTime | null; /* All values less than or equal the given value. */ createdAt_gt: DateTime | null; /* All values greater than the given value. */ createdAt_gte: DateTime | null; /* All values greater than or equal the given value. */ id: string | null; id_not: string | null; /* All values that are not equal to given value. */ id_in: string[]; /* All values that are contained in given list. */ id_not_in: string[]; /* All values that are not contained in given list. */ id_lt: string | null; /* All values less than the given value. */ id_lte: string | null; /* All values less than or equal the given value. */ id_gt: string | null; /* All values greater than the given value. */ id_gte: string | null; /* All values greater than or equal the given value. */ id_contains: string | null; /* All values containing the given string. */ id_not_contains: string | null; /* All values not containing the given string. */ id_starts_with: string | null; /* All values starting with the given string. */ id_not_starts_with: string | null; /* All values not starting with the given string. */ id_ends_with: string | null; /* All values ending with the given string. */ id_not_ends_with: string | null; /* All values not ending with the given string. */ name: string | null; name_not: string | null; /* All values that are not equal to given value. */ name_in: string[]; /* All values that are contained in given list. */ name_not_in: string[]; /* All values that are not contained in given list. */ name_lt: string | null; /* All values less than the given value. */ name_lte: string | null; /* All values less than or equal the given value. */ name_gt: string | null; /* All values greater than the given value. */ name_gte: string | null; /* All values greater than or equal the given value. */ name_contains: string | null; /* All values containing the given string. */ name_not_contains: string | null; /* All values not containing the given string. */ name_starts_with: string | null; /* All values starting with the given string. */ name_not_starts_with: string | null; /* All values not starting with the given string. */ name_ends_with: string | null; /* All values ending with the given string. */ name_not_ends_with: string | null; /* All values not ending with the given string. */ secret: string | null; secret_not: string | null; /* All values that are not equal to given value. */ secret_in: string[]; /* All values that are contained in given list. */ secret_not_in: string[]; /* All values that are not contained in given list. */ secret_lt: string | null; /* All values less than the given value. */ secret_lte: string | null; /* All values less than or equal the given value. */ secret_gt: string | null; /* All values greater than the given value. */ secret_gte: string | null; /* All values greater than or equal the given value. */ secret_contains: string | null; /* All values containing the given string. */ secret_not_contains: string | null; /* All values not containing the given string. */ secret_starts_with: string | null; /* All values starting with the given string. */ secret_not_starts_with: string | null; /* All values not starting with the given string. */ secret_ends_with: string | null; /* All values ending with the given string. */ secret_not_ends_with: string | null; /* All values not ending with the given string. */ size: number | null; size_not: number | null; /* All values that are not equal to given value. */ size_in: number[]; /* All values that are contained in given list. */ size_not_in: number[]; /* All values that are not contained in given list. */ size_lt: number | null; /* All values less than the given value. */ size_lte: number | null; /* All values less than or equal the given value. */ size_gt: number | null; /* All values greater than the given value. */ size_gte: number | null; /* All values greater than or equal the given value. */ updatedAt: DateTime | null; updatedAt_not: DateTime | null; /* All values that are not equal to given value. */ updatedAt_in: DateTime[]; /* All values that are contained in given list. */ updatedAt_not_in: DateTime[]; /* All values that are not contained in given list. */ updatedAt_lt: DateTime | null; /* All values less than the given value. */ updatedAt_lte: DateTime | null; /* All values less than or equal the given value. */ updatedAt_gt: DateTime | null; /* All values greater than the given value. */ updatedAt_gte: DateTime | null; /* All values greater than or equal the given value. */ url: string | null; url_not: string | null; /* All values that are not equal to given value. */ url_in: string[]; /* All values that are contained in given list. */ url_not_in: string[]; /* All values that are not contained in given list. */ url_lt: string | null; /* All values less than the given value. */ url_lte: string | null; /* All values less than or equal the given value. */ url_gt: string | null; /* All values greater than the given value. */ url_gte: string | null; /* All values greater than or equal the given value. */ url_contains: string | null; /* All values containing the given string. */ url_not_contains: string | null; /* All values not containing the given string. */ url_starts_with: string | null; /* All values starting with the given string. */ url_not_starts_with: string | null; /* All values not starting with the given string. */ url_ends_with: string | null; /* All values ending with the given string. */ url_not_ends_with: string | null; /* All values not ending with the given string. */ } export interface UserFilter { AND: UserFilter[]; /* Logical AND on all given filters. */ OR: UserFilter[]; /* Logical OR on all given filters. */ createdAt: DateTime | null; createdAt_not: DateTime | null; /* All values that are not equal to given value. */ createdAt_in: DateTime[]; /* All values that are contained in given list. */ createdAt_not_in: DateTime[]; /* All values that are not contained in given list. */ createdAt_lt: DateTime | null; /* All values less than the given value. */ createdAt_lte: DateTime | null; /* All values less than or equal the given value. */ createdAt_gt: DateTime | null; /* All values greater than the given value. */ createdAt_gte: DateTime | null; /* All values greater than or equal the given value. */ id: string | null; id_not: string | null; /* All values that are not equal to given value. */ id_in: string[]; /* All values that are contained in given list. */ id_not_in: string[]; /* All values that are not contained in given list. */ id_lt: string | null; /* All values less than the given value. */ id_lte: string | null; /* All values less than or equal the given value. */ id_gt: string | null; /* All values greater than the given value. */ id_gte: string | null; /* All values greater than or equal the given value. */ id_contains: string | null; /* All values containing the given string. */ id_not_contains: string | null; /* All values not containing the given string. */ id_starts_with: string | null; /* All values starting with the given string. */ id_not_starts_with: string | null; /* All values not starting with the given string. */ id_ends_with: string | null; /* All values ending with the given string. */ id_not_ends_with: string | null; /* All values not ending with the given string. */ updatedAt: DateTime | null; updatedAt_not: DateTime | null; /* All values that are not equal to given value. */ updatedAt_in: DateTime[]; /* All values that are contained in given list. */ updatedAt_not_in: DateTime[]; /* All values that are not contained in given list. */ updatedAt_lt: DateTime | null; /* All values less than the given value. */ updatedAt_lte: DateTime | null; /* All values less than or equal the given value. */ updatedAt_gt: DateTime | null; /* All values greater than the given value. */ updatedAt_gte: DateTime | null; /* All values greater than or equal the given value. */ } export interface UpdateCar { id: string; make: string | null; model: string | null; photoURL: string | null; price: number | null; year: number | null; } export interface CreateCar { make: string | null; model: string | null; photoURL: string | null; price: number | null; year: number | null; } export interface UpdateFile { id: string; name: string | null; } export interface CreateFile { name: string; } export interface UpdateUser { id: string; } export interface CarSubscriptionFilter { AND: CarSubscriptionFilter[]; /* Logical AND on all given filters. */ OR: CarSubscriptionFilter[]; /* Logical OR on all given filters. */ mutation_in: _ModelMutationType[]; /* The subscription event gets dispatched when it&#x27;s listed in mutation_in */ updatedFields_contains: string | null; /* The subscription event gets only dispatched when one of the updated fields names is included in this list */ updatedFields_contains_every: string[]; /* The subscription event gets only dispatched when all of the field names included in this list have been updated */ updatedFields_contains_some: string[]; /* The subscription event gets only dispatched when some of the field names included in this list have been updated */ node: CarSubscriptionFilterNode | null; } export interface CarSubscriptionFilterNode { createdAt: DateTime | null; createdAt_not: DateTime | null; /* All values that are not equal to given value. */ createdAt_in: DateTime[]; /* All values that are contained in given list. */ createdAt_not_in: DateTime[]; /* All values that are not contained in given list. */ createdAt_lt: DateTime | null; /* All values less than the given value. */ createdAt_lte: DateTime | null; /* All values less than or equal the given value. */ createdAt_gt: DateTime | null; /* All values greater than the given value. */ createdAt_gte: DateTime | null; /* All values greater than or equal the given value. */ id: string | null; id_not: string | null; /* All values that are not equal to given value. */ id_in: string[]; /* All values that are contained in given list. */ id_not_in: string[]; /* All values that are not contained in given list. */ id_lt: string | null; /* All values less than the given value. */ id_lte: string | null; /* All values less than or equal the given value. */ id_gt: string | null; /* All values greater than the given value. */ id_gte: string | null; /* All values greater than or equal the given value. */ id_contains: string | null; /* All values containing the given string. */ id_not_contains: string | null; /* All values not containing the given string. */ id_starts_with: string | null; /* All values starting with the given string. */ id_not_starts_with: string | null; /* All values not starting with the given string. */ id_ends_with: string | null; /* All values ending with the given string. */ id_not_ends_with: string | null; /* All values not ending with the given string. */ make: string | null; make_not: string | null; /* All values that are not equal to given value. */ make_in: string[]; /* All values that are contained in given list. */ make_not_in: string[]; /* All values that are not contained in given list. */ make_lt: string | null; /* All values less than the given value. */ make_lte: string | null; /* All values less than or equal the given value. */ make_gt: string | null; /* All values greater than the given value. */ make_gte: string | null; /* All values greater than or equal the given value. */ make_contains: string | null; /* All values containing the given string. */ make_not_contains: string | null; /* All values not containing the given string. */ make_starts_with: string | null; /* All values starting with the given string. */ make_not_starts_with: string | null; /* All values not starting with the given string. */ make_ends_with: string | null; /* All values ending with the given string. */ make_not_ends_with: string | null; /* All values not ending with the given string. */ model: string | null; model_not: string | null; /* All values that are not equal to given value. */ model_in: string[]; /* All values that are contained in given list. */ model_not_in: string[]; /* All values that are not contained in given list. */ model_lt: string | null; /* All values less than the given value. */ model_lte: string | null; /* All values less than or equal the given value. */ model_gt: string | null; /* All values greater than the given value. */ model_gte: string | null; /* All values greater than or equal the given value. */ model_contains: string | null; /* All values containing the given string. */ model_not_contains: string | null; /* All values not containing the given string. */ model_starts_with: string | null; /* All values starting with the given string. */ model_not_starts_with: string | null; /* All values not starting with the given string. */ model_ends_with: string | null; /* All values ending with the given string. */ model_not_ends_with: string | null; /* All values not ending with the given string. */ photoURL: string | null; photoURL_not: string | null; /* All values that are not equal to given value. */ photoURL_in: string[]; /* All values that are contained in given list. */ photoURL_not_in: string[]; /* All values that are not contained in given list. */ photoURL_lt: string | null; /* All values less than the given value. */ photoURL_lte: string | null; /* All values less than or equal the given value. */ photoURL_gt: string | null; /* All values greater than the given value. */ photoURL_gte: string | null; /* All values greater than or equal the given value. */ photoURL_contains: string | null; /* All values containing the given string. */ photoURL_not_contains: string | null; /* All values not containing the given string. */ photoURL_starts_with: string | null; /* All values starting with the given string. */ photoURL_not_starts_with: string | null; /* All values not starting with the given string. */ photoURL_ends_with: string | null; /* All values ending with the given string. */ photoURL_not_ends_with: string | null; /* All values not ending with the given string. */ price: number | null; price_not: number | null; /* All values that are not equal to given value. */ price_in: number[]; /* All values that are contained in given list. */ price_not_in: number[]; /* All values that are not contained in given list. */ price_lt: number | null; /* All values less than the given value. */ price_lte: number | null; /* All values less than or equal the given value. */ price_gt: number | null; /* All values greater than the given value. */ price_gte: number | null; /* All values greater than or equal the given value. */ updatedAt: DateTime | null; updatedAt_not: DateTime | null; /* All values that are not equal to given value. */ updatedAt_in: DateTime[]; /* All values that are contained in given list. */ updatedAt_not_in: DateTime[]; /* All values that are not contained in given list. */ updatedAt_lt: DateTime | null; /* All values less than the given value. */ updatedAt_lte: DateTime | null; /* All values less than or equal the given value. */ updatedAt_gt: DateTime | null; /* All values greater than the given value. */ updatedAt_gte: DateTime | null; /* All values greater than or equal the given value. */ year: number | null; year_not: number | null; /* All values that are not equal to given value. */ year_in: number[]; /* All values that are contained in given list. */ year_not_in: number[]; /* All values that are not contained in given list. */ year_lt: number | null; /* All values less than the given value. */ year_lte: number | null; /* All values less than or equal the given value. */ year_gt: number | null; /* All values greater than the given value. */ year_gte: number | null; /* All values greater than or equal the given value. */ } export interface FileSubscriptionFilter { AND: FileSubscriptionFilter[]; /* Logical AND on all given filters. */ OR: FileSubscriptionFilter[]; /* Logical OR on all given filters. */ mutation_in: _ModelMutationType[]; /* The subscription event gets dispatched when it&#x27;s listed in mutation_in */ updatedFields_contains: string | null; /* The subscription event gets only dispatched when one of the updated fields names is included in this list */ updatedFields_contains_every: string[]; /* The subscription event gets only dispatched when all of the field names included in this list have been updated */ updatedFields_contains_some: string[]; /* The subscription event gets only dispatched when some of the field names included in this list have been updated */ node: FileSubscriptionFilterNode | null; } export interface FileSubscriptionFilterNode { contentType: string | null; contentType_not: string | null; /* All values that are not equal to given value. */ contentType_in: string[]; /* All values that are contained in given list. */ contentType_not_in: string[]; /* All values that are not contained in given list. */ contentType_lt: string | null; /* All values less than the given value. */ contentType_lte: string | null; /* All values less than or equal the given value. */ contentType_gt: string | null; /* All values greater than the given value. */ contentType_gte: string | null; /* All values greater than or equal the given value. */ contentType_contains: string | null; /* All values containing the given string. */ contentType_not_contains: string | null; /* All values not containing the given string. */ contentType_starts_with: string | null; /* All values starting with the given string. */ contentType_not_starts_with: string | null; /* All values not starting with the given string. */ contentType_ends_with: string | null; /* All values ending with the given string. */ contentType_not_ends_with: string | null; /* All values not ending with the given string. */ createdAt: DateTime | null; createdAt_not: DateTime | null; /* All values that are not equal to given value. */ createdAt_in: DateTime[]; /* All values that are contained in given list. */ createdAt_not_in: DateTime[]; /* All values that are not contained in given list. */ createdAt_lt: DateTime | null; /* All values less than the given value. */ createdAt_lte: DateTime | null; /* All values less than or equal the given value. */ createdAt_gt: DateTime | null; /* All values greater than the given value. */ createdAt_gte: DateTime | null; /* All values greater than or equal the given value. */ id: string | null; id_not: string | null; /* All values that are not equal to given value. */ id_in: string[]; /* All values that are contained in given list. */ id_not_in: string[]; /* All values that are not contained in given list. */ id_lt: string | null; /* All values less than the given value. */ id_lte: string | null; /* All values less than or equal the given value. */ id_gt: string | null; /* All values greater than the given value. */ id_gte: string | null; /* All values greater than or equal the given value. */ id_contains: string | null; /* All values containing the given string. */ id_not_contains: string | null; /* All values not containing the given string. */ id_starts_with: string | null; /* All values starting with the given string. */ id_not_starts_with: string | null; /* All values not starting with the given string. */ id_ends_with: string | null; /* All values ending with the given string. */ id_not_ends_with: string | null; /* All values not ending with the given string. */ name: string | null; name_not: string | null; /* All values that are not equal to given value. */ name_in: string[]; /* All values that are contained in given list. */ name_not_in: string[]; /* All values that are not contained in given list. */ name_lt: string | null; /* All values less than the given value. */ name_lte: string | null; /* All values less than or equal the given value. */ name_gt: string | null; /* All values greater than the given value. */ name_gte: string | null; /* All values greater than or equal the given value. */ name_contains: string | null; /* All values containing the given string. */ name_not_contains: string | null; /* All values not containing the given string. */ name_starts_with: string | null; /* All values starting with the given string. */ name_not_starts_with: string | null; /* All values not starting with the given string. */ name_ends_with: string | null; /* All values ending with the given string. */ name_not_ends_with: string | null; /* All values not ending with the given string. */ secret: string | null; secret_not: string | null; /* All values that are not equal to given value. */ secret_in: string[]; /* All values that are contained in given list. */ secret_not_in: string[]; /* All values that are not contained in given list. */ secret_lt: string | null; /* All values less than the given value. */ secret_lte: string | null; /* All values less than or equal the given value. */ secret_gt: string | null; /* All values greater than the given value. */ secret_gte: string | null; /* All values greater than or equal the given value. */ secret_contains: string | null; /* All values containing the given string. */ secret_not_contains: string | null; /* All values not containing the given string. */ secret_starts_with: string | null; /* All values starting with the given string. */ secret_not_starts_with: string | null; /* All values not starting with the given string. */ secret_ends_with: string | null; /* All values ending with the given string. */ secret_not_ends_with: string | null; /* All values not ending with the given string. */ size: number | null; size_not: number | null; /* All values that are not equal to given value. */ size_in: number[]; /* All values that are contained in given list. */ size_not_in: number[]; /* All values that are not contained in given list. */ size_lt: number | null; /* All values less than the given value. */ size_lte: number | null; /* All values less than or equal the given value. */ size_gt: number | null; /* All values greater than the given value. */ size_gte: number | null; /* All values greater than or equal the given value. */ updatedAt: DateTime | null; updatedAt_not: DateTime | null; /* All values that are not equal to given value. */ updatedAt_in: DateTime[]; /* All values that are contained in given list. */ updatedAt_not_in: DateTime[]; /* All values that are not contained in given list. */ updatedAt_lt: DateTime | null; /* All values less than the given value. */ updatedAt_lte: DateTime | null; /* All values less than or equal the given value. */ updatedAt_gt: DateTime | null; /* All values greater than the given value. */ updatedAt_gte: DateTime | null; /* All values greater than or equal the given value. */ url: string | null; url_not: string | null; /* All values that are not equal to given value. */ url_in: string[]; /* All values that are contained in given list. */ url_not_in: string[]; /* All values that are not contained in given list. */ url_lt: string | null; /* All values less than the given value. */ url_lte: string | null; /* All values less than or equal the given value. */ url_gt: string | null; /* All values greater than the given value. */ url_gte: string | null; /* All values greater than or equal the given value. */ url_contains: string | null; /* All values containing the given string. */ url_not_contains: string | null; /* All values not containing the given string. */ url_starts_with: string | null; /* All values starting with the given string. */ url_not_starts_with: string | null; /* All values not starting with the given string. */ url_ends_with: string | null; /* All values ending with the given string. */ url_not_ends_with: string | null; /* All values not ending with the given string. */ } export interface UserSubscriptionFilter { AND: UserSubscriptionFilter[]; /* Logical AND on all given filters. */ OR: UserSubscriptionFilter[]; /* Logical OR on all given filters. */ mutation_in: _ModelMutationType[]; /* The subscription event gets dispatched when it&#x27;s listed in mutation_in */ updatedFields_contains: string | null; /* The subscription event gets only dispatched when one of the updated fields names is included in this list */ updatedFields_contains_every: string[]; /* The subscription event gets only dispatched when all of the field names included in this list have been updated */ updatedFields_contains_some: string[]; /* The subscription event gets only dispatched when some of the field names included in this list have been updated */ node: UserSubscriptionFilterNode | null; } export interface UserSubscriptionFilterNode { createdAt: DateTime | null; createdAt_not: DateTime | null; /* All values that are not equal to given value. */ createdAt_in: DateTime[]; /* All values that are contained in given list. */ createdAt_not_in: DateTime[]; /* All values that are not contained in given list. */ createdAt_lt: DateTime | null; /* All values less than the given value. */ createdAt_lte: DateTime | null; /* All values less than or equal the given value. */ createdAt_gt: DateTime | null; /* All values greater than the given value. */ createdAt_gte: DateTime | null; /* All values greater than or equal the given value. */ id: string | null; id_not: string | null; /* All values that are not equal to given value. */ id_in: string[]; /* All values that are contained in given list. */ id_not_in: string[]; /* All values that are not contained in given list. */ id_lt: string | null; /* All values less than the given value. */ id_lte: string | null; /* All values less than or equal the given value. */ id_gt: string | null; /* All values greater than the given value. */ id_gte: string | null; /* All values greater than or equal the given value. */ id_contains: string | null; /* All values containing the given string. */ id_not_contains: string | null; /* All values not containing the given string. */ id_starts_with: string | null; /* All values starting with the given string. */ id_not_starts_with: string | null; /* All values not starting with the given string. */ id_ends_with: string | null; /* All values ending with the given string. */ id_not_ends_with: string | null; /* All values not ending with the given string. */ updatedAt: DateTime | null; updatedAt_not: DateTime | null; /* All values that are not equal to given value. */ updatedAt_in: DateTime[]; /* All values that are contained in given list. */ updatedAt_not_in: DateTime[]; /* All values that are not contained in given list. */ updatedAt_lt: DateTime | null; /* All values less than the given value. */ updatedAt_lte: DateTime | null; /* All values less than or equal the given value. */ updatedAt_gt: DateTime | null; /* All values greater than the given value. */ updatedAt_gte: DateTime | null; /* All values greater than or equal the given value. */ } export interface AllCarsQueryArgs { filter: CarFilter | null; orderBy: CarOrderBy | null; skip: number | null; after: string | null; before: string | null; first: number | null; last: number | null; } export interface AllFilesQueryArgs { filter: FileFilter | null; orderBy: FileOrderBy | null; skip: number | null; after: string | null; before: string | null; first: number | null; last: number | null; } export interface AllUsersQueryArgs { filter: UserFilter | null; orderBy: UserOrderBy | null; skip: number | null; after: string | null; before: string | null; first: number | null; last: number | null; } export interface AllCarsMetaQueryArgs { filter: CarFilter | null; orderBy: CarOrderBy | null; skip: number | null; after: string | null; before: string | null; first: number | null; last: number | null; } export interface AllFilesMetaQueryArgs { filter: FileFilter | null; orderBy: FileOrderBy | null; skip: number | null; after: string | null; before: string | null; first: number | null; last: number | null; } export interface AllUsersMetaQueryArgs { filter: UserFilter | null; orderBy: UserOrderBy | null; skip: number | null; after: string | null; before: string | null; first: number | null; last: number | null; } export interface CarQueryArgs { id: string | null; } export interface FileQueryArgs { id: string | null; secret: string | null; url: string | null; } export interface UserQueryArgs { id: string | null; } export interface NodeQueryArgs { id: string; /* The ID of an object */ } export interface CreateCarMutationArgs { make: string | null; model: string | null; photoURL: string | null; price: number | null; year: number | null; } export interface CreateFileMutationArgs { name: string; } export interface UpdateCarMutationArgs { id: string; make: string | null; model: string | null; photoURL: string | null; price: number | null; year: number | null; } export interface UpdateFileMutationArgs { id: string; name: string | null; } export interface UpdateUserMutationArgs { id: string; } export interface UpdateOrCreateCarMutationArgs { update: UpdateCar; create: CreateCar; } export interface UpdateOrCreateFileMutationArgs { update: UpdateFile; create: CreateFile; } export interface UpdateOrCreateUserMutationArgs { update: UpdateUser; } export interface DeleteCarMutationArgs { id: string; } export interface DeleteFileMutationArgs { id: string; } export interface DeleteUserMutationArgs { id: string; } export interface CarSubscriptionArgs { filter: CarSubscriptionFilter | null; } export interface FileSubscriptionArgs { filter: FileSubscriptionFilter | null; } export interface UserSubscriptionArgs { filter: UserSubscriptionFilter | null; } export type CarOrderBy = "createdAt_ASC" | "createdAt_DESC" | "id_ASC" | "id_DESC" | "make_ASC" | "make_DESC" | "model_ASC" | "model_DESC" | "photoURL_ASC" | "photoURL_DESC" | "price_ASC" | "price_DESC" | "updatedAt_ASC" | "updatedAt_DESC" | "year_ASC" | "year_DESC"; export type FileOrderBy = "contentType_ASC" | "contentType_DESC" | "createdAt_ASC" | "createdAt_DESC" | "id_ASC" | "id_DESC" | "name_ASC" | "name_DESC" | "secret_ASC" | "secret_DESC" | "size_ASC" | "size_DESC" | "updatedAt_ASC" | "updatedAt_DESC" | "url_ASC" | "url_DESC"; export type UserOrderBy = "createdAt_ASC" | "createdAt_DESC" | "id_ASC" | "id_DESC" | "updatedAt_ASC" | "updatedAt_DESC"; export type _ModelMutationType = "CREATED" | "UPDATED" | "DELETED"; export namespace AllCars { export type Variables = { } export type Query = { allCars: AllCars[]; } export type AllCars = { id: string; make: string | null; model: string | null; year: number | null; } } export namespace Car { export type Variables = { id: string; } export type Query = { Car: Car | null; } export type Car = { make: string | null; model: string | null; photoURL: string | null; price: number | null; } }
the_stack
import React, { PureComponent } from 'react' import ConsentManagerBuilder from '../consent-manager-builder' import Container from './container' import { ADVERTISING_CATEGORIES, FUNCTIONAL_CATEGORIES } from './categories' import { CategoryPreferences, Destination, ConsentManagerProps, PreferenceDialogTemplate } from '../types' const zeroValuePreferences: CategoryPreferences = { marketingAndAnalytics: null, advertising: null, functional: null } const defaultPreferencesDialogTemplate: PreferenceDialogTemplate = { headings: { allowValue: 'Allow', categoryValue: 'Category', purposeValue: 'Purpose', toolsValue: 'Tools' }, checkboxes: { noValue: 'No', yesValue: 'Yes' }, actionButtons: { cancelValue: 'Cancel', saveValue: 'Save' }, cancelDialogButtons: { cancelValue: 'Yes, Cancel', backValue: 'Go Back' }, categories: [ { key: 'functional', name: 'Functional', description: 'To monitor the performance of our site and to enhance your browsing experience.', example: 'For example, these tools enable you to communicate with us via live chat.' }, { key: 'marketing', name: 'Marketing and Analytics', description: 'To understand user behavior in order to provide you with a more relevant browsing experience or personalize the content on our site.', example: 'For example, we collect information about which pages you visit to help us present more relevant information.' }, { key: 'advertising', name: 'Advertising', description: 'To personalize and measure the effectiveness of advertising on our site and other websites.', example: 'For example, we may serve you a personalized ad based on the pages you visit on our site.' }, { key: 'essential', name: 'Essential', description: 'We use browser cookies that are necessary for the site to work as intended.', example: 'For example, we store your website data collection preferences so we can honor them if you return to our site. You can disable these cookies in your browser settings but if you do the site may not work as intended.' } ] } export default class ConsentManager extends PureComponent<ConsentManagerProps, {}> { static displayName = 'ConsentManager' static defaultProps = { otherWriteKeys: [], shouldRequireConsent: () => true, implyConsentOnInteraction: false, onError: undefined, cookieDomain: undefined, cookieName: undefined, cookieExpires: undefined, customCategories: undefined, bannerActionsBlock: undefined, bannerHideCloseButton: false, bannerTextColor: '#fff', bannerSubContent: 'You can change your preferences at any time.', bannerBackgroundColor: '#1f4160', preferencesDialogTitle: 'Website Data Collection Preferences', cancelDialogTitle: 'Are you sure you want to cancel?', defaultDestinationBehavior: 'disable', preferencesDialogTemplate: defaultPreferencesDialogTemplate } render() { const { writeKey, otherWriteKeys, shouldRequireConsent, implyConsentOnInteraction, cookieDomain, cookieName, cookieExpires, bannerContent, bannerActionsBlock, bannerSubContent, bannerTextColor, bannerBackgroundColor, bannerHideCloseButton, bannerAsModal, preferencesDialogTitle, preferencesDialogContent, cancelDialogTitle, cancelDialogContent, customCategories, defaultDestinationBehavior, cdnHost, preferencesDialogTemplate, onError } = this.props return ( <ConsentManagerBuilder onError={onError} writeKey={writeKey} otherWriteKeys={otherWriteKeys} shouldRequireConsent={shouldRequireConsent} cookieDomain={cookieDomain} cookieName={cookieName} cookieExpires={cookieExpires} initialPreferences={this.getInitialPreferences()} mapCustomPreferences={this.handleMapCustomPreferences} customCategories={customCategories} defaultDestinationBehavior={defaultDestinationBehavior} cdnHost={cdnHost} > {({ destinations, customCategories, newDestinations, preferences, isConsentRequired, setPreferences, resetPreferences, saveConsent, havePreferencesChanged, workspaceAddedNewDestinations }) => { return ( <Container customCategories={customCategories} destinations={destinations} newDestinations={newDestinations} preferences={preferences} isConsentRequired={isConsentRequired} setPreferences={setPreferences} resetPreferences={resetPreferences} saveConsent={saveConsent} closeBehavior={this.props.closeBehavior} implyConsentOnInteraction={ implyConsentOnInteraction ?? ConsentManager.defaultProps.implyConsentOnInteraction } bannerContent={bannerContent} bannerSubContent={bannerSubContent} bannerActionsBlock={bannerActionsBlock} bannerHideCloseButton={bannerHideCloseButton} bannerTextColor={bannerTextColor || ConsentManager.defaultProps.bannerTextColor} bannerBackgroundColor={ bannerBackgroundColor || ConsentManager.defaultProps.bannerBackgroundColor } bannerAsModal={bannerAsModal} preferencesDialogTitle={preferencesDialogTitle} preferencesDialogContent={preferencesDialogContent} cancelDialogTitle={cancelDialogTitle} cancelDialogContent={cancelDialogContent} havePreferencesChanged={havePreferencesChanged} defaultDestinationBehavior={defaultDestinationBehavior} workspaceAddedNewDestinations={workspaceAddedNewDestinations} preferencesDialogTemplate={ preferencesDialogTemplate ? this.mergeTemplates(preferencesDialogTemplate, defaultPreferencesDialogTemplate) : ConsentManager.defaultProps.preferencesDialogTemplate } /> ) }} </ConsentManagerBuilder> ) } mergeTemplates = ( newProps: PreferenceDialogTemplate, defaultPreferencesDialogTemplate: PreferenceDialogTemplate ): PreferenceDialogTemplate => { const headingsMerge = { ...defaultPreferencesDialogTemplate.headings, ...newProps.headings } const checkboxesMerge = { ...defaultPreferencesDialogTemplate.checkboxes, ...newProps.checkboxes } const actionButtonsMerge = { ...defaultPreferencesDialogTemplate.actionButtons, ...newProps.actionButtons } const cancelDialogButtonsMerge = { ...defaultPreferencesDialogTemplate.cancelDialogButtons, ...newProps.cancelDialogButtons } const categoriesMerge = defaultPreferencesDialogTemplate?.categories!.map(category => ({ ...category, ...newProps?.categories?.find(c => c.key === category.key) })) return { headings: headingsMerge, checkboxes: checkboxesMerge, actionButtons: actionButtonsMerge, cancelDialogButtons: cancelDialogButtonsMerge, categories: categoriesMerge } } getInitialPreferences = () => { const { initialPreferences, customCategories } = this.props if (initialPreferences) { return initialPreferences } if (!customCategories) { return zeroValuePreferences } const initialCustomPreferences = {} Object.keys(customCategories).forEach(category => { initialCustomPreferences[category] = null }) return initialCustomPreferences } handleMapCustomPreferences = (destinations: Destination[], preferences: CategoryPreferences) => { const { customCategories } = this.props const destinationPreferences = {} const customPreferences = {} if (customCategories) { for (const preferenceName of Object.keys(customCategories)) { const value = preferences[preferenceName] if (typeof value === 'boolean') { customPreferences[preferenceName] = value } else { customPreferences[preferenceName] = true } } destinations.forEach(destination => { // Mark custom categories Object.entries(customCategories).forEach(([categoryName, { integrations }]) => { const consentAlreadySetToFalse = destinationPreferences[destination.id] === false const shouldSetConsent = integrations.includes(destination.id) if (shouldSetConsent && !consentAlreadySetToFalse) { destinationPreferences[destination.id] = customPreferences[categoryName] } }) }) return { destinationPreferences, customPreferences } } // Default unset preferences to true (for implicit consent) for (const preferenceName of Object.keys(preferences)) { const value = preferences[preferenceName] if (typeof value === 'boolean') { customPreferences[preferenceName] = value } else { customPreferences[preferenceName] = true } } const customPrefs = customPreferences as CategoryPreferences for (const destination of destinations) { // Mark advertising destinations if ( ADVERTISING_CATEGORIES.find(c => c === destination.category) && destinationPreferences[destination.id] !== false ) { destinationPreferences[destination.id] = customPrefs.advertising } // Mark function destinations if ( FUNCTIONAL_CATEGORIES.find(c => c === destination.category) && destinationPreferences[destination.id] !== false ) { destinationPreferences[destination.id] = customPrefs.functional } // Fallback to marketing if (!(destination.id in destinationPreferences)) { destinationPreferences[destination.id] = customPrefs.marketingAndAnalytics } } return { destinationPreferences, customPreferences } } }
the_stack
import {Component, Input, OnChanges, OnInit, SimpleChanges} from "@angular/core"; import {FormGroup} from "@angular/forms"; import * as _ from "underscore" import {Templates} from "../../feed-mgr/services/TemplateTypes"; import {FieldConfig} from "../../dynamic-form/model/FieldConfig"; import {FieldGroup} from "../../dynamic-form/model/FieldGroup"; import {InputType} from "../../dynamic-form/model/InputText"; import {DynamicFormBuilder} from "../../dynamic-form/services/dynamic-form-builder"; import {DynamicFormFieldGroupBuilder} from "../../dynamic-form/services/dynamic-form-field-group-builder"; import {DynamicFormService} from "../../dynamic-form/services/dynamic-form.service"; import {ConfigurationFieldBuilder} from "../../dynamic-form/services/field-config-builder"; import {Property} from "../model/property"; import {ProcessorRef} from "./processor-ref"; export class FieldConfigurationState { formFieldOrder = 0; /** * Map of the inputProcessorId to the controls related to that input */ inputFieldsMap: { [key: string]: FieldConfig<any>[] } = {}; /** * Map of all processors other inputs to array of configs */ processorFieldMap: { [key: string]: FieldConfig<any>[] } = {}; /** * Return all fieldconfig objects for a given input processor */ getFieldsForInput(processorId: string, emptyArrayIfNull: boolean = true): FieldConfig<any>[] { if (!this.hasInputFields(processorId) && emptyArrayIfNull) { return []; } else { return this.inputFieldsMap[processorId]; } } /** * are there input fields defined for the processor * param {string} processorId * return {boolean} */ hasInputFields(processorId: string) { return this.inputFieldsMap[processorId] != undefined; } /** * are there fields defined for the processor * param {string} processorId * return {boolean} */ hasNonInputFields(processorId: string) { return this.processorFieldMap[processorId] != undefined; } /** * Return all fieldconfig objects for a given input processor */ getFieldsForNonInput(processorId: string, emptyArrayIfNull: boolean = true): FieldConfig<any>[] { if (!this.hasNonInputFields(processorId) && emptyArrayIfNull) { return []; } else { return this.processorFieldMap[processorId]; } } getAndIncrementFieldOrder() { let order = this.formFieldOrder; this.formFieldOrder++; return order; } incrementAndGetFieldOrder() { this.formFieldOrder++; return this.formFieldOrder; } reset() { this.formFieldOrder = 0; this.inputFieldsMap = {}; this.processorFieldMap = {} } } export class FieldConfigurationBuilder { formGroupBuilder: DynamicFormFieldGroupBuilder; constructor(private state: FieldConfigurationState, private addSectionHeader: boolean) { } public createFormFields(processor: ProcessorRef, properties?: Property[]): FieldConfig<any>[] { this.formGroupBuilder = new DynamicFormBuilder().column(); return this.toFieldConfig(processor as any, (properties != null) ? properties : processor.processor.properties); } private buildField(property: Templates.Property): FieldConfig<any> { let field: FieldConfig<any>; //build the generic options to be used by all fields let label = property.propertyDescriptor.displayName || property.propertyDescriptor.name; let configBuilder = new ConfigurationFieldBuilder().setKey(property.nameKey).setOrder(this.state.getAndIncrementFieldOrder()).setPlaceholder(label).setRequired(property.required).setValue(property.value).setModel(property).setHint(property.propertyDescriptor.description); if(property.displayValue){ configBuilder.setReadonlyValue(property.displayValue) } if (this.isInputText(property)) { //get the correct input type let type = property.renderType; if (property.sensitive) { type = "password"; } let inputType: InputType = <InputType>InputType[type] || InputType.text; //create the field field = this.formGroupBuilder.text().update(configBuilder).setType(inputType).build(); } else if (property.renderType == "select") { field = this.formGroupBuilder.select().update(configBuilder).setOptions(this.getSelectOptions(property)).build() } else if (property.renderType == "radio") { field = this.formGroupBuilder.radio().update(configBuilder).setOptions(this.getSelectOptions(property)).build(); } else if (property.renderType == "checkbox-true-false" || property.renderType == "checkbox-custom") { let trueValue = property.renderOptions['trueValue'] || 'true'; let falseValue = property.renderOptions['falseValue'] || 'false'; field = this.formGroupBuilder.checkbox().update(configBuilder).setTrueValue(trueValue).setFalseValue(falseValue).build(); } else if (property.renderType == "textarea") { field = this.formGroupBuilder.textarea().update(configBuilder).build(); } return field; } /** * convert the property allowable values to label,value objects */ private getSelectOptions(property: Templates.Property): { label: string, value: string }[] { //get the select options let options: ({ label: string, value: string })[] = []; if (property.propertyDescriptor.allowableValues && property.propertyDescriptor.allowableValues.length > 0) { options = (<any[]>property.propertyDescriptor.allowableValues).map(allowableValue => { return {label: allowableValue.displayName, value: allowableValue.value} }); } else if (property.renderOptions && property.renderOptions.selectOptions && property.renderOptions.selectOptions.length > 0) { let selectOptions = JSON.parse(property.renderOptions.selectOptions); options = (<any[]>selectOptions).map(allowableValue => { return {label: allowableValue, value: allowableValue} }); } //add in the not set value if (!property.required) { options.unshift({label: "Not Set", value: ""}); } return options; } private toFieldConfig(processor: Templates.Processor, properties: Property[]): FieldConfig<any>[] { let elements: FieldConfig<any>[] = []; properties.filter((property: Templates.Property) => property.userEditable).map((property: Templates.Property) => { if (!property.uniqueId) { property.uniqueId = _.uniqueId("property-"); } let fieldConfig: FieldConfig<any> = this.buildField(property); if (property.inputProperty) { if (this.state.inputFieldsMap[processor.id] == undefined) { this.state.inputFieldsMap[processor.id] = []; } this.state.inputFieldsMap[processor.id].push(fieldConfig); } else { if (this.state.processorFieldMap[processor.id] == undefined) { this.state.processorFieldMap[processor.id] = []; if (this.addSectionHeader !== false) { //add a new SectionHeader let sectionHeader = this.formGroupBuilder.sectionHeader().setOrder(this.state.getAndIncrementFieldOrder()).setPlaceholder(processor.name).setShowDivider(true).build(); elements.push(sectionHeader); this.state.processorFieldMap[processor.id].push(sectionHeader); } } this.state.processorFieldMap[processor.id].push(fieldConfig); } elements.push(fieldConfig); }); return elements; } private isInputText(property: Templates.Property) { return (property.renderType == null || property.renderType == "text" || property.renderType == "email" || property.renderType == "number" || property.renderType == "password"); } } @Component({ selector: "processor-form", template: ` <dynamic-form [form]="form" [fieldGroups]="fieldGroups" [readonly]="readonly"></dynamic-form> ` }) export class ProcessorFormComponent implements OnChanges, OnInit { @Input() addSectionHeader: boolean | string; @Input() form: FormGroup; @Input() processor: ProcessorRef; @Input() properties: Property | Property[]; @Input() readonly: boolean; fieldGroups = [new FieldGroup()]; private fieldConfigurationState: FieldConfigurationState = new FieldConfigurationState(); constructor(private dynamicFormService: DynamicFormService) { } ngOnInit(): void { } ngOnChanges(changes: SimpleChanges): void { if ((changes.processor || changes.properties || changes.readonly)) { if (this.processor != null) { this.fieldConfigurationState.reset(); new FieldConfigurationBuilder(this.fieldConfigurationState, (this.addSectionHeader !== "false" && this.addSectionHeader !== false)) .createFormFields(this.processor, (typeof this.properties === "undefined" || Array.isArray(this.properties)) ? this.properties as any : [this.properties]) .sort((n1, n2) => { return n1.order - n2.order; }); //populate the form with the correct input processors let inputProcessorFields = this.fieldConfigurationState.getFieldsForInput(this.processor.id); if (inputProcessorFields.length == 0) { inputProcessorFields = this.fieldConfigurationState.getFieldsForNonInput(this.processor.id); } this.fieldGroups[0].fields = inputProcessorFields; this.dynamicFormService.addToFormGroup(inputProcessorFields, this.form); } else { this.fieldGroups = [new FieldGroup()]; } } } }
the_stack
import 'd3-transition'; import { rgb as d3_rgb, } from 'd3-color'; import { scaleOrdinal as d3_scaleOrdinal, schemeCategory10 as d3_schemeCategory10 } from 'd3-scale'; import { BaseType as d3_BaseType, Selection as d3_Selection, select as d3_select, event as d3_event, } from 'd3-selection'; import { zoom as d3_zoom, zoomIdentity as d3_zoomIdentity, } from 'd3-zoom'; import * as fs from 'file-saver'; import {HistoryConfig, HistoryState} from './config'; import {VisibleHistoryNode, VisibleHistoryEdge} from './structures'; import {HistoryGraphData, HistoryNodeData, HistoryTrialNodeData} from './structures'; export class HistoryGraph { config: HistoryConfig; state: HistoryState; graphId: string; zoom: any; transform: any; i: number; div: d3_Selection<d3_BaseType, {}, HTMLElement | null, any>; tooltipDiv: d3_Selection<d3_BaseType, {}, HTMLElement | null, any>; svg: d3_Selection<d3_BaseType, {}, HTMLElement | null, any>; g: d3_Selection<d3_BaseType, {}, HTMLElement | null, any>; hintElement: d3_Selection<d3_BaseType, {}, HTMLElement | null, any>; nodes: VisibleHistoryNode[] = []; versionNodes: VisibleHistoryNode[] = []; edges: VisibleHistoryEdge[] = []; maxX: number = 0; maxY: number = 0; maxId: number = 0; constructor(graphId:string, div: any, config: any = {}) { this.i = 0; var defaultConfig: HistoryConfig = { customSelectNode: (g: HistoryGraph, d: VisibleHistoryNode) => false, customCtrlClick: (g: HistoryGraph, d: VisibleHistoryNode) => false, customForm: (g: HistoryGraph, form: d3_Selection<d3_BaseType, {}, HTMLElement | null, any>) => null, customSize: (g: HistoryGraph) => [g.config.width, g.config.height], hintMessage: "Ctrl+Shift click or ⌘+Shift click to diff trials", width: 200, height: 100, radius: 20, moveX: 20, moveY: 25, moveY2: 10, spacing: 17, margin: 50, fontSize: 10, useTooltip: false, } this.config = (Object as any).assign({}, defaultConfig, config); this.graphId = graphId; this.zoom = d3_zoom() .on("zoom", () => this.zoomFunction()) .on("start", () => d3_select('body').style("cursor", "move")) .on("end", () => d3_select('body').style("cursor", "auto")) .wheelDelta(() => { return -d3_event.deltaY * (d3_event.deltaMode ? 120 : 1) / 2000; }) this.div = d3_select(div); let form = d3_select(div) .append("form") .classed("history-toolbar", true); this.svg = d3_select(div) .append("div") .append("svg") .attr("width", this.config.width) .attr("height", this.config.height) .call(this.zoom) .on("mouseup", () => this.svgMouseUp()); this.state = { selectedNode: null, mouseDownNode: null, justScale: false } // Tooltip this.tooltipDiv = d3_select("body").append("div") .classed("now-tooltip now-history-tooltip", true) .style("opacity", 0) .style("max-width", "250px") .on("mouseout", () => { this.closeTooltip(); }); this.createToolbar(form); this.createMarker('end-arrow', 'endarrow', '#000'); this.g = this.svg.append("g") .attr("id", this._graphId()) .attr("transform", "translate(0,0)") .classed('HistoryGraph', true); } createToolbar(form: d3_Selection<d3_BaseType, {}, HTMLElement | null, any>) { form = form.append("div") .classed("buttons", true); this.config.customForm(this, form); // Reset zoom form.append("a") .classed("toollink", true) .attr("id", "history-" + this.graphId + "-history-zoom") .attr("href", "#") .attr("title", "Restore zoom") .on("click", () => this.restorePosition()) .append("i") .classed("fa fa-eye", true) // Toggle Tooltips let tooltipsToggle = form.append("input") .attr("id", "history-" + this.graphId + "-toolbar-tooltips") .attr("type", "checkbox") .attr("name", "history-toolbar-tooltips") .attr("value", "show") .property("checked", this.config.useTooltip) .on("change", () => { this.closeTooltip(); this.config.useTooltip = tooltipsToggle.property("checked"); }); form.append("label") .attr("for", "history-" + this.graphId + "-toolbar-tooltips") .attr("title", "Show tooltips on mouse hover") .append("i") .classed("fa fa-comment", true) // Download SVG form.append("a") .classed("toollink", true) .attr("id", "history-" + this.graphId + "-download") .attr("href", "#") .attr("title", "Download graph SVG") .on("click", () => { this.download(); }) .append("i") .classed("fa fa-download", true) // Set Font Size let fontToggle = form.append("input") .attr("id", "history-" + this.graphId + "-toolbar-fonts") .attr("type", "checkbox") .attr("name", "history-toolbar-fonts") .attr("value", "show") .property("checked", false) .on("change", () => { let display = fontToggle.property("checked")? "inline-block" : "none"; fontSize.style("display", display); }); form.append("label") .attr("for", "history-" + this.graphId + "-toolbar-fonts") .attr("title", "Set font size") .append("i") .classed("fa fa-font", true) let fontSize = form.append("input") .attr("type", "number") .attr("value", this.config.fontSize) .style("width", "50px") .style("display", "none") .attr("title", "Node font size") .on("change", () => { this.config.fontSize = fontSize.property("value"); this.svg.selectAll("text.trial-id") .attr("font-size", this.config.fontSize); }) // Submit form.append("input") .attr("type", "submit") .attr("name", "prevent-enter") .attr("onclick", "return false;") .style("display", "none"); form.append("div") form.append("div") .text(this.config.hintMessage) .style('font-family', 'sans-serif') .style('font-size', '12px') .style('pointer-events', 'none') } load(data: HistoryGraphData): VisibleHistoryNode[] { let nodes: VisibleHistoryNode[] = [], otherNodes: VisibleHistoryNode[] = [], edges: VisibleHistoryEdge[] = [], spacing = this.config.spacing, margin = this.config.margin; let spacing2 = 2 * spacing, spacing4 = 4 * spacing, start = margin, max = 0, id = 0, last = data.nodes.length - 1, tid = 0, useVersion = false; let levels = []; for (var i = 0; i <= last; i++) { let node: HistoryNodeData = data.nodes[i]; var previous = levels[node.level]; if (previous == undefined) { previous = -1; } var trials = node.trials; if (trials == undefined) { trials = []; } levels[node.level] = Math.max(previous, trials.length); } let levelsy = []; var current = margin; for (var i = 0; i <= levels.length; i++) { levelsy[i] = current current += spacing2 + levels[i] * spacing2; } for (var i = 0; i <= last; i++) { let node: HistoryNodeData = data.nodes[i]; let x: number = start + spacing4 * id; let y: number = levelsy[node.level]; var new_node: VisibleHistoryNode = { id: id, display: node.display, x: x, y: y, title: node.id.toString(), info: node, radius: this.config.radius, gradient: false, status: "finished" }; nodes.push(new_node) if (typeof(node.trials) != "undefined") { useVersion = true; for (var j = 0; j < node.trials.length; j++) { let trialNode: HistoryTrialNodeData = node.trials[j] as HistoryTrialNodeData; let ny = y + (j + 1) * spacing2 + spacing otherNodes.push({ id: tid, display: trialNode.display, x: x + this.config.radius / 2, y: ny, title: trialNode.id.toString(), info: trialNode, tooltip: trialNode.tooltip, radius: this.config.radius / 2, gradient: true, status: trialNode.status }); tid += 1; max = Math.max(max, y); } } else { new_node.tooltip = (node as HistoryTrialNodeData).tooltip; } max = Math.max(max, y); this.maxX = x; id += 1; } max += spacing2; this.maxY = max; this.maxId = Math.max(tid, id); for (var i = 0; i < data.edges.length; i++) { let edge: any = { ...data.edges[i]}; edge.id = edge.source + "-" + edge.target; edge.source = nodes[edge.source]; edge.target = nodes[edge.target]; edges.push(edge as VisibleHistoryEdge); } if (useVersion) { this.nodes = otherNodes; this.versionNodes = nodes; } else { this.nodes = nodes; this.versionNodes = []; } this.edges = edges; this.updateWindow(); this.restorePosition(); this.update(); return nodes; } updateWindow(): void { let size = this.config.customSize(this); this.config.width = size[0]; this.config.height = size[1]; this.svg .attr("width", size[0]) .attr("height", size[1]); } update() { var nodes = this.g.selectAll('g.node') .data(this.nodes, (d: any) => d.id); var edges = this.g.selectAll('g.link') .data(this.edges, (d: any) => d.id); var version = this.g.selectAll('g.version') .data(this.versionNodes, (d: any) => d.id); this.updateNodes(nodes); this.updateVersionNodes(version); this.updateLinks(edges); } restorePosition(): void { let scale = this.config.height / this.maxY; if (scale <= 1.0) { this.svg.call(this.zoom.transform, d3_zoomIdentity .translate( this.config.width - this.maxX * scale - this.config.margin, 0) .scale(scale) ) } else { this.svg.call(this.zoom.transform, d3_zoomIdentity .scale(1) .translate( this.config.width - this.maxX - this.config.margin, 0) ) } this.state.justScale = false; } selectNode(node: VisibleHistoryNode): void { this.state.selectedNode = node; this.config.customSelectNode(this, node); this.svg.selectAll('.node[attr-trial="' + node.title + '"] > rect') .attr('stroke', 'rgb(200, 238, 241)') .classed('selected', true); } selectTrial(trialId: string) { for (var node of this.nodes) { if (node.title == trialId) { this.selectNode(node); return; } } } download(name?: string) { var isFileSaverSupported = false; try { isFileSaverSupported = !!new Blob(); } catch (e) { alert("blob not supported"); } name = (name === undefined)? "history.svg" : name; let gnode: any = this.g.node() var bbox = gnode.getBBox(); var width = this.svg.attr("width"), height = this.svg.attr("height"); this.g.attr("transform", "translate(" + (-bbox.x + 5) +", " +(-bbox.y + 5) +")"); let svgNode: any = this.svg .attr("title", "Trial") .attr("version", 1.1) .attr("width", bbox.width + 10) .attr("height", bbox.height + 10) .attr("xmlns", "http://www.w3.org/2000/svg") .node(); var html = svgNode.parentNode.innerHTML; html = '<svg xmlns:xlink="http://www.w3.org/1999/xlink" ' + html.slice(4); this.svg .attr("width", width) .attr("height", height); this.g.attr("transform", this.transform); if (isFileSaverSupported) { var blob = new Blob([html], {type: "image/svg+xml"}); fs.saveAs(blob, name); } } private closeTooltip(): void { this.tooltipDiv.transition() .duration(500) .style("opacity", 0); this.tooltipDiv.classed("hidden", true); } private showTooltip(d: VisibleHistoryNode) { if (typeof(d.tooltip) == "undefined") { return; } this.tooltipDiv.classed("hidden", false); this.tooltipDiv.transition() .duration(200) .style("opacity", 0.9); this.tooltipDiv.html(d.tooltip) .style("left", (d3_event.pageX - 3) + "px") .style("top", (d3_event.pageY - 28) + "px"); } private createMarker(name: string, cls: string, fill: string) { this.svg.append("svg:defs").selectAll("marker") .data([name]) .enter().append("svg:marker") .attr("id", String) .attr("viewBox", "0 -5 10 10") .attr("refX", 6) .attr("refY", 0) .attr("markerWidth", 3) .attr("markerHeight", 3) .attr("orient", "auto") .append("svg:path") .classed(cls, true) .attr("fill", fill) .attr("d", "M0,-5L10,0L0,5"); } private unselectNode(): void { this.g.selectAll('g.node').filter((cd: VisibleHistoryNode) => { if (this.state.selectedNode == null) { return false; } return cd.id === this.state.selectedNode.id; }).select('rect') .classed('selected', false) .attr("stroke", "#000"); this.state.selectedNode = null; } private nodeMouseDown(d3node: d3_Selection<d3_BaseType, {}, HTMLElement | null, any>, d: VisibleHistoryNode): void { d3_event.stopPropagation(); this.state.mouseDownNode = d; this.closeTooltip(); } private nodeMouseUp(d3node: d3_Selection<d3_BaseType, {}, HTMLElement | null, any>, d: VisibleHistoryNode): void { d3_event.stopPropagation(); if (!this.state.mouseDownNode) { return; } if (this.state.justScale) { this.state.justScale = false; } else { if (d3_event.ctrlKey || d3_event.shiftKey || d3_event.altKey) { this.config.customCtrlClick(this, d); return; } if (this.state.selectedNode) { this.unselectNode(); } d3node .attr('stroke', 'rgb(200, 238, 241)') .classed('selected', true); this.state.selectedNode = d; this.config.customSelectNode(this, d); } this.state.mouseDownNode = null; } private svgMouseUp() { if (this.state.justScale) { this.state.justScale = false; } } private updateVersionNodes(nodes: any) { var nodeEnter = nodes.enter().append("g") .classed("version", true) .attr("attr-trialid", (d: VisibleHistoryNode) => d.title) .attr("transform", (d: VisibleHistoryNode) => { return "translate(" + 0 + "," + 0 + ")"; }) // Circle for new nodes nodeEnter.append('rect') .attr("transform", (d: VisibleHistoryNode) => { return "translate(" + d.x + "," + d.y + ")"; }) .attr('width', (d: VisibleHistoryNode) => 2 * d.radius) .attr('height', (d: VisibleHistoryNode) => 2 * d.radius) .attr('rx', 0) .attr('ry', 0) //.attr('r', ) .attr("stroke", "#000") .attr("stroke-width", "2.5px") .attr("fill", "#F6FBFF") .attr("stroke", "#000") .attr("stroke-width", "2.5px") nodeEnter.append('text') .classed('trial-id', true) .attr('font-family', 'sans-serif') .attr('font-size', this.config.fontSize + 'px') .attr('pointer-events', 'none') .attr('x', (d: VisibleHistoryNode) => d.radius) .attr('y', (d: VisibleHistoryNode) => d.radius + 4) .attr('stroke', '#000') .attr('text-anchor', 'middle') //.attr('font-weight', 'bold') .attr("transform", (d: VisibleHistoryNode) => { return "translate(" + d.x + "," + d.y + ")"; }).text((d: VisibleHistoryNode) => d.display); nodeEnter.merge(nodes); // nodeUpdate nodes.exit().remove(); // nodeExit } private updateNodes(nodes: any) { let self = this; var nodeEnter = nodes.enter().append("g") .classed("node", true) .attr("attr-trialid", (d: VisibleHistoryNode) => d.title) .attr("cursor", "pointer") .attr("transform", (d: VisibleHistoryNode) => { return "translate(" + 0 + "," + 0 + ")"; }) // Circle for new nodes nodeEnter.append('rect') .attr("transform", (d: VisibleHistoryNode) => { return "translate(" + d.x + "," + d.y + ")"; }) .attr('cursor', 'pointer') .attr('title', (d: VisibleHistoryNode) => d.info.display) .attr('width', (d: VisibleHistoryNode) => 2 * d.radius) .attr('height', (d: VisibleHistoryNode) => 2 * d.radius) .attr('rx', (d: VisibleHistoryNode) => 2 * d.radius) .attr('ry', (d: VisibleHistoryNode) => 2 * d.radius) //.attr('r', ) .attr("stroke", "#000") .attr("stroke-width", "2.5px") .attr("fill", function (d: VisibleHistoryNode) { var proportion = Math.round(200 * (1.0 - (parseInt(d.title) / self.maxId)) + 50); if (d.status === 'unfinished') { return d.gradient? d3_rgb(255, proportion, proportion, 255).toString(): "rgb(238, 200, 241)"; } if (d.status === 'finished') { return d.gradient? d3_rgb(proportion, proportion, proportion, 255).toString(): "#F6FBFF"; } if (d.status === 'backup') { return d.gradient? d3_rgb(255, 255, proportion, 255).toString(): "rgb(241, 238, 200)"; } return '#666'; }) .attr("stroke", function(d: VisibleHistoryNode) { return (d3_select(this).classed('selected')) ? 'rgb(200, 238, 241)' : "#000"; }) .attr("stroke-width", "2.5px") .on('mousedown', function(d: VisibleHistoryNode) { self.nodeMouseDown(d3_select(this), d); }).on('mouseup', function (d: VisibleHistoryNode) { self.nodeMouseUp(d3_select(this), d); }).on('mouseover', function (d: VisibleHistoryNode) { if (!self.state.mouseDownNode && self.config.useTooltip) { self.closeTooltip(); self.showTooltip(d); } d3_select(this) .attr('stroke', 'rgb(200, 238, 241)') }).on('mouseout', function (d: VisibleHistoryNode) { d3_select(this) .attr("stroke", (d: VisibleHistoryNode) => { return (d3_select(this).classed('selected')) ? 'rgb(200, 238, 241)' : "#000"; }); }) nodeEnter.append('text') .classed('trial-id', true) .attr('font-family', 'sans-serif') .attr('font-size', this.config.fontSize + 'px') .attr('pointer-events', 'none') .attr('x', (d: VisibleHistoryNode) => d.radius) .attr('y', (d: VisibleHistoryNode) => d.radius + 4) .attr('stroke', '#000') .attr('text-anchor', 'middle') //.attr('font-weight', 'bold') .attr("transform", (d: VisibleHistoryNode) => { return "translate(" + d.x + "," + d.y + ")"; }).text((d: VisibleHistoryNode) => d.gradient? "" : d.display); nodeEnter.merge(nodes); // nodeUpdate nodes.exit().remove(); // nodeExit } private updateLinks(link: any) { // Enter any new links let colors = d3_scaleOrdinal(d3_schemeCategory10); var linkEnter = link.enter().insert('path', 'g') .classed('link', true) .attr('cursor', 'crosshair') .attr('fill', 'none') .attr('stroke', '#000') .attr('stroke-width', '4px'); linkEnter .attr("d", (d: VisibleHistoryEdge) => { var deltaX = d.target.x - d.source.x, deltaY = d.target.y - d.source.y, dist = Math.sqrt(deltaX * deltaX + deltaY * deltaY), normX = deltaX / dist, normY = deltaY / dist, sourcePadding = this.config.radius -5, targetPadding = this.config.radius + (d.right ? 3 : -5), sourceX = d.source.x + this.config.radius + (sourcePadding * normX), sourceY = d.source.y + this.config.radius + (sourcePadding * normY), targetX = d.target.x + this.config.radius - (targetPadding * normX), targetY = d.target.y + this.config.radius - (targetPadding * normY); var step = 0; if (d.level > 0) { step += this.config.moveY; step += (d.level - 1) * this.config.moveY2; } return `M ${sourceX}, ${sourceY} C ${(sourceX - this.config.moveX / 2)} ${sourceY} ${(sourceX - this.config.moveX / 2)} ${(sourceY + 3 * step / 4)} ${(sourceX - this.config.moveX)} ${(sourceY + step)} L ${(sourceX - this.config.moveX)} ${(sourceY + step)} ${(targetX + this.config.moveX)} ${(sourceY + step)} C ${(targetX + this.config.moveX / 2)} ${(sourceY + 3 * step / 4)} ${(targetX + this.config.moveX / 2)} ${sourceY} ${targetX}, ${targetY}`; }) .attr('marker-end', (d: VisibleHistoryEdge) => { return d.right ? 'url(#end-arrow)' : '' }) .attr('stroke', (d: VisibleHistoryEdge) => { return d3_rgb(colors(d.level.toString())).darker().toString(); }); // Update linkEnter.merge(link); // linkUpdate // Remove any exiting links link.exit().remove(); // linkExit } private zoomFunction() { this.state.justScale = true; this.closeTooltip(); this.transform = d3_event.transform; this.g.attr("transform", d3_event.transform); } private _graphId(): string { return "history-graph-" + this.graphId; } }
the_stack
import { Match, MatchGame, Seeding, Stage, Status } from 'brackets-model'; import { BracketKind, ParticipantSlot, Side } from '../types'; import { SetNextOpponent } from '../helpers'; import { ordering } from '../ordering'; import { Create } from '../create'; import { BaseGetter } from './getter'; import * as helpers from '../helpers'; export class BaseUpdater extends BaseGetter { /** * Updates or resets the seeding of a stage. * * @param stageId ID of the stage. * @param seeding A new seeding or null to reset the existing seeding. */ protected async updateSeeding(stageId: number, seeding: Seeding | null): Promise<void> { const stage = await this.storage.select('stage', stageId); if (!stage) throw Error('Stage not found.'); if (seeding && seeding.length !== stage.settings.size) throw Error('The size of the seeding is incorrect.'); const create = new Create(this.storage, { name: stage.name, tournamentId: stage.tournament_id, type: stage.type, settings: stage.settings, seeding: seeding || undefined, }); create.setExisting(stageId); const method = BaseGetter.getSeedingOrdering(stage.type, create); const slots = await create.getSlots(); const matches = await this.getSeedingMatches(stage.id, stage.type); if (!matches) throw Error('Error getting matches associated to the seeding.'); const ordered = ordering[method](slots); await BaseUpdater.assertCanUpdateSeeding(matches, ordered); await create.run(); } /** * Updates a parent match based on its child games. * * @param parentId ID of the parent match. */ protected async updateParentMatch(parentId: number): Promise<void> { const storedParent = await this.storage.select('match', parentId); if (!storedParent) throw Error('Parent not found.'); const games = await this.storage.select('match_game', { parent_id: parentId }); if (!games) throw Error('No match games.'); const parentScores = helpers.getChildGamesResults(games); const parent = helpers.getParentMatchResults(storedParent, parentScores); const stage = await this.storage.select('stage', storedParent.stage_id); if (!stage) throw Error('Stage not found.'); const inRoundRobin = helpers.isRoundRobin(stage); helpers.setParentMatchCompleted(parent, storedParent.child_count, inRoundRobin); await this.updateMatch(storedParent, parent, true); } /** * Throws an error if a match is locked and the new seeding will change this match's participants. * * @param matches The matches stored in the database. * @param slots The slots to check from the new seeding. */ protected static async assertCanUpdateSeeding(matches: Match[], slots: ParticipantSlot[]): Promise<void> { let index = 0; for (const match of matches) { const opponent1 = slots[index++]; const opponent2 = slots[index++]; const locked = helpers.isMatchParticipantLocked(match); if (!locked) continue; if (match.opponent1?.id !== opponent1?.id || match.opponent2?.id !== opponent2?.id) throw Error('A match is locked.'); } } /** * Updates the matches related (previous and next) to a match. * * @param match A match. * @param updatePrevious Whether to update the previous matches. * @param updateNext Whether to update the next matches. */ protected async updateRelatedMatches(match: Match, updatePrevious: boolean, updateNext: boolean): Promise<void> { const { roundNumber, roundCount } = await this.getRoundPositionalInfo(match.round_id); const stage = await this.storage.select('stage', match.stage_id); if (!stage) throw Error('Stage not found.'); const group = await this.storage.select('group', match.group_id); if (!group) throw Error('Group not found.'); const matchLocation = helpers.getMatchLocation(stage.type, group.number); updatePrevious && await this.updatePrevious(match, matchLocation, stage, roundNumber); updateNext && await this.updateNext(match, matchLocation, stage, roundNumber, roundCount); } /** * Updates a match based on a partial match. * * @param stored A reference to what will be updated in the storage. * @param match Input of the update. * @param force Whether to force update locked matches. */ protected async updateMatch(stored: Match, match: Partial<Match>, force?: boolean): Promise<void> { if (!force && helpers.isMatchUpdateLocked(stored)) throw Error('The match is locked.'); const { statusChanged, resultChanged } = helpers.setMatchResults(stored, match); await this.applyMatchUpdate(stored); // Don't update related matches if it's a simple score update. if (!statusChanged && !resultChanged) return; const stage = await this.storage.select('stage', stored.stage_id); if (!stage) throw Error('Stage not found.'); if (!helpers.isRoundRobin(stage)) await this.updateRelatedMatches(stored, statusChanged, resultChanged); } /** * Updates a match and its child games. * * @param match A match. */ protected async applyMatchUpdate(match: Match): Promise<void> { if (!await this.storage.update('match', match.id, match)) throw Error('Could not update the match.'); if (match.child_count === 0) return; const update: Partial<MatchGame> = { opponent1: helpers.toResult(match.opponent1), opponent2: helpers.toResult(match.opponent2), }; if (match.status <= Status.Ready || match.status === Status.Archived) update.status = match.status; if (!await this.storage.update('match_game', { parent_id: match.id }, update)) throw Error('Could not update the match game.'); } /** * Updates the match(es) leading to the current match based on this match results. * * @param match Input of the update. * @param matchLocation Location of the current match. * @param stage The parent stage. * @param roundNumber Number of the round. */ protected async updatePrevious(match: Match, matchLocation: BracketKind, stage: Stage, roundNumber: number): Promise<void> { const previousMatches = await this.getPreviousMatches(match, matchLocation, stage, roundNumber); if (previousMatches.length === 0) return; if (match.status >= Status.Running) await this.archiveMatches(previousMatches); else await this.resetMatchesStatus(previousMatches); } /** * Sets the status of a list of matches to archived. * * @param matches The matches to update. */ protected async archiveMatches(matches: Match[]): Promise<void> { for (const match of matches) { match.status = Status.Archived; await this.applyMatchUpdate(match); } } /** * Resets the status of a list of matches to what it should currently be. * * @param matches The matches to update. */ protected async resetMatchesStatus(matches: Match[]): Promise<void> { for (const match of matches) { match.status = helpers.getMatchStatus(match); await this.applyMatchUpdate(match); } } /** * Updates the match(es) following the current match based on this match results. * * @param match Input of the update. * @param matchLocation Location of the current match. * @param stage The parent stage. * @param roundNumber Number of the round. * @param roundCount Count of rounds. */ protected async updateNext(match: Match, matchLocation: BracketKind, stage: Stage, roundNumber: number, roundCount: number): Promise<void> { const nextMatches = await this.getNextMatches(match, matchLocation, stage, roundNumber, roundCount); if (nextMatches.length === 0) return; const winnerSide = helpers.getMatchResult(match); const actualRoundNumber = (stage.settings.skipFirstRound && matchLocation === 'winner_bracket') ? roundNumber + 1 : roundNumber; if (winnerSide) await this.applyToNextMatches(helpers.setNextOpponent, match, matchLocation, actualRoundNumber, roundCount, nextMatches, winnerSide); else await this.applyToNextMatches(helpers.resetNextOpponent, match, matchLocation, actualRoundNumber, roundCount, nextMatches); } /** * Applies a SetNextOpponent function to matches following the current match. * * @param setNextOpponent The SetNextOpponent function. * @param match The current match. * @param matchLocation Location of the current match. * @param roundNumber Number of the current round. * @param roundCount Count of rounds. * @param nextMatches The matches following the current match. * @param winnerSide Side of the winner in the current match. */ protected async applyToNextMatches(setNextOpponent: SetNextOpponent, match: Match, matchLocation: BracketKind, roundNumber: number, roundCount: number, nextMatches: (Match | null)[], winnerSide?: Side): Promise<void> { if (matchLocation === 'final_group') { if (!nextMatches[0]) throw Error('First next match is null.'); setNextOpponent(nextMatches[0], 'opponent1', match, 'opponent1'); setNextOpponent(nextMatches[0], 'opponent2', match, 'opponent2'); await this.applyMatchUpdate(nextMatches[0]); return; } const nextSide = helpers.getNextSide(match.number, roundNumber, roundCount, matchLocation); if (nextMatches[0]) { setNextOpponent(nextMatches[0], nextSide, match, winnerSide); await this.propagateByeWinners(nextMatches[0]); } if (nextMatches.length !== 2) return; if (!nextMatches[1]) throw Error('Second next match is null.'); // The second match is either the consolation final (single elimination) or a loser bracket match (double elimination). if (matchLocation === 'single_bracket') { setNextOpponent(nextMatches[1], nextSide, match, winnerSide && helpers.getOtherSide(winnerSide)); await this.applyMatchUpdate(nextMatches[1]); } else { const nextSideLB = helpers.getNextSideLoserBracket(match.number, nextMatches[1], roundNumber); setNextOpponent(nextMatches[1], nextSideLB, match, winnerSide && helpers.getOtherSide(winnerSide)); await this.propagateByeWinners(nextMatches[1]); } } /** * Propagates winner against BYEs in related matches. * * @param match The current match. */ protected async propagateByeWinners(match: Match): Promise<void> { helpers.setMatchResults(match, match); await this.applyMatchUpdate(match); if (helpers.hasBye(match)) await this.updateRelatedMatches(match, true, true); } }
the_stack
import { compose, createSelector } from '@ngrx/store'; import { Step, RateType, Entities, Rational, DisplayRateVal, RationalProduct, Product, MatrixResultType, } from '~/models'; import { RateUtility, SimplexUtility, FlowUtility, RecipeUtility, } from '~/utilities'; import * as Factories from '../factories'; import * as Items from '../items'; import * as Preferences from '../preferences'; import * as Recipes from '../recipes'; import * as Settings from '../settings'; import { State } from '../'; import { ProductsState } from './products.reducer'; /* Base selector functions */ const productsState = (state: State): ProductsState => state.productsState; const sIds = (state: ProductsState): string[] => state.ids; const sEntities = (state: ProductsState): Entities<Product> => state.entities; /* Simple selectors */ export const getIds = compose(sIds, productsState); export const getEntities = compose(sEntities, productsState); /* Complex selectors */ export const getBaseProducts = createSelector( getIds, getEntities, Settings.getNormalDataset, (ids, entities, data) => ids.map((i) => entities[i]).filter((p) => data.itemEntities[p.itemId]) ); export const getProductSteps = createSelector( getBaseProducts, Items.getItemSettings, Settings.getDisabledRecipes, Recipes.getAdjustedDataset, Preferences.getSimplexModifiers, (products, itemSettings, disabledRecipes, data, adj) => products?.reduce((e: Entities<[string, Rational][]>, p) => { e[p.itemId] = SimplexUtility.getSteps( p.itemId, itemSettings, disabledRecipes, adj.costInput, adj.costIgnored, data, p.rateType === RateType.Factories, adj.simplex ); return e; }, {}) ); export const getProducts = createSelector( getBaseProducts, getProductSteps, Recipes.getRecipeSettings, Factories.getFactorySettings, Settings.getNormalDataset, (products, productSteps, recipeSettings, factories, data) => products?.map((p) => RecipeUtility.adjustProduct( p, productSteps, recipeSettings, factories, data ) ) ); export const getRationalProducts = createSelector(getProducts, (products) => products.map((p) => new RationalProduct(p)) ); export const getProductsBy = createSelector(getRationalProducts, (products) => products.reduce((e: Entities<RationalProduct[]>, p) => { if (!e[p.rateType]) { e[p.rateType] = []; } e[p.rateType] = [...e[p.rateType], p]; return e; }, {}) ); export const getProductsByItems = createSelector( getProductsBy, (products) => products[RateType.Items] ); export const getProductsByBelts = createSelector( getProductsBy, (products) => products[RateType.Belts] ); export const getProductsByWagons = createSelector( getProductsBy, (products) => products[RateType.Wagons] ); export const getProductsByFactories = createSelector( getProductsBy, (products) => products[RateType.Factories] ); export const getNormalizedRatesByItems = createSelector( getProductsByItems, getProductSteps, Settings.getDisplayRate, (products, productSteps, displayRate) => products?.reduce((e: Entities<Rational>, p) => { const rate = p.rate.div(DisplayRateVal[displayRate]); if (p.viaId === p.itemId) { e[p.id] = rate; } else { const via = RecipeUtility.getProductStepData(productSteps, p); if (via) { e[p.id] = rate.div(via[1]); } else { e[p.id] = Rational.zero; } } return e; }, {}) ); export const getNormalizedRatesByBelts = createSelector( getProductsByBelts, getProductSteps, Items.getItemSettings, Settings.getBeltSpeed, (products, productSteps, itemSettings, beltSpeed) => products?.reduce((e: Entities<Rational>, p) => { if (p.viaId === p.itemId) { e[p.id] = p.rate.mul( beltSpeed[p.viaSetting || itemSettings[p.itemId].belt] ); } else { const via = RecipeUtility.getProductStepData(productSteps, p); if (via) { e[p.id] = p.rate .mul(beltSpeed[p.viaSetting || itemSettings[via[0]].belt]) .div(via[1]); } else { e[p.id] = Rational.zero; } } return e; }, {}) ); export const getNormalizedRatesByWagons = createSelector( getProductsByWagons, getProductSteps, Items.getItemSettings, Settings.getDisplayRate, Settings.getDataset, (products, productSteps, itemSettings, displayRate, data) => products?.reduce((e: Entities<Rational>, p) => { if (p.viaId === p.itemId) { const item = data.itemR[p.itemId]; const wagon = data.itemR[p.viaSetting || itemSettings[p.itemId].wagon]; e[p.id] = p.rate .div(DisplayRateVal[displayRate]) .mul( item.stack ? item.stack.mul(wagon.cargoWagon.size) : wagon.fluidWagon.capacity ); } else { const via = RecipeUtility.getProductStepData(productSteps, p); if (via) { const item = data.itemR[via[0]]; const wagon = data.itemR[p.viaSetting || itemSettings[via[0]].wagon]; e[p.id] = p.rate .div(DisplayRateVal[displayRate]) .mul( item.stack ? item.stack.mul(wagon.cargoWagon.size) : wagon.fluidWagon.capacity ) .div(via[1]); } else { e[p.id] = Rational.zero; } } return e; }, {}) ); export const getNormalizedRatesByFactories = createSelector( getProductsByFactories, getProductSteps, Recipes.getRationalRecipeSettings, Settings.getAdjustmentData, Recipes.getAdjustedDataset, (products, productSteps, recipeSettings, adj, data) => products?.reduce((e: Entities<Rational>, p) => { let recipeId = data.itemRecipeIds[p.itemId]; if (recipeId && p.viaId === recipeId) { const recipe = data.recipeR[recipeId]; e[p.id] = p.rate.div(recipe.time).mul(recipe.out[p.itemId]); if (recipe.adjustProd) { e[p.id] = e[p.id].div(recipe.productivity); } } else { const via = RecipeUtility.getProductStepData(productSteps, p); if (via) { recipeId = via[0]; e[p.id] = p.rate.div(via[1]); } else { e[p.id] = Rational.zero; } } // Adjust based on product recipe settings if (recipeId && p.viaSetting) { const customSettings = { ...recipeSettings, ...{ [recipeId]: { ...{ factory: p.viaSetting, factoryModules: p.viaFactoryModules, beaconCount: p.viaBeaconCount, beacon: p.viaBeacon, beaconModules: p.viaBeaconModules, overclock: p.viaOverclock, }, }, }, }; const recipeR = RecipeUtility.adjustRecipes( customSettings, adj.fuel, adj.miningBonus, adj.researchSpeed, adj.data ); const oldRecipe = data.recipeR[recipeId]; const newRecipe = recipeR[recipeId]; const ratio = newRecipe.productivity .div(newRecipe.time) .div(oldRecipe.productivity) .mul(oldRecipe.time); e[p.id] = e[p.id].mul(ratio); } return e; }, {}) ); export const getNormalizedRates = createSelector( getNormalizedRatesByItems, getNormalizedRatesByBelts, getNormalizedRatesByWagons, getNormalizedRatesByFactories, (byItems, byBelts, byWagons, byFactories) => ({ ...byItems, ...byBelts, ...byWagons, ...byFactories, }) ); export const getNormalizedSteps = createSelector( getProducts, getNormalizedRates, Items.getItemSettings, Recipes.getAdjustedDataset, (products, rates, itemSettings, data) => { const steps: Step[] = []; for (const product of products) { RateUtility.addStepsFor( product.itemId, rates[product.id], steps, itemSettings, data ); } return steps; } ); export const getMatrixResult = createSelector( getNormalizedSteps, Items.getItemSettings, Settings.getDisabledRecipes, Recipes.getAdjustedDataset, Preferences.getSimplexModifiers, (steps, itemSettings, disabledRecipes, data, adj) => adj.simplex ? SimplexUtility.solve( RateUtility.copy(steps), itemSettings, disabledRecipes, adj.costInput, adj.costIgnored, data ) : { steps, result: MatrixResultType.Skipped } ); export const getNormalizedStepsWithBelts = createSelector( getMatrixResult, Items.getItemSettings, Recipes.getRecipeSettings, Settings.getBeltSpeed, Recipes.getAdjustedDataset, (result, itemSettings, recipeSettings, beltSpeed, data) => RateUtility.calculateBelts( RateUtility.copy(result.steps), itemSettings, recipeSettings, beltSpeed, data ) ); export const getNormalizedStepsWithOutputs = createSelector( getNormalizedStepsWithBelts, Recipes.getAdjustedDataset, (steps, data) => RateUtility.calculateOutputs(RateUtility.copy(steps), data) ); export const getNormalizedStepsWithBeacons = createSelector( getNormalizedStepsWithOutputs, Settings.getRationalBeaconReceivers, Recipes.getRationalRecipeSettings, Recipes.getAdjustedDataset, (steps, beaconReceivers, recipeSettings, data) => RateUtility.calculateBeacons( RateUtility.copy(steps), beaconReceivers, recipeSettings, data ) ); export const getSteps = createSelector( getNormalizedStepsWithBeacons, Settings.getDisplayRate, (steps, displayRate) => RateUtility.sortHierarchy( RateUtility.displayRate(RateUtility.copy(steps), displayRate) ) ); export const getSankey = createSelector( getSteps, Preferences.getLinkSize, Preferences.getLinkText, Preferences.getLinkPrecision, Recipes.getAdjustedDataset, (steps, linkSize, linkText, linkPrecision, data) => FlowUtility.buildSankey( RateUtility.copy(steps), linkSize, linkText, linkPrecision, data ) ); export const checkViaState = createSelector( getRationalProducts, getNormalizedRates, (products, rates) => ({ products, rates }) ); export const getZipState = createSelector( productsState, Items.itemsState, Recipes.recipesState, Factories.factoriesState, Settings.settingsState, (products, items, recipes, factories, settings) => ({ products, items, recipes, factories, settings, }) );
the_stack
import { Currency, CurrencyAmount, IssuedCurrencyAmount, XRPDropsAmount, } from '../../../src/XRP/Generated/web/org/xrpl/rpc/v1/amount_pb' import { Amount, Date, Destination, Account, SigningPublicKey, TransactionSignature, Sequence, DestinationTag, DeliverMin, InvoiceID, SendMax, MemoData, MemoFormat, MemoType, AccountTransactionID, Flags, LastLedgerSequence, SourceTag, DeliveredAmount, SignerEntry, SignerWeight, } from '../../../src/XRP/Generated/web/org/xrpl/rpc/v1/common_pb' import { Payment, Transaction, CheckCash, Memo, Signer, } from '../../../src/XRP/Generated/web/org/xrpl/rpc/v1/transaction_pb' import { AccountAddress } from '../../../src/XRP/Generated/web/org/xrpl/rpc/v1/account_pb' import { GetAccountTransactionHistoryResponse } from '../../../src/XRP/Generated/web/org/xrpl/rpc/v1/get_account_transaction_history_pb' import XrpTransaction from '../../../src/XRP/protobuf-wrappers/xrp-transaction' import { GetTransactionResponse } from '../../../src/XRP/Generated/web/org/xrpl/rpc/v1/get_transaction_pb' import { Meta } from '../../../src/XRP/Generated/web/org/xrpl/rpc/v1/meta_pb' import { XrplNetwork } from 'xpring-common-js' // primitive test values const testCurrencyName = 'currencyName' const testCurrencyCode = new Uint8Array([1, 2, 3]) const testAddress = 'rsKouRxYLWGseFwXSAo57qXjcGiNqR55wr' const testAddress2 = 'rPuNV4oA6f3SrKA4pLEpdVZW6QLvn3UJxK' const testInvalidAddress = 'badAddress' const testIssuedCurrencyValue = '100' const testInvalidIssuedCurrencyValue = 'xrp' // non-numeric const testPublicKey = new Uint8Array([1, 2, 3]) const testTransactionSignature = new Uint8Array([4, 5, 6]) const testSequence = 1 const testFee = '3' const testInvalidFee = '1x' const testDrops = '20' const testDestinationTag = 2 const testInvoiceID = new Uint8Array([7, 8, 9]) const testMemoData = new Uint8Array([2, 4, 6]) const testMemoFormat = new Uint8Array([3, 6, 9]) const testMemoType = new Uint8Array([3, 2, 1]) const testAccountTransactionID = new Uint8Array([5, 6, 7]) const testFlags = 4 const testSourceTag = 6 const testLastLedgerSequence = 5 const testTransactionHash = new Uint8Array([3, 5, 7, 9]) // Set date to Ripple epoch, January 1, 2000 (00:00 UTC). // Expected timestamp is in unix time, 946684800 after Unix epoch. const testTimestamp = 0 const expectedTimestamp = 946684800 const testIsValidated = true const testLedgerIndex = 1000 const testSignerWeight = 1 // VALID OBJECTS =============================================== // Currency proto const testCurrencyProto: Currency = new Currency() testCurrencyProto.setCode(testCurrencyCode) testCurrencyProto.setName(testCurrencyName) // AccountAddress protos const accountAddressProto = new AccountAddress() accountAddressProto.setAddress(testAddress) const testAccountAddressIssuer = new AccountAddress() testAccountAddressIssuer.setAddress(testAddress2) // PathElement protos const testPathElementProtoWithAccount = new Payment.PathElement() testPathElementProtoWithAccount.setAccount(accountAddressProto) const testPathElementProtoWithCurrencyIssuer = new Payment.PathElement() testPathElementProtoWithCurrencyIssuer.setCurrency(testCurrencyProto) testPathElementProtoWithCurrencyIssuer.setIssuer(testAccountAddressIssuer) // Path protos const testEmptyPathProto = new Payment.Path() const testPathProtoOneElement = new Payment.Path() testPathProtoOneElement.addElements(testPathElementProtoWithAccount) const testPathProtoThreeElements = new Payment.Path() testPathProtoThreeElements.setElementsList([ testPathElementProtoWithAccount, testPathElementProtoWithCurrencyIssuer, testPathElementProtoWithAccount, ]) // ... for Payment protos const accountAddressProto456 = new AccountAddress() accountAddressProto456.setAddress('r456') const accountAddressProto789 = new AccountAddress() accountAddressProto789.setAddress('r789') const accountAddressProtoABC = new AccountAddress() accountAddressProtoABC.setAddress('rabc') const pathElementProto456 = new Payment.PathElement() pathElementProto456.setAccount(accountAddressProto456) const pathElementProto789 = new Payment.PathElement() pathElementProto789.setAccount(accountAddressProto789) const pathElementProtoABC = new Payment.PathElement() pathElementProtoABC.setAccount(accountAddressProtoABC) const pathProtoOneElement = new Payment.Path() pathProtoOneElement.setElementsList([pathElementProto456]) const pathProtoTwoElements = new Payment.Path() pathProtoTwoElements.setElementsList([pathElementProto789, pathElementProtoABC]) const paths = [pathProtoOneElement, pathProtoTwoElements] // IssuedCurrencyAmount proto const testIssuedCurrencyProto = new IssuedCurrencyAmount() testIssuedCurrencyProto.setCurrency(testCurrencyProto) testIssuedCurrencyProto.setIssuer(accountAddressProto) testIssuedCurrencyProto.setValue(testIssuedCurrencyValue) // Account proto const transactionAccountProto = new Account() transactionAccountProto.setValue(accountAddressProto) // XRPDropsAmount protos const xrpDropsProto = new XRPDropsAmount() xrpDropsProto.setDrops(testDrops) const transactionFeeProto = new XRPDropsAmount() transactionFeeProto.setDrops(testFee) const invalidTransactionFeeProto = new XRPDropsAmount() invalidTransactionFeeProto.setDrops(testInvalidFee) // Sequence proto const transactionSequenceProto = new Sequence() transactionSequenceProto.setValue(testSequence) // CurrencyAmount protos const testCurrencyAmountProtoDrops = new CurrencyAmount() testCurrencyAmountProtoDrops.setXrpAmount(xrpDropsProto) const testCurrencyAmountProtoIssuedCurrency = new CurrencyAmount() testCurrencyAmountProtoIssuedCurrency.setIssuedCurrencyAmount( testIssuedCurrencyProto, ) // Amount proto const paymentAmountProtoIssuedCurrency = new Amount() paymentAmountProtoIssuedCurrency.setValue(testCurrencyAmountProtoIssuedCurrency) const paymentAmountProtoXRP = new Amount() paymentAmountProtoXRP.setValue(testCurrencyAmountProtoDrops) // AccountAddress proto const destinationAccountAddressProto = new AccountAddress() destinationAccountAddressProto.setAddress(testAddress2) const invalidAccountAddressProto = new AccountAddress() invalidAccountAddressProto.setAddress(testInvalidAddress) // Destination proto const paymentDestinationProto = new Destination() paymentDestinationProto.setValue(destinationAccountAddressProto) const invalidPaymentDestinationProto = new Destination() invalidPaymentDestinationProto.setValue(invalidAccountAddressProto) // DestinationTag proto const destinationTagProto = new DestinationTag() destinationTagProto.setValue(testDestinationTag) // DeliverMin proto const deliverMinProto = new DeliverMin() deliverMinProto.setValue(testCurrencyAmountProtoDrops) // InvoidID proto const invoiceIDProto = new InvoiceID() invoiceIDProto.setValue(testInvoiceID) // SendMax proto const sendMaxProto = new SendMax() sendMaxProto.setValue(testCurrencyAmountProtoDrops) // Payment protos const testPaymentProtoAllFieldsSet = new Payment() testPaymentProtoAllFieldsSet.setAmount(paymentAmountProtoIssuedCurrency) testPaymentProtoAllFieldsSet.setDestination(paymentDestinationProto) testPaymentProtoAllFieldsSet.setDestinationTag(destinationTagProto) testPaymentProtoAllFieldsSet.setDeliverMin(deliverMinProto) testPaymentProtoAllFieldsSet.setInvoiceId(invoiceIDProto) testPaymentProtoAllFieldsSet.setPathsList(paths) testPaymentProtoAllFieldsSet.setSendMax(sendMaxProto) const testPaymentProtoMandatoryFieldsOnly = new Payment() testPaymentProtoMandatoryFieldsOnly.setAmount(paymentAmountProtoIssuedCurrency) testPaymentProtoMandatoryFieldsOnly.setDestination(paymentDestinationProto) testPaymentProtoMandatoryFieldsOnly.setSendMax(sendMaxProto) // Memo protos const memoDataProto = new MemoData() memoDataProto.setValue(testMemoData) const memoFormatProto = new MemoFormat() memoFormatProto.setValue(testMemoFormat) const memoTypeProto = new MemoType() memoTypeProto.setValue(testMemoType) const testMemoProtoAllFields = new Memo() testMemoProtoAllFields.setMemoData(memoDataProto) testMemoProtoAllFields.setMemoFormat(memoFormatProto) testMemoProtoAllFields.setMemoType(memoTypeProto) const testEmptyMemoProto = new Memo() // Account proto const accountProto = new Account() accountProto.setValue(accountAddressProto) // SigningPublicKey proto const signingPublicKeyProto = new SigningPublicKey() signingPublicKeyProto.setValue(testPublicKey) const signingPublicKeyProtoEmpty = new SigningPublicKey() signingPublicKeyProtoEmpty.setValue('') // TransactionSignature proto const transactionSignatureProto = new TransactionSignature() transactionSignatureProto.setValue(testTransactionSignature) // Signer proto const testSignerProto = new Signer() testSignerProto.setAccount(accountProto) testSignerProto.setSigningPublicKey(signingPublicKeyProto) testSignerProto.setTransactionSignature(transactionSignatureProto) // AccountTransactionID proto const accountTransactionIDProto = new AccountTransactionID() accountTransactionIDProto.setValue(testAccountTransactionID) // Flags proto const flagsProto = new Flags() flagsProto.setValue(testFlags) // LastLedgerSequence proto const lastLedgerSequenceProto = new LastLedgerSequence() lastLedgerSequenceProto.setValue(testLastLedgerSequence) // SourceTag proto const sourceTagProto = new SourceTag() sourceTagProto.setValue(testSourceTag) // Transaction protos // (PAYMENT) (all fields set) const testTransactionPaymentAllFields = new Transaction() testTransactionPaymentAllFields.setAccount(accountProto) testTransactionPaymentAllFields.setFee(transactionFeeProto) testTransactionPaymentAllFields.setSequence(transactionSequenceProto) testTransactionPaymentAllFields.setSigningPublicKey(signingPublicKeyProto) testTransactionPaymentAllFields.setTransactionSignature( transactionSignatureProto, ) testTransactionPaymentAllFields.setAccountTransactionId( accountTransactionIDProto, ) testTransactionPaymentAllFields.setFlags(flagsProto) testTransactionPaymentAllFields.setLastLedgerSequence(lastLedgerSequenceProto) testTransactionPaymentAllFields.setMemosList([testMemoProtoAllFields]) testTransactionPaymentAllFields.setSignersList([testSignerProto]) testTransactionPaymentAllFields.setSourceTag(sourceTagProto) testTransactionPaymentAllFields.setPayment(testPaymentProtoMandatoryFieldsOnly) // (PAYMENT) (only mandatory common fields set) const testTransactionPaymentMandatoryFields = new Transaction() testTransactionPaymentMandatoryFields.setAccount(transactionAccountProto) testTransactionPaymentMandatoryFields.setFee(transactionFeeProto) testTransactionPaymentMandatoryFields.setSequence(transactionSequenceProto) testTransactionPaymentMandatoryFields.setSigningPublicKey(signingPublicKeyProto) testTransactionPaymentMandatoryFields.setTransactionSignature( transactionSignatureProto, ) testTransactionPaymentMandatoryFields.setPayment( testPaymentProtoMandatoryFieldsOnly, ) // (PAYMENT) (mandatory fields, with signers instead of public key) const testTransactionPaymentSigners = new Transaction() testTransactionPaymentSigners.setAccount(transactionAccountProto) testTransactionPaymentSigners.setFee(transactionFeeProto) testTransactionPaymentSigners.setSequence(transactionSequenceProto) testTransactionPaymentSigners.setSigningPublicKey(signingPublicKeyProtoEmpty) testTransactionPaymentSigners.setSignersList([testSignerProto]) testTransactionPaymentSigners.setTransactionSignature(transactionSignatureProto) testTransactionPaymentSigners.setPayment(testPaymentProtoMandatoryFieldsOnly) // (CHECKCASH) (only mandatory common fields set, currently unsupported) const checkCashProto = new CheckCash() const testCheckCashTransaction = new Transaction() testCheckCashTransaction.setAccount(transactionAccountProto) testCheckCashTransaction.setFee(transactionFeeProto) testCheckCashTransaction.setSequence(transactionSequenceProto) testCheckCashTransaction.setSigningPublicKey(signingPublicKeyProto) testCheckCashTransaction.setTransactionSignature(transactionSignatureProto) testCheckCashTransaction.setCheckCash(checkCashProto) // Date proto const dateProto = new Date() dateProto.setValue(testTimestamp) // DeliveredAmount proto const deliveredAmountProto = new DeliveredAmount() deliveredAmountProto.setValue(testCurrencyAmountProtoIssuedCurrency) // Meta proto const metaProto = new Meta() metaProto.setDeliveredAmount(deliveredAmountProto) // GetTransactionResponse protos const testGetTransactionResponseProto = new GetTransactionResponse() testGetTransactionResponseProto.setTransaction(testTransactionPaymentAllFields) testGetTransactionResponseProto.setDate(dateProto) testGetTransactionResponseProto.setHash(testTransactionHash) testGetTransactionResponseProto.setMeta(metaProto) testGetTransactionResponseProto.setValidated(testIsValidated) testGetTransactionResponseProto.setLedgerIndex(testLedgerIndex) const testGetTransactionResponseProtoMandatoryOnly = new GetTransactionResponse() testGetTransactionResponseProtoMandatoryOnly.setTransaction( testTransactionPaymentMandatoryFields, ) testGetTransactionResponseProtoMandatoryOnly.setHash(testTransactionHash) const testGetTransactionResponseProtoSigners = new GetTransactionResponse() testGetTransactionResponseProtoSigners.setTransaction( testTransactionPaymentSigners, ) testGetTransactionResponseProtoSigners.setHash(testTransactionHash) // GetAccountTransactionHistoryResponse proto const testGetAccountTransactionHistoryResponse = new GetAccountTransactionHistoryResponse() const transactionResponseList = [ testGetTransactionResponseProto, testGetTransactionResponseProto, ] testGetAccountTransactionHistoryResponse.setTransactionsList( transactionResponseList, ) // SignerEntry protos const testAccountAddressProto = new AccountAddress() testAccountAddressProto.setAddress(testAddress) const testSignerEntryAccountProto = new Account() testSignerEntryAccountProto.setValue(testAccountAddressProto) const testSignerWeightProto = new SignerWeight() testSignerWeightProto.setValue(testSignerWeight) const testSignerEntryProto = new SignerEntry() testSignerEntryProto.setAccount(testSignerEntryAccountProto) testSignerEntryProto.setSignerWeight(testSignerWeightProto) // INVALID OBJECTS ============================================= // Invalid PathElement protos const testInvalidPathElementWithAccountCurrency = new Payment.PathElement() testInvalidPathElementWithAccountCurrency.setCurrency(testCurrencyProto) testInvalidPathElementWithAccountCurrency.setAccount(accountAddressProto) const testInvalidPathElementWithAccountIssuer = new Payment.PathElement() testInvalidPathElementWithAccountIssuer.setIssuer(testAccountAddressIssuer) testInvalidPathElementWithAccountIssuer.setAccount(accountAddressProto) const testInvalidPathElementProtoEmpty = new Payment.PathElement() // Invalid Currency proto const testInvalidCurrencyProtoNoName = new Currency() testInvalidCurrencyProtoNoName.setCode(testCurrencyCode) const testInvalidCurrencyProtoNoCode = new Currency() testInvalidCurrencyProtoNoCode.setName(testCurrencyName) // Invalid IssuedCurrencyAmount protos const testInvalidIssuedCurrencyProtoBadValue = new IssuedCurrencyAmount() testInvalidIssuedCurrencyProtoBadValue.setCurrency(testCurrencyProto) testInvalidIssuedCurrencyProtoBadValue.setIssuer(accountAddressProto) testInvalidIssuedCurrencyProtoBadValue.setValue(testInvalidIssuedCurrencyValue) const testInvalidIssuedCurrencyProtoBadCurrency = new IssuedCurrencyAmount() testInvalidIssuedCurrencyProtoBadCurrency.setIssuer(accountAddressProto) testInvalidIssuedCurrencyProtoBadCurrency.setValue(testIssuedCurrencyValue) const testInvalidIssuedCurrencyProtoBadIssuer = new IssuedCurrencyAmount() testInvalidIssuedCurrencyProtoBadIssuer.setValue(testIssuedCurrencyValue) testInvalidIssuedCurrencyProtoBadIssuer.setCurrency(testCurrencyProto) // Invalid CurrencyAmount proto const testInvalidCurrencyAmountProto = new CurrencyAmount() testInvalidCurrencyAmountProto.setIssuedCurrencyAmount( testInvalidIssuedCurrencyProtoBadValue, ) const testInvalidCurrencyAmountProtoEmpty = new CurrencyAmount() const testInvalidCurrencyAmountProtoBadDrops = new CurrencyAmount() testInvalidCurrencyAmountProtoBadDrops.setXrpAmount(undefined) // Invalid Amount proto const invalidAmountProto = new Amount() invalidAmountProto.setValue(testInvalidCurrencyAmountProto) // Invalid DeliverMin proto const invalidDeliverMinProto = new DeliverMin() invalidDeliverMinProto.setValue(testInvalidCurrencyAmountProto) // Invalid SendMax proto const invalidSendMaxProto = new SendMax() invalidSendMaxProto.setValue(testInvalidCurrencyAmountProto) // Invalid Payment protos const testInvalidPaymentProtoNoAmount = new Payment() testInvalidPaymentProtoNoAmount.setDestination(paymentDestinationProto) const testInvalidPaymentProtoNoDestination = new Payment() testInvalidPaymentProtoNoDestination.setAmount(paymentAmountProtoIssuedCurrency) const testInvalidPaymentProtoBadDestination = new Payment() testInvalidPaymentProtoBadDestination.setAmount( paymentAmountProtoIssuedCurrency, ) testInvalidPaymentProtoBadDestination.setDestination( invalidPaymentDestinationProto, ) const testInvalidPaymentProtoXrpPaths = new Payment() testInvalidPaymentProtoXrpPaths.setAmount(paymentAmountProtoXRP) testInvalidPaymentProtoXrpPaths.setDestination(paymentDestinationProto) testInvalidPaymentProtoXrpPaths.setPathsList(paths) const testInvalidPaymentProtoXrpSendMax = new Payment() testInvalidPaymentProtoXrpSendMax.setAmount(paymentAmountProtoXRP) testInvalidPaymentProtoXrpSendMax.setDestination(paymentDestinationProto) testInvalidPaymentProtoXrpSendMax.setSendMax(sendMaxProto) const testInvalidPaymentProtoNoSendMax = new Payment() testInvalidPaymentProtoNoSendMax.setAmount(paymentAmountProtoIssuedCurrency) testInvalidPaymentProtoNoSendMax.setDestination(paymentDestinationProto) // Invalid Signer protos const invalidAccountProto = new Account() invalidAccountProto.setValue(invalidAccountAddressProto) const testInvalidSignerProtoNoAccount = new Signer() testInvalidSignerProtoNoAccount.setSigningPublicKey(signingPublicKeyProto) testInvalidSignerProtoNoAccount.setTransactionSignature( transactionSignatureProto, ) const testInvalidSignerProtoBadAccount = new Signer() testInvalidSignerProtoBadAccount.setAccount(invalidAccountProto) testInvalidSignerProtoBadAccount.setSigningPublicKey(signingPublicKeyProto) testInvalidSignerProtoBadAccount.setTransactionSignature( transactionSignatureProto, ) const testInvalidSignerProtoNoPublicKey = new Signer() testInvalidSignerProtoNoPublicKey.setAccount(accountProto) testInvalidSignerProtoNoPublicKey.setTransactionSignature( transactionSignatureProto, ) const testInvalidSignerProtoNoTxnSignature = new Signer() testInvalidSignerProtoNoTxnSignature.setAccount(accountProto) testInvalidSignerProtoNoTxnSignature.setSigningPublicKey(signingPublicKeyProto) // Invalid Transaction proto (PAYMENT, malformed) (only mandatory common fields set) const testInvalidPaymentTransaction = new Transaction() testInvalidPaymentTransaction.setAccount(transactionAccountProto) testInvalidPaymentTransaction.setFee(transactionFeeProto) testInvalidPaymentTransaction.setSequence(transactionSequenceProto) testInvalidPaymentTransaction.setSigningPublicKey(signingPublicKeyProto) testInvalidPaymentTransaction.setTransactionSignature(transactionSignatureProto) testInvalidPaymentTransaction.setPayment(testInvalidPaymentProtoNoAmount) // ... no account const testInvalidPaymentTransactionNoAccount = new Transaction() testInvalidPaymentTransactionNoAccount.setFee(transactionFeeProto) testInvalidPaymentTransactionNoAccount.setSequence(transactionSequenceProto) testInvalidPaymentTransactionNoAccount.setSigningPublicKey( signingPublicKeyProto, ) testInvalidPaymentTransactionNoAccount.setTransactionSignature( transactionSignatureProto, ) testInvalidPaymentTransactionNoAccount.setPayment( testPaymentProtoMandatoryFieldsOnly, ) // ... bad account const testInvalidPaymentTransactionBadAccount = new Transaction() testInvalidPaymentTransactionBadAccount.setAccount(invalidAccountProto) testInvalidPaymentTransactionBadAccount.setFee(transactionFeeProto) testInvalidPaymentTransactionBadAccount.setSequence(transactionSequenceProto) testInvalidPaymentTransactionBadAccount.setSigningPublicKey( signingPublicKeyProto, ) testInvalidPaymentTransactionBadAccount.setTransactionSignature( transactionSignatureProto, ) testInvalidPaymentTransactionBadAccount.setPayment( testPaymentProtoMandatoryFieldsOnly, ) // ... no fee const testInvalidPaymentTransactionNoFee = new Transaction() testInvalidPaymentTransactionNoFee.setAccount(transactionAccountProto) testInvalidPaymentTransactionNoFee.setSequence(transactionSequenceProto) testInvalidPaymentTransactionNoFee.setSigningPublicKey(signingPublicKeyProto) testInvalidPaymentTransactionNoFee.setTransactionSignature( transactionSignatureProto, ) testInvalidPaymentTransactionNoFee.setPayment( testPaymentProtoMandatoryFieldsOnly, ) // ... non-int fee const testInvalidTransactionPaymentBadFee = new Transaction() testInvalidTransactionPaymentBadFee.setAccount(transactionAccountProto) testInvalidTransactionPaymentBadFee.setFee(invalidTransactionFeeProto) testInvalidTransactionPaymentBadFee.setSequence(transactionSequenceProto) testInvalidTransactionPaymentBadFee.setSigningPublicKey(signingPublicKeyProto) testInvalidTransactionPaymentBadFee.setTransactionSignature( transactionSignatureProto, ) testInvalidTransactionPaymentBadFee.setPayment( testPaymentProtoMandatoryFieldsOnly, ) // ... no sequence const testInvalidTransactionPaymentNoSequence = new Transaction() testInvalidTransactionPaymentNoSequence.setAccount(transactionAccountProto) testInvalidTransactionPaymentNoSequence.setFee(transactionFeeProto) testInvalidTransactionPaymentNoSequence.setSigningPublicKey( signingPublicKeyProto, ) testInvalidTransactionPaymentNoSequence.setTransactionSignature( transactionSignatureProto, ) testInvalidTransactionPaymentNoSequence.setPayment( testPaymentProtoMandatoryFieldsOnly, ) // ... no signingPublicKey const testInvalidTransactionPaymentNoSigningPublicKey = new Transaction() testInvalidTransactionPaymentNoSigningPublicKey.setAccount( transactionAccountProto, ) testInvalidTransactionPaymentNoSigningPublicKey.setFee(transactionFeeProto) testInvalidTransactionPaymentNoSigningPublicKey.setSequence( transactionSequenceProto, ) testInvalidTransactionPaymentNoSigningPublicKey.setTransactionSignature( transactionSignatureProto, ) testInvalidTransactionPaymentNoSigningPublicKey.setPayment( testPaymentProtoMandatoryFieldsOnly, ) // ... no signers const testInvalidTransactionPaymentNoSigners = new Transaction() testInvalidTransactionPaymentNoSigners.setAccount(transactionAccountProto) testInvalidTransactionPaymentNoSigners.setFee(transactionFeeProto) testInvalidTransactionPaymentNoSigners.setSequence(transactionSequenceProto) testInvalidTransactionPaymentNoSigners.setSigningPublicKey( signingPublicKeyProtoEmpty, ) testInvalidTransactionPaymentNoSigners.setTransactionSignature( transactionSignatureProto, ) testInvalidTransactionPaymentNoSigners.setPayment( testPaymentProtoMandatoryFieldsOnly, ) // ... no transactionSignature const testInvalidTransactionPaymentNoSignature = new Transaction() testInvalidTransactionPaymentNoSignature.setAccount(transactionAccountProto) testInvalidTransactionPaymentNoSignature.setFee(transactionFeeProto) testInvalidTransactionPaymentNoSignature.setSequence(transactionSequenceProto) testInvalidTransactionPaymentNoSignature.setSigningPublicKey( signingPublicKeyProto, ) testInvalidTransactionPaymentNoSignature.setPayment( testPaymentProtoMandatoryFieldsOnly, ) // ... no data const testInvalidTransactionPaymentNoData = new Transaction() testInvalidTransactionPaymentNoData.setAccount(transactionAccountProto) testInvalidTransactionPaymentNoData.setFee(transactionFeeProto) testInvalidTransactionPaymentNoData.setSequence(transactionSequenceProto) testInvalidTransactionPaymentNoData.setSigningPublicKey(signingPublicKeyProto) testInvalidTransactionPaymentNoData.setTransactionSignature( transactionSignatureProto, ) // Invalid GetTransactionResponse protos const testInvalidGetTransactionResponseProto = new GetTransactionResponse() testInvalidGetTransactionResponseProto.setTransaction( testInvalidPaymentTransaction, ) testInvalidGetTransactionResponseProto.setHash(testTransactionHash) // ... unsupported transaction type const testInvalidGetTransactionResponseProtoUnsupportedType = new GetTransactionResponse() testInvalidGetTransactionResponseProtoUnsupportedType.setTransaction( testCheckCashTransaction, ) testInvalidGetTransactionResponseProtoUnsupportedType.setHash( testTransactionHash, ) // ... no transaction const testInvalidGetTransactionResponseProtoNoTransaction = new GetTransactionResponse() testInvalidGetTransactionResponseProtoNoTransaction.setHash(testTransactionHash) // ... no account const testInvalidGetTransactionResponseProtoNoAccount = new GetTransactionResponse() testInvalidGetTransactionResponseProtoNoAccount.setTransaction( testInvalidPaymentTransactionNoAccount, ) testInvalidGetTransactionResponseProtoNoAccount.setHash(testTransactionHash) // ... bad account const testInvalidGetTransactionResponseProtoBadAccount = new GetTransactionResponse() testInvalidGetTransactionResponseProtoBadAccount.setTransaction( testInvalidPaymentTransactionBadAccount, ) testInvalidGetTransactionResponseProtoBadAccount.setHash(testTransactionHash) // ... no fee const testInvalidGetTransactionResponseProtoNoFee = new GetTransactionResponse() testInvalidGetTransactionResponseProtoNoFee.setTransaction( testInvalidPaymentTransactionNoFee, ) testInvalidGetTransactionResponseProtoNoFee.setHash(testTransactionHash) // ... non-int fee const testInvalidGetTransactionResponseProtoBadFee = new GetTransactionResponse() testInvalidGetTransactionResponseProtoBadFee.setTransaction( testInvalidTransactionPaymentBadFee, ) testInvalidGetTransactionResponseProtoBadFee.setHash(testTransactionHash) // ... no sequence const testInvalidGetTransactionResponseProtoNoSequence = new GetTransactionResponse() testInvalidGetTransactionResponseProtoNoSequence.setTransaction( testInvalidTransactionPaymentNoSequence, ) testInvalidGetTransactionResponseProtoNoSequence.setHash(testTransactionHash) // ... no signingPublicKey const testInvalidGetTransactionResponseProtoNoSigningPublicKey = new GetTransactionResponse() testInvalidGetTransactionResponseProtoNoSigningPublicKey.setTransaction( testInvalidTransactionPaymentNoSigningPublicKey, ) testInvalidGetTransactionResponseProtoNoSigningPublicKey.setHash( testTransactionHash, ) // ... no signers const testInvalidGetTransactionResponseProtoNoSigners = new GetTransactionResponse() testInvalidGetTransactionResponseProtoNoSigners.setTransaction( testInvalidTransactionPaymentNoSigners, ) testInvalidGetTransactionResponseProtoNoSigners.setHash(testTransactionHash) // ... no transactionSignature const testInvalidGetTransactionResponseProtoNoSignature = new GetTransactionResponse() testInvalidGetTransactionResponseProtoNoSignature.setTransaction( testInvalidTransactionPaymentNoSignature, ) testInvalidGetTransactionResponseProtoNoSignature.setHash(testTransactionHash) // ... no data const testInvalidGetTransactionResponseProtoNoData = new GetTransactionResponse() testInvalidGetTransactionResponseProtoNoData.setTransaction( testInvalidTransactionPaymentNoData, ) testInvalidGetTransactionResponseProtoNoData.setHash(testTransactionHash) // ... no hash const testInvalidGetTransactionResponseProtoNoHash = new GetTransactionResponse() testInvalidGetTransactionResponseProtoNoHash.setTransaction( testTransactionPaymentMandatoryFields, ) // Invalid GetAccountTransactionHistoryResponse proto const testInvalidGetAccountTransactionHistoryResponse = new GetAccountTransactionHistoryResponse() const invalidTransactionResponseList = [ testInvalidGetTransactionResponseProto, // one bad transaction (malformed Payment) testGetTransactionResponseProto, ] testInvalidGetAccountTransactionHistoryResponse.setTransactionsList( invalidTransactionResponseList, ) // Invalid SignerEntry protos const testInvalidSignerEntryAccountProto = new Account() testInvalidSignerEntryAccountProto.setValue(invalidAccountAddressProto) const testInvalidSignerEntryProtoNoAccount = new SignerEntry() testInvalidSignerEntryProtoNoAccount.setSignerWeight(testSignerWeightProto) const testInvalidSignerEntryProtoBadAccount = new SignerEntry() testInvalidSignerEntryProtoBadAccount.setAccount( testInvalidSignerEntryAccountProto, ) testInvalidSignerEntryProtoBadAccount.setSignerWeight(testSignerWeightProto) const testInvalidSignerEntryProtoNoSignerWeight = new SignerEntry() testInvalidSignerEntryProtoNoSignerWeight.setAccount( testSignerEntryAccountProto, ) // XRP OBJECTS =================================================== // test XrpTransaction const testXrpTransaction = XrpTransaction.from( testGetTransactionResponseProto, XrplNetwork.Test, )! export { testCurrencyName, testCurrencyCode, testAddress, testAddress2, testIssuedCurrencyValue, testInvalidIssuedCurrencyValue, testPublicKey, testTransactionSignature, testSequence, testFee, testDrops, testDestinationTag, testInvoiceID, testMemoData, testMemoFormat, testMemoType, testAccountTransactionID, testFlags, testSourceTag, testLastLedgerSequence, testTransactionHash, testTimestamp, expectedTimestamp, testIsValidated, testLedgerIndex, testCurrencyProto, testAccountAddressIssuer, testPathElementProtoWithAccount, testPathElementProtoWithCurrencyIssuer, testEmptyPathProto, testPathProtoOneElement, testPathProtoThreeElements, testIssuedCurrencyProto, testCurrencyAmountProtoDrops, testCurrencyAmountProtoIssuedCurrency, testPaymentProtoAllFieldsSet, testPaymentProtoMandatoryFieldsOnly, testMemoProtoAllFields, testEmptyMemoProto, testSignerProto, testSignerEntryProto, testTransactionPaymentAllFields, testTransactionPaymentMandatoryFields, testGetTransactionResponseProto, testCheckCashTransaction, testXrpTransaction, testGetAccountTransactionHistoryResponse, testGetTransactionResponseProtoMandatoryOnly, testGetTransactionResponseProtoSigners, testInvalidCurrencyProtoNoName, testInvalidCurrencyProtoNoCode, testInvalidIssuedCurrencyProtoBadValue, testInvalidIssuedCurrencyProtoBadCurrency, testInvalidIssuedCurrencyProtoBadIssuer, testInvalidCurrencyAmountProto, testInvalidCurrencyAmountProtoEmpty, testInvalidCurrencyAmountProtoBadDrops, testInvalidPathElementWithAccountCurrency, testInvalidPathElementWithAccountIssuer, testInvalidPathElementProtoEmpty, testInvalidPaymentProtoNoAmount, testInvalidPaymentProtoBadDestination, testInvalidPaymentProtoNoDestination, testInvalidPaymentProtoXrpPaths, testInvalidPaymentProtoXrpSendMax, testInvalidPaymentTransaction, testInvalidSignerProtoNoAccount, testInvalidSignerProtoBadAccount, testInvalidSignerProtoNoPublicKey, testInvalidSignerProtoNoTxnSignature, testInvalidGetTransactionResponseProto, testInvalidGetTransactionResponseProtoUnsupportedType, testInvalidGetTransactionResponseProtoNoTransaction, testInvalidGetTransactionResponseProtoNoAccount, testInvalidGetTransactionResponseProtoBadAccount, testInvalidGetTransactionResponseProtoNoFee, testInvalidGetTransactionResponseProtoBadFee, testInvalidGetTransactionResponseProtoNoSequence, testInvalidGetTransactionResponseProtoNoSigningPublicKey, testInvalidGetTransactionResponseProtoNoSigners, testInvalidGetTransactionResponseProtoNoSignature, testInvalidGetTransactionResponseProtoNoData, testInvalidGetTransactionResponseProtoNoHash, testInvalidGetAccountTransactionHistoryResponse, testInvalidSignerEntryProtoNoAccount, testInvalidSignerEntryProtoBadAccount, testInvalidSignerEntryProtoNoSignerWeight, }
the_stack
import { IAspectExports } from "../util/IAspectExports"; import { Rtrace, BlockInfo, TOTAL_OVERHEAD } from "../util/rTrace"; // @ts-ignore: Constructor is new Long(low, high, signed); import Long from "long"; import { NameSection } from "../util/wasmTools"; import { ReflectedValue } from "../util/ReflectedValue"; import { ReflectedValueType } from "@as-pect/assembly/assembly/internal/ReflectedValueType"; import { TestNode } from "./TestNode"; import { TestNodeType } from "../util/TestNodeType"; import { IReporter } from "../reporter/IReporter"; import { performance } from "perf_hooks"; import { IWarning } from "./IWarning"; import { Snapshot, SnapshotDiffResultType, SnapshotDiff, } from "@as-pect/snapshots"; import { StringifyReflectedValueProps } from "../util/stringifyReflectedValue"; type WASI = import("wasi").WASI; const id = (a: string) => a; const stringifyOptions: Partial<StringifyReflectedValueProps> = { classNameFormatter: id, indent: 0, keywordFormatter: id, maxExpandLevel: Infinity, maxLineLength: Infinity, maxPropertyCount: Infinity, numberFormatter: id, stringFormatter: id, tab: 2, }; type InstantiateResult = { // instance: WebAssembly.Instance; exports: IAspectExports; instance: WebAssembly.Instance; }; /** * This function is a filter for stack trace lines. * * @param {string} input - The stack trace line. */ const wasmFilter = (input: string): boolean => /wasm/i.test(input); /** * This is a collection of all the parameters required for intantiating a TestCollector. */ export interface ITestContextParameters { /** A regular expression that filters what tests can be run. Must be set before calling `testContext.run(wasm);` */ testRegex?: RegExp; /** A regular expression that filters what test groups can be run. Must be set before calling `testContext.run(wasm);` */ groupRegex?: RegExp; /** The test file name. */ fileName?: string; /** The web assembly binary. */ binary?: Uint8Array; /** The reporter. */ reporter: IReporter; /** The expected snapshot output. */ snapshots?: Snapshot; /** WASI, if provided. */ wasi?: WASI | null; } /** This class is responsible for collecting and running all the tests in a test binary. */ export class TestContext { /** The web assembly module if it was set. */ protected wasm: IAspectExports | null = null; /** The name section for function name evaluation. */ protected nameSection: NameSection | null = null; /** The top level node for this test suite. */ public rootNode: TestNode = new TestNode(); /** The current working node that is collecting logs and callback pointers. */ protected targetNode: TestNode = this.rootNode; /** The name of the AssemblyScript test file. */ public fileName: string = ""; /** An indicator to see if the TestSuite passed. */ public pass: boolean = false; /** The test context's reporter. */ protected reporter: IReporter; /** The place where stack traces are stored when a function pointer errors. */ protected stack: string = ""; /** The place where the abort() messages are stored. */ protected message: string = ""; /** The collected actual value. */ protected actual: ReflectedValue | null = null; /** The collected expected value. */ protected expected: ReflectedValue | null = null; /** Filter the tests by regex. */ protected testRegex: RegExp = new RegExp(""); /** Filter the groups by regex. */ protected groupRegex: RegExp = new RegExp(""); /** The test count. */ public testCount: number = 0; /** The number of tests that ran. */ public testRunCount: number = 0; /** The number of passing tests count. */ public testPassCount: number = 0; /** The group count. */ public groupCount: number = 0; /** The number of groups that ran. */ public groupRunCount: number = 0; /** The number of passing groups count. */ public groupPassCount: number = 0; /** The number of todos. */ public todoCount: number = 0; /** A collection of all the generated namespaces for shapshot purposes. */ protected namespaces: Set<string> = new Set<string>(); /** The wasi instance associated with this module */ private wasi: WASI | null = null; /** The WebAssembly.Instance object. */ private instance: WebAssembly.Instance | null = null; /** The module instance. */ // private instance: WebAssembly.Instance | null = null; /** * A collection of reflected values used to help cache and aid in the creation * of nested reflected values. */ private reflectedValueCache: ReflectedValue[] = []; /** A collection of errors. */ public errors: IWarning[] = []; /** A collection of warnings. */ public warnings: IWarning[] = []; /** A collection of collected snapshots. */ public snapshots = new Snapshot(); /** The expected snapshots. */ public expectedSnapshots: Snapshot; public rtrace: Rtrace & { blocks: Map<number, number> }; /** The resulting snapshot diff. */ public snapshotDiff: SnapshotDiff | null = null; constructor(props: ITestContextParameters) { ``; this.rtrace = new Rtrace({ /* istanbul ignore next */ getMemory: () => { /* istanbul ignore next */ return this.wasm!.memory as WebAssembly.Memory; }, /* istanbul ignore next */ onerror: (err: Error, info: BlockInfo) => { /* istanbul ignore next */ return this.onRtraceError(err, info); }, /* istanbul ignore next */ oninfo: (msg: string) => { /* istanbul ignore next */ return this.onRtraceInfo(msg); }, }) as Rtrace & { blocks: Map<number, number> }; /* istanbul ignore next */ if (props.fileName) this.fileName = props.fileName; /* istanbul ignore next */ if (props.testRegex) this.testRegex = props.testRegex; /* istanbul ignore next */ if (props.groupRegex) this.groupRegex = props.groupRegex; if (props.binary) this.nameSection = new NameSection(props.binary); if (props.wasi) this.wasi = props.wasi; this.expectedSnapshots = props.snapshots ? props.snapshots : new Snapshot(); this.reporter = props.reporter; /* istanbul ignore next */ if (typeof props.reporter.onEnter !== "function") { /* istanbul ignore next */ this.pushError({ message: "Invalid reporter callback: onEnter is not a function", stackTrace: "", type: "TestContext Initialization", }); } /* istanbul ignore next */ if (typeof props.reporter.onExit !== "function") { /* istanbul ignore next */ this.pushError({ message: "Invalid reporter callback: onExit is not a function", stackTrace: "", type: "TestContext Initialization", }); } /* istanbul ignore next */ if (typeof props.reporter.onFinish !== "function") { /* istanbul ignore next */ this.pushError({ message: "Invalid reporter callback: onFinish is not a function", stackTrace: "", type: "TestContext Initialization", }); } /** The root node is a group. */ this.rootNode.type = TestNodeType.Group; } /** * Track an rtrace error. This method should be bound and passed to the RTrace options. * * @param err - The error. * @param block - BlockInfo */ // @ts-ignore private onRtraceError(err: Error, block: BlockInfo): void { /* istanbul ignore next */ this.pushError({ message: `Block: ${block.ptr} => ${err.message}`, stackTrace: /* istanbul ignore next */ err.stack?.split("\n").filter(wasmFilter).join("\n") || "No stack trace provided.", type: "rtrace", }); } private onRtraceInfo(_message: string): void { // this.pushWarning({ // message, // stackTrace: this.getLogStackTrace(), // type: "rtrace", // }); } /** * Call this method to start the `__main()` method provided by the `as-pect` exports to start the * process of test collection and evaluation. */ public run(wasm: InstantiateResult): void { /* istanbul ignore next */ this.wasm = wasm.exports || ((<any>wasm) as IAspectExports); this.instance = wasm.instance; // start by visiting the root node this.visit(this.rootNode); // calculate snapshot diff const snapshotDiff = this.snapshots.diff(this.expectedSnapshots); // determine if this test suite passed const snapshotsPass = Array.from(snapshotDiff.results.values()).reduce( (result, value) => { if (result) { return ( // @ts-ignore value.type === SnapshotDiffResultType.Added || // @ts-ignore value.type === SnapshotDiffResultType.NoChange ); } return false; }, true, ); // store the diff results this.snapshotDiff = snapshotDiff; // determine if this test suite passed or failed this.pass = Boolean(snapshotsPass) && this.rootNode.pass; // finish the report this.reporter.onFinish(this); } /** Visit a node and evaluate it's children. */ protected visit(node: TestNode): void { // validate this node will run if (node !== this.rootNode) { const regexTester = node.type === TestNodeType.Group ? this.groupRegex : this.testRegex; if (!regexTester.test(node.name)) return; } // this node is being tested for sure node.ran = true; if (node.type === TestNodeType.Group) { this.groupRunCount += 1; } else { this.testRunCount += 1; } // set the start timer for this node node.start = performance.now(); // set the rtraceStart value node.rtraceStart = this.rtrace.blocks.size; // set the target node for collection this.targetNode = node; // in the case of a throws() test if (node.negated) { const success = this.tryCall(node.callback) === 0; // we want the value to be 0 this.reporter.onEnter(this, node); if (success) { node.message = null; node.stackTrace = null; node.pass = true; node.actual = null; node.expected = null; } node.end = performance.now(); this.addResult(node, success); this.reporter.onExit(this, node); return; } // perform test collection and evaluate the node, each node must set pass to `true` if it passes if (node === this.rootNode) { try { if (this.wasi) { this.wasi!.start(this.instance!); } else { // collect all the top level function pointers, tests, groups, and logs this.wasm!._start(); } } catch (ex) { this.reporter.onEnter(this, node); /** * If this catch occurs, the entire test suite is completed. * This is a sanity check. */ node.end = performance.now(); this.addResult(node, false); this.reporter.onExit(this, node); return; } } else { // gather all the tests and groups, validate program state at this level const success = this.tryCall(node.callback) === 1; this.reporter.onEnter(this, node); if (!success) { // collection or test failure, stop traversal of this node this.collectStatistics(node); this.addResult(node, false); this.reporter.onExit(this, node); return; } } // Errors can occur at any level before you visit them, even if nothing was thrown if (node.errors.length > 0) { this.collectStatistics(node); this.addResult(node, false); this.reporter.onExit(this, node); return; } // We now have the responsibility to run each beforeAll callback before traversing children if (!this.runFunctions(node.beforeAll)) { this.collectStatistics(node); this.addResult(node, false); this.reporter.onExit(this, node); return; } // now that the tests have been collected and the beforeAll has run, visit each child const children = node.children; for (let i = 0; i < children.length; i++) { const child = children[i]; // in the context of running a test, run the beforeEach functions if (child.type === TestNodeType.Test) { if (!this.runBeforeEach(node)) { this.collectStatistics(node); this.addResult(node, false); this.reporter.onExit(this, node); return; } } // now we can visit the child this.visit(child); // in the context of running a test, run the afterEach functions if (child.type === TestNodeType.Test) { if (!this.runAfterEach(node)) { this.collectStatistics(node); this.addResult(node, false); this.reporter.onExit(this, node); return; } } } // We now have the responsibility to run each afterAll callback after traversing children if (!this.runFunctions(node.afterAll)) { this.collectStatistics(node); this.addResult(node, false); this.reporter.onExit(this, node); return; } // if any children failed, this node failed too, but assume it passes node.pass = node.children.reduce( (pass: boolean, node: TestNode) => pass && node.pass, true, ); node.end = performance.now(); this.addResult(node, true); this.reporter.onExit(this, node); } /** Report a TestNode */ private reportTestNode( type: TestNodeType, descriptionPointer: number, callbackPointer: number, negated: 1 | 0, messagePointer: number, ): void { const parent = this.targetNode; const node = new TestNode(); node.type = type; node.name = this.getString(descriptionPointer, node.name); node.callback = callbackPointer; node.negated = negated === 1; node.message = node.negated ? this.getString(messagePointer, "No Message Provided.") : node.message; // namespacing for snapshots later const namespacePrefix = `${parent.namespace}!~${node.name}`; let i = 0; while (true) { const namespace = `${namespacePrefix}[${i}]`; if (this.namespaces.has(namespace)) { i++; continue; } node.namespace = namespace; this.namespaces.add(namespace); break; } // fix the node hierarchy node.parent = parent; parent.children.push(node); } /** Obtain the stack trace, actual, expected, and message values, and attach them to a given node. */ private collectStatistics(node: TestNode): void { node.stackTrace = this.stack; node.actual = this.actual; node.expected = this.expected; node.message = this.message; node.end = performance.now(); node.rtraceEnd = this.rtrace.blocks.size; } /** Add a test or group result to the statistics. */ private addResult(node: TestNode, pass: boolean): void { if (node.type === TestNodeType.Group) { this.groupCount += 1; if (pass) this.groupPassCount += 1; } else { this.testCount += 1; if (pass) this.testPassCount += 1; } this.todoCount += node.todos.length; } /** Run a series of callbacks into web assembly. */ private runFunctions(funcs: number[]): boolean { for (let i = 0; i < funcs.length; i++) { if (this.tryCall(funcs[i]) === 0) return false; } return true; } /** Run every before each callback in the proper order. */ private runBeforeEach(node: TestNode): boolean { return node.parent ? //run parents first and bail early if the parents failed this.runBeforeEach(node.parent) && this.runFunctions(node.beforeEach) : this.runFunctions(node.beforeEach); } /** Run every before each callback in the proper order. */ private runAfterEach(node: TestNode): boolean { return node.parent ? //run parents first and bail early if the parents failed this.runAfterEach(node.parent) && this.runFunctions(node.afterEach) : this.runFunctions(node.afterEach); } /** * This method creates a WebAssembly imports object with all the TestContext functions * bound to the TestContext. * * @param {any[]} imports - Every import item specified. */ public createImports(...imports: any[]): any { const finalImports: any = {}; for (const moduleImport of imports) { for (const [key, value] of Object.entries(moduleImport)) { /* istanbul ignore next */ if (key === "__aspect") continue; /* istanbul ignore next */ finalImports[key] = Object.assign(finalImports[key] || {}, value); } } finalImports.__aspect = { attachStackTraceToReflectedValue: this.attachStackTraceToReflectedValue.bind(this), afterAll: this.reportAfterAll.bind(this), afterEach: this.reportAfterEach.bind(this), beforeAll: this.reportBeforeAll.bind(this), beforeEach: this.reportBeforeEach.bind(this), clearActual: this.clearActual.bind(this), clearExpected: this.clearExpected.bind(this), createReflectedValue: this.createReflectedValue.bind(this), createReflectedNumber: this.createReflectedNumber.bind(this), createReflectedLong: this.createReflectedLong.bind(this), debug: this.debug.bind(this), logReflectedValue: this.logReflectedValue.bind(this), pushReflectedObjectKey: this.pushReflectedObjectKey.bind(this), pushReflectedObjectValue: this.pushReflectedObjectValue.bind(this), reportActualReflectedValue: this.reportActualReflectedValue.bind(this), reportExpectedFalsy: this.reportExpectedFalsy.bind(this), reportExpectedFinite: this.reportExpectedFinite.bind(this), reportExpectedReflectedValue: this.reportExpectedReflectedValue.bind(this), reportNegatedTestNode: this.reportNegatedTestNode.bind(this), reportTodo: this.reportTodo.bind(this), reportTestTypeNode: this.reportTestTypeNode.bind(this), reportGroupTypeNode: this.reportGroupTypeNode.bind(this), reportExpectedSnapshot: this.reportExpectedSnapshot.bind(this), reportExpectedTruthy: this.reportExpectedTruthy.bind(this), tryCall: this.tryCall.bind(this), }; this.rtrace.install(finalImports); finalImports.rtrace.onalloc = this.onalloc.bind(this); finalImports.rtrace.onfree = this.onfree.bind(this); /** add an env object */ finalImports.env = finalImports.env || {}; /** Override the abort function */ const previousAbort = finalImports.env.abort || (() => {}); finalImports.env.abort = (...args: any[]) => { previousAbort(...args); // @ts-ignore this.abort(...args); }; /** Override trace completely. */ finalImports.env.trace = this.trace.bind(this); // add wasi support if requested if (this.wasi) { finalImports.wasi_snapshot_preview1 = this.wasi.wasiImport; } return finalImports; } /** * This function sets up a test group. * * @param {number} description - The test suite description string pointer. * @param {number} runner - The pointer to a test suite callback */ private reportGroupTypeNode(description: number, runner: number): void { this.reportTestNode(TestNodeType.Group, description, runner, 0, 0); } /** * This function sets up a test node. * * @param description - The test description string pointer * @param runner - The pointer to a test callback */ private reportTestTypeNode(description: number, runner: number): void { this.reportTestNode(TestNodeType.Test, description, runner, 0, 0); } /** * This function expects a throws from a test node. * * @param description - The test description string pointer * @param runner - The pointer to a test callback * @param message - The pointer to an additional assertion message in string */ private reportNegatedTestNode( description: number, runner: number, message: number, ): void { this.reportTestNode(TestNodeType.Test, description, runner, 1, message); } /** * This is called to stop the debugger. e.g. `node --inspect-brk asp`. */ /* istanbul ignore next */ private debug(): void { /* istanbul ignore next */ debugger; } /** * This is a web assembly utility function that wraps a function call in a try catch block to * report success or failure. * * @param {number} pointer - The function pointer to call. It must accept no parameters and return * void. * @returns {1 | 0} - If the callback was run successfully without error, it returns 1, else it * returns 0. */ protected tryCall(pointer: number): 1 | 0 { /** This is a safety net conditional, no reason to test it. */ /* istanbul ignore next */ if (pointer < 0) return 1; try { this.wasm!.__call(pointer); } catch (ex) { this.stack = this.getErrorStackTrace(ex); return 0; } return 1; } /** * This web assembly linked function sets the group's "beforeEach" callback pointer to * the current groupStackItem. * * @param {number} callbackPointer - The callback that should run before each test. */ private reportBeforeEach(callbackPointer: number): void { this.targetNode.beforeEach.push(callbackPointer); } /** * This web assembly linked function adds the group's "beforeAll" callback pointer to * the current groupStackItem. * * @param {number} callbackPointer - The callback that should run before each test in the * current context. */ private reportBeforeAll(callbackPointer: number): void { this.targetNode.beforeAll.push(callbackPointer); } /** * This web assembly linked function sets the group's "afterEach" callback pointer. * * @param {number} callbackPointer - The callback that should run before each test group. */ private reportAfterEach(callbackPointer: number): void { this.targetNode.afterEach.push(callbackPointer); } /** * This web assembly linked function adds the group's "afterAll" callback pointer to * the current groupStackItem. * * @param {number} callbackPointer - The callback that should run before each test in the * current context. */ private reportAfterAll(callbackPointer: number): void { this.targetNode.afterAll.push(callbackPointer); } /** * This function reports a single "todo" item in a test suite. * * @param {number} todoPointer - The todo description string pointer. * @param {number} _callbackPointer - The test callback function pointer. */ private reportTodo(todoPointer: number, _callbackPointer: number): void { this.targetNode.todos.push( this.getString(todoPointer, "No todo() value provided."), ); } /** * This function overrides the provided AssemblyScript `env.abort()` function to catch abort * reasons. * * @param {number} reasonPointer - This points to the message value that causes the expectation to * fail. * @param {number} fileNamePointer - The file name that reported the error. (Ignored) * @param {number} line - The line that reported the error. (Ignored) * @param {number} col - The column that reported the error. (Ignored) */ private abort( reasonPointer: number, fileNamePointer: number, line: number, col: number, ): void { this.message = this.getString( reasonPointer, `Error in ${this.getString( fileNamePointer, "[No Filename Provided]", )}:${line}:${col} `, ); } /** * Gets an error stack trace. */ protected getErrorStackTrace(ex: Error): string { var stackItems = ex.stack!.toString().split("\n"); return [stackItems[0], ...stackItems.slice(1).filter(wasmFilter)].join( "\n", ); } /** * Gets a log stack trace. */ protected getLogStackTrace(): string { return new Error("Get stack trace.") .stack!.toString() .split("\n") .slice(1) .filter(wasmFilter) .join("\n"); } /** A map of strings that can be cached because they are static. */ private cachedStrings = new Map<number, string>(); /** * This method is called when a memory block is deallocated from the heap. * * @param {number} block - This is a unique identifier for the affected block. */ public onfree(block: number): void { this.targetNode.frees += 1; // remove any cached strings at this pointer this.cachedStrings.delete(block + TOTAL_OVERHEAD); this.rtrace.onfree(block); } /** * This method is called when a memory block is allocated on the heap. * * @param {number} block - This is a unique identifier for the affected block. */ public onalloc(block: number): void { this.targetNode.allocations += 1; this.rtrace.onalloc(block); } /** * Gets a string from the wasm module, unless the module string is null. Otherwise it returns * a default value. */ protected getString(pointer: number, defaultValue: string): string { pointer >>>= 0; if (pointer === 0) return defaultValue; if (this.cachedStrings.has(pointer)) { return this.cachedStrings.get(pointer)!; } const result = this.wasm!.__getString(pointer); this.cachedStrings.set(pointer, result); return result; } /** * An override implementation of the AssemblyScript trace function. * * @param {number} strPointer - The trace string. * @param {number} count - The number of arguments to be traced. * @param {number[]} args - The traced arguments. */ private trace(strPointer: number, count: number, ...args: number[]): void { const reflectedValue = new ReflectedValue(); reflectedValue.pointer = strPointer; reflectedValue.stack = this.getLogStackTrace(); reflectedValue.typeName = "trace"; reflectedValue.type = ReflectedValueType.String; reflectedValue.value = `trace: ${this.getString(strPointer, "")} ${args .slice(0, count) .join(", ")}`; // push the log value to the logs this.targetNode.logs.push(reflectedValue); } /** * Retrieve the function name of a given web assembly function. * * @param {number} index - The function index */ private funcName(index: number): string { const nameSection = this.nameSection; /* istanbul ignore next */ if (nameSection) { const result = this.wasm!.table!.get(index); return nameSection.fromIndex(parseInt(result!.name)); } /* istanbul ignore next */ return ""; } private createReflectedValue( isNull: 1 | 0, hasKeys: 1 | 0, nullable: 1 | 0, offset: number, // offsetof<T>("propName") pointer: number, // changetype<usize>(this) | 0 signed: 1 | 0, // isSigned<T>() size: number, // sizeof<T>() reflectedTypeValue: ReflectedValueType, typeId: number, // idof<T>() typeName: number, // nameof<T>() value: number, // usize hasValues: 1 | 0, // bool isManaged: 1 | 0, // bool ): number { const reflectedValue = new ReflectedValue(); reflectedValue.isNull = isNull === 1; reflectedValue.keys = hasKeys ? [] : null; reflectedValue.nullable = nullable === 1; reflectedValue.offset = offset; reflectedValue.pointer = pointer; reflectedValue.signed = signed === 1; reflectedValue.size = size; reflectedValue.type = reflectedTypeValue; reflectedValue.typeId = typeId; reflectedValue.typeName = this.getString(typeName, ""); reflectedValue.values = hasValues ? [] : null; reflectedValue.isManaged = isManaged === 1; if (isNull === 1) { reflectedValue.value = "null"; } else if (reflectedTypeValue === ReflectedValueType.String) { reflectedValue.value = this.getString(value, ""); } else if (reflectedTypeValue === ReflectedValueType.Function) { reflectedValue.value = this.funcName(value); } else { reflectedValue.value = value; } return this.reflectedValueCache.push(reflectedValue) - 1; } /** * Create a reflected number value. * * @param {1 | 0} signed - Indicate if the value is signed. * @param {number} size - The size of the value in bytes. * @param {ReflectedValueType} reflectedTypeValue - The ReflectedValueType * @param {number} typeName - The name of the type. * @param {number} value - The value itself */ private createReflectedNumber( signed: 1 | 0, // isSigned<T>() size: number, // sizeof<T>() reflectedTypeValue: ReflectedValueType, typeName: number, // nameof<T>() value: number, // f64 ): number { const reflectedValue = new ReflectedValue(); reflectedValue.signed = signed === 1; reflectedValue.size = size; reflectedValue.type = reflectedTypeValue; reflectedValue.typeName = this.getString(typeName, ""); reflectedValue.value = value; return this.reflectedValueCache.push(reflectedValue) - 1; } /** * Create reflection of a long number (not supported directly from javascript) */ private createReflectedLong( signed: 1 | 0, // isSigned<T>() size: number, // sizeof<T>() reflectedTypeValue: ReflectedValueType, typeName: number, // nameof<T>() lowValue: number, // i32 highValue: number, // i32 ): number { const reflectedValue = new ReflectedValue(); reflectedValue.signed = signed === 1; reflectedValue.size = size; reflectedValue.type = reflectedTypeValue; reflectedValue.typeName = this.getString(typeName, ""); reflectedValue.value = Long.fromBits( lowValue >>> 0, highValue >>> 0, signed === 0, ).toString(); return this.reflectedValueCache.push(reflectedValue) - 1; } /** * Log a reflected value. * * @param {number} id - The ReflectedValue id */ private logReflectedValue(id: number): void { /* istanbul ignore next */ if (id >= this.reflectedValueCache.length || id < 0) { /* istanbul ignore next */ this.pushError({ message: `Cannot log ReflectedValue of id ${id}. Index out of bounds.`, stackTrace: this.getLogStackTrace(), type: "ReflectedValue", }); /* istanbul ignore next */ return; } this.targetNode.logs.push(this.reflectedValueCache[id]); } /** * Report an actual reflected value. * * @param {number} id - The ReflectedValue id */ private reportActualReflectedValue(id: number): void { // ignored lines are santiy checks for error reporting /* istanbul ignore next */ if (id >= this.reflectedValueCache.length || id < 0) { /* istanbul ignore next */ this.pushError({ message: `Cannot report actual ReflectedValue of id ${id}. Index out of bounds.`, stackTrace: this.getLogStackTrace(), type: "ReflectedValue", }); /* istanbul ignore next */ return; } this.actual = this.reflectedValueCache[id]; } /** * Report an expected reflected value. * * @param {number} id - The ReflectedValue id */ private reportExpectedReflectedValue(id: number, negated: number): void { // ignored lines are error reporting for sanity checks /* istanbul ignore next */ if (id >= this.reflectedValueCache.length || id < 0) { /* istanbul ignore next */ this.pushError({ message: `Cannot report expected ReflectedValue of id ${id}. Index out of bounds.`, stackTrace: this.getLogStackTrace(), type: "ReflectedValue", }); /* istanbul ignore next */ return; } this.expected = this.reflectedValueCache[id]; this.expected.negated = negated === 1; } /** * Push a reflected value to a given reflected value. * * @param {number} reflectedValueID - The target reflected value parent. * @param {number} childID - The child value by it's id to be pushed. */ private pushReflectedObjectValue( reflectedValueID: number, childID: number, ): void { // each ignored line for test coverage is error reporting for sanity checks /* istanbul ignore next */ if ( reflectedValueID >= this.reflectedValueCache.length || reflectedValueID < 0 ) { /* istanbul ignore next */ this.pushError({ message: `Cannot push ReflectedValue of id ${childID} to ReflectedValue ${reflectedValueID}. ReflectedValue id out of bounds.`, stackTrace: this.getLogStackTrace(), type: "ReflectedValue", }); /* istanbul ignore next */ return; } /* istanbul ignore next */ if (childID >= this.reflectedValueCache.length || childID < 0) { /* istanbul ignore next */ this.pushError({ message: `Cannot push ReflectedValue of id ${childID} to ReflectedValue ${reflectedValueID}. ReflectedValue id out of bounds.`, stackTrace: this.getLogStackTrace(), type: "ReflectedValue", }); /* istanbul ignore next */ return; } let reflectedParentValue = this.reflectedValueCache[reflectedValueID]; let childValue = this.reflectedValueCache[childID]; /* istanbul ignore next */ if (!reflectedParentValue.values) { /* istanbul ignore next */ this.pushError({ message: `Cannot push ReflectedValue of id ${childID} to ReflectedValue ${reflectedValueID}. ReflectedValue was not initialized with a values array.`, stackTrace: this.getLogStackTrace(), type: "ReflectedValue", }); /* istanbul ignore next */ return; } reflectedParentValue.values.push(childValue); } /** * Push a reflected value key to a given reflected value. * * @param {number} reflectedValueID - The target reflected value parent. * @param {number} keyId - The target reflected value key to be pushed. */ private pushReflectedObjectKey( reflectedValueID: number, keyId: number, ): void { // every ignored line for test coverage in this function are sanity checks /* istanbul ignore next */ if ( reflectedValueID >= this.reflectedValueCache.length || reflectedValueID < 0 ) { /* istanbul ignore next */ this.pushError({ message: `Cannot push ReflectedValue of id ${keyId} to ReflectedValue ${reflectedValueID}. ReflectedValue id out of bounds.`, stackTrace: this.getLogStackTrace(), type: "ReflectedValue", }); /* istanbul ignore next */ return; } /* istanbul ignore next */ if (keyId >= this.reflectedValueCache.length || keyId < 0) { /* istanbul ignore next */ this.pushError({ message: `Cannot push ReflectedValue of id ${keyId} to ReflectedValue ${reflectedValueID}. ReflectedValue key id out of bounds.`, stackTrace: this.getLogStackTrace(), type: "ReflectedValue", }); /* istanbul ignore next */ return; } let reflectedValue = this.reflectedValueCache[reflectedValueID]; let key = this.reflectedValueCache[keyId]; // this is a failsafe if a keys[] does not exist on the ReflectedValue /* istanbul ignore next */ if (!reflectedValue.keys) { /* istanbul ignore next */ this.pushError({ message: `Cannot push ReflectedValue of id ${keyId} to ReflectedValue ${reflectedValueID}. ReflectedValue was not initialized with a keys array.`, stackTrace: this.getLogStackTrace(), type: "ReflectedValue", }); /* istanbul ignore next */ return; } reflectedValue.keys.push(key); } /** * Clear the expected value. */ private clearExpected(): void { this.expected = null; } /** * Clear the actual value. */ private clearActual(): void { this.actual = null; } /** * Report an expected truthy value, and if it's negated. * * @param {1 | 0} negated - An indicator if the expectation is negated. */ private reportExpectedTruthy(negated: number): void { const expected = (this.expected = new ReflectedValue()); expected.negated = negated === 1; expected.type = ReflectedValueType.Truthy; } /** * Report an expected truthy value, and if it's negated. * * @param {1 | 0} negated - An indicator if the expectation is negated. */ private reportExpectedFalsy(negated: number): void { const expected = (this.expected = new ReflectedValue()); expected.negated = negated === 1; expected.type = ReflectedValueType.Falsy; } /** * Report an expected finite value, and if it's negated. * * @param {1 | 0} negated - An indicator if the expectation is negated. */ private reportExpectedFinite(negated: number): void { const expected = (this.expected = new ReflectedValue()); expected.negated = negated === 1; expected.type = ReflectedValueType.Finite; } /** * Attaches a stack trace to the given reflectedValue by it's id. * * @param {number} reflectedValueID - The given reflected value by it's id. */ private attachStackTraceToReflectedValue(reflectedValueID: number): void { /* istanbul ignore next */ if ( reflectedValueID >= this.reflectedValueCache.length || reflectedValueID < 0 ) { /* istanbul ignore next */ this.pushError({ message: `Cannot push a stack trace to ReflectedValue ${reflectedValueID}. ReflectedValue id out of bounds.`, stackTrace: this.getLogStackTrace(), type: "ReflectedValue", }); /* istanbul ignore next */ return; } this.reflectedValueCache[reflectedValueID].stack = this.getLogStackTrace(); } /** Push an error to the errors array. */ protected pushError(error: IWarning): void { this.targetNode.errors.push(error); this.errors.push(error); } /** Push an warning to the warnings array. */ /* istanbul ignore next */ protected pushWarning(warning: IWarning): void { /* istanbul ignore next */ this.targetNode.warnings.push(warning); /* istanbul ignore next */ this.warnings.push(warning); } /** * Report an expected snapshot. * * @param {number} reflectedValueID - The id of the reflected actual value. * @param {number} namePointer - The name of the snapshot. */ protected reportExpectedSnapshot( reflectedValueID: number, namePointer: number, ): void { const name = `${this.targetNode.name}!~${this.getString(namePointer, "")}`; /* istanbul ignore next */ if ( reflectedValueID >= this.reflectedValueCache.length || reflectedValueID < 0 ) { /* istanbul ignore next */ this.pushError({ message: `Cannot add snapshot ${name} with reflected value ${reflectedValueID}. ReflectedValue id out of bounds.`, stackTrace: this.getLogStackTrace(), type: "ReflectedValue", }); /* istanbul ignore next */ return; } this.snapshots.add( name, this.reflectedValueCache[reflectedValueID].stringify(stringifyOptions), ); } }
the_stack
import { TimeInstant } from '../time'; import { Command } from 'nf-grapher'; import { ScoreAudioParam } from '../params/ScoreAudioParam'; import { SPNode, NodePlaybackDescription } from './SPNode'; import { SPNodeFactory } from './SPNodeFactory'; import { mixdown, asInterleaved, asPlanar } from '../AudioBufferUtils'; import { ContentCache } from '../ContentCache'; import { SoundTouch } from 'soundtouch-ts'; import { CommandsMutation, applyMutationToParam } from '../Mutations'; import { debug as Debug } from 'debug'; import { XAudioBuffer } from '../XAudioBuffer'; const DBG_STR = 'nf:stretchnode'; const dbg = Debug(DBG_STR); // This will never be used, but is purely here to satisfy Term 6b of the // LGPL2.1: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html, which // mandates that the user, at runtime, can use a copy of the software already // present on their system. This avoids forcing NFPlayerJS and derivative // software from needing to be licensed under the LGPL2.1. let SHARED_SOUNDTOUCH_CTOR: typeof SoundTouch; if ( typeof global !== 'undefined' && typeof (global as any).SoundTouch !== 'undefined' ) { SHARED_SOUNDTOUCH_CTOR = (global as any).SoundTouch; } else if ( typeof window !== 'undefined' && typeof (window as any).SoundTouch !== 'undefined' ) { SHARED_SOUNDTOUCH_CTOR = (window as any).SoundTouch; } else { SHARED_SOUNDTOUCH_CTOR = SoundTouch; } // This is only used to help differentiate debug logs. I don't like it, // but not sure of a better way without great complication (global id // store???). Node ids are not checked for uniqueness, since the player // does not look at ids of either graphs or nodes unless a mutation arrives. let uniqId = 0; export class SPStretchNode extends SPNode { // TODO: looks like TS Grapher doesn't expose the default/initial values. // Also might have to fork PseudoAudioParam and add in default/initial values. protected stretchParam = new ScoreAudioParam(1); protected pitchRatioParam = new ScoreAudioParam(1); protected previousFeedTime: TimeInstant = TimeInstant.ZERO; protected requestedAncestorSamples: number = 0; protected st: SoundTouch = new SHARED_SOUNDTOUCH_CTOR(this.info.sampleRate); // Again, this is only for debug logs! protected uniqId = uniqId++; async nodeDidMount() { this.stretchParam.applyScoreCommands(this.node.params!.stretch); this.pitchRatioParam.applyScoreCommands(this.node.params!.pitchRatio); } async nodeWillUnmount() { dbg.enabled && dbg( '%s %d unmounting. requestedAncestorSamples %f, previousFeed %f', this.node.id, this.uniqId, this.requestedAncestorSamples, this.previousFeedTime.asSamples(this.info.sampleRate) ); } async timeChange( renderTime: TimeInstant, cache: ContentCache, quantumSize: number ) { const stretchValue = this.stretchParam.getValueAtTime( renderTime.asSeconds() ); const dilated = renderTime.scale(stretchValue); // Short circuiting since these values are not just simple reads. dbg.enabled && dbg( '%s %d timeChange to %d, dilated %d. prev requested samples %d.', this.node.id, this.uniqId, renderTime.asSamples(this.info.sampleRate), dilated.asSamples(this.info.sampleRate), this.requestedAncestorSamples ); await super.timeChange(dilated, cache, quantumSize); this.previousFeedTime = TimeInstant.from(renderTime); this.requestedAncestorSamples = this.estimateRequestedAncestorSamples( renderTime, quantumSize ); dbg( '%s %d new requested samples estimate: %d', this.node.id, this.uniqId, this.requestedAncestorSamples ); // TODO: does this do what I hope it does? this.st.clear(); this.st = new SHARED_SOUNDTOUCH_CTOR(this.info.sampleRate); } // This is still quite inaccurate, at least audibly. Could be SoundTouch itself, // but more likely just need more accurate estimation (verlet integration?). estimateRequestedAncestorSamples( renderTime: TimeInstant, quantumSize: number ) { const hz = this.info.sampleRate; const renderTimeSamples = renderTime.asSamples(hz); const frameDuration = TimeInstant.fromSamples(quantumSize, hz); let receivedSamples = 0; let requiredSamples = 0; while (receivedSamples <= renderTimeSamples) { const frameStart = TimeInstant.fromSamples(receivedSamples, hz); const frameEnd = frameStart.add(frameDuration); const seconds = frameStart.asSeconds(); const frameEndSeconds = frameEnd.asSeconds(); const startStretchValue = this.stretchParam.getValueAtTime(seconds); const endStretchValue = this.stretchParam.getValueAtTime(frameEndSeconds); const averageStretchValue = (endStretchValue + startStretchValue) / 2; const startPitchValue = this.pitchRatioParam.getValueAtTime(seconds); const endPitchValue = this.pitchRatioParam.getValueAtTime( frameEndSeconds ); const avgPitchValue = (endPitchValue + startPitchValue) / 2; // https://github.com/kirbysayshi/soundtouch-ts/blob/d0c8ddd8ee78e25c0c278870188c5cec72cb2063/src/index.ts#L842-L854 const stVirtualPitch = avgPitchValue; const stVirtualTempo = 1 / averageStretchValue; // inverse, compared to Scores! const stVirtualRate = 1; // This is not exposed in Scores, specific to ST. const stTempo = stVirtualTempo / stVirtualPitch; const stRate = stVirtualRate * stVirtualPitch; // https://www.surina.net/soundtouch/faq.html#sample_processing // Number_of_output_samples = Number_of_input_samples / (tempo_change * rate_change) // Algebra... // num_output_samples * (tempo_change * rate_change) = num_input_samples const inputSamples = quantumSize * stTempo * stRate; requiredSamples += inputSamples; receivedSamples += quantumSize; } return requiredSamples; } getPlaybackDescription( renderTime: TimeInstant, descriptions: NodePlaybackDescription[] ) { const ancestorRenderTime = TimeInstant.fromSamples( this.requestedAncestorSamples, this.info.sampleRate ); const desc: NodePlaybackDescription = { id: this.node.id, kind: this.node.kind, time: ancestorRenderTime }; descriptions.push(desc); SPNodeFactory.getPlaybackDescription( this.ancestors, ancestorRenderTime, descriptions ); } feed(renderTime: TimeInstant, buffers: XAudioBuffer[], sampleCount: number) { const hz = this.info.sampleRate; const seconds = renderTime.asSeconds(); const frameDuration = TimeInstant.fromSamples(sampleCount, hz); const frameEnd = renderTime.add(frameDuration); const frameEndSeconds = frameEnd.asSeconds(); // Stretch factor is hard here, I guess just average it given the sample window? const startStretchValue = this.stretchParam.getValueAtTime(seconds); const endStretchValue = this.stretchParam.getValueAtTime(frameEndSeconds); const averageStretchValue = (endStretchValue + startStretchValue) / 2; // Average the pitch factor too. const startPitchValue = this.pitchRatioParam.getValueAtTime(seconds); const endPitchValue = this.pitchRatioParam.getValueAtTime(frameEndSeconds); const averagePitchValue = (endPitchValue + startPitchValue) / 2; // Have to use samples to avoid floating point precision. const renderTimeSamples = renderTime.asSamples(hz); const previousFeedTimeSamples = this.previousFeedTime.asSamples(hz); if (renderTimeSamples < previousFeedTimeSamples) { const hz = this.info.sampleRate; const prevFeed = this.previousFeedTime; // We have gone back in time! We need to reset in order to request the // right time from our ancestors. this.requestedAncestorSamples = this.estimateRequestedAncestorSamples( renderTime, sampleCount ); // Short circuiting since these values are not just simple reads. dbg.enabled && dbg( '%s %d prev feed time (%f) was _after_ current feed time (%f). ' + 'Estimating prev feed as %f and requested samples as %f', this.node.id, this.uniqId, prevFeed.asSamples(hz), renderTime.asSamples(hz), this.previousFeedTime.asSamples(hz), this.requestedAncestorSamples ); // Also need to reset the time stretcher to avoid drifting over multiple // loops (especially infinite). this.st.clear(); dbg( '%s %d reset ancestor samples to %f', this.node.id, this.uniqId, this.requestedAncestorSamples ); } // NOTE: // stretch of 0.5 means "play the audio in 1/2 the time" // pitch of 2 means "play the audio at 2x the pitch/frequency" // Unfortunately, this SoundTouch port is hard coded to two channels. // We need to account for this in all puts/requests to/from SoundTouch. const CHANNEL_COUNT = 2; // NOTE: This port of SoundTouch does not allow for configuring of // processing windows or durations! // SoundTouch uses Interleaved buffers, so we cannot use AudioBuffers. const output = new Float32Array(sampleCount * CHANNEL_COUNT); // TODO: can probably apply both at a more granular level, if we request // a smaller number of frames from SoundTouch. this.st.pitch = averagePitchValue; // soundtouch uses the inverse. this.st.tempo = 1 / averageStretchValue; // These include _all_ channels let receivedSamples = 0; const requiredSampleCount = sampleCount * CHANNEL_COUNT; // SoundTouch uses Interleaved buffers, so we cannot use AudioBuffers' // implicit notion of length == a single channel. while (receivedSamples < requiredSampleCount) { this.st.process(); // SoundTouch considers a "frame" a pair of samples for LR channels. // Calling them iFrames here to differentiate between other plugins that // consider a "frame" the current sample rendering window. const queuedIFrames = this.st.outputBuffer.frameCount; const iFrameCount = sampleCount / CHANNEL_COUNT; const receiver = output.subarray(receivedSamples); // This ST assumes two channels, always, and does math internally // to expand the numbers. Need to halve what we request because of it. const requestedFrameCount = Math.min( Math.floor(iFrameCount), Math.floor(receiver.length / CHANNEL_COUNT) ); this.st.outputBuffer.receiveSamples(receiver, requestedFrameCount); const remainingIFrames = this.st.outputBuffer.frameCount; const receivedThisStep = (queuedIFrames - remainingIFrames) * CHANNEL_COUNT; receivedSamples += receivedThisStep; if (receivedThisStep > 0) { // We might have enough, so spin the loop to check again. continue; } // Got nothing, so request from ancestors and inject! const ancestorScratch = new XAudioBuffer({ numberOfChannels: CHANNEL_COUNT, length: sampleCount, sampleRate: hz }); const frameStartSamples = this.requestedAncestorSamples; const ancestorBuffers: XAudioBuffer[] = []; SPNodeFactory.feed( this.ancestors, TimeInstant.fromSamples(frameStartSamples, hz), ancestorBuffers, sampleCount ); mixdown(ancestorScratch, ancestorBuffers); this.requestedAncestorSamples += sampleCount; const interleaved = asInterleaved(ancestorScratch); this.st.inputBuffer.putSamples(interleaved); } const planar = asPlanar(output, this.info.sampleRate, CHANNEL_COUNT); buffers.push(planar); this.previousFeedTime = TimeInstant.from(renderTime); } acceptCommandsEffect(effect: CommandsMutation) { const { paramName } = effect; let param: ScoreAudioParam | null = null; let gparam: Command[] | null = null; switch (paramName) { case 'stretch': { param = this.stretchParam; gparam = this.node.params!.stretch; break; } case 'pitchRatio': { param = this.pitchRatioParam; gparam = this.node.params!.pitchRatio; break; } case 'formantRatio': { gparam = this.node.params!.formantRatio; break; } } if (!param || !gparam) { throw new Error(`Unknown or Unimplemented Param with name ${paramName}`); } return applyMutationToParam(effect, param, gparam); } }
the_stack
import '../common/eager_offset' import { Bytes } from '../common/collections' import { BigInt } from '../common/numbers' // Most types from this namespace are direct mappings or adaptations from: // https://github.com/streamingfast/proto-near/blob/develop/sf/near/codec/v1/codec.proto export namespace near { export type CryptoHash = Bytes export type Account = string export type BlockHeight = u64 export type Balance = BigInt export type Gas = u64 export type ShardId = u64 export type NumBlocks = u64 export type ProtocolVersion = u32 export type Payload = u64 export enum CurveKind { ED25519 = 0, SECP256K1 = 1, } export class Signature { constructor( public kind: CurveKind, public bytes: Bytes, ) {} } export class PublicKey { constructor( public kind: CurveKind, public bytes: Bytes, ) {} } export enum AccessKeyPermissionKind { FUNCTION_CALL = 0, FULL_ACCESS = 1, } export class FunctionCallPermission { constructor( public allowance: BigInt, public receiverId: string, public methodNames: Array<string>, ) {} } export class FullAccessPermission {} export class AccessKeyPermissionValue { constructor( public kind: AccessKeyPermissionKind, public data: Payload, ) {} toFunctionCall(): FunctionCallPermission { assert(this.kind == AccessKeyPermissionKind.FUNCTION_CALL, 'AccessKeyPermissionValue is not a \'FunctionCall\'.') return changetype<FunctionCallPermission>(this.data as u32) } toFullAccess(): FullAccessPermission { assert(this.kind == AccessKeyPermissionKind.FULL_ACCESS, 'AccessKeyPermissionValue is not a \'FullAccess\'.') return changetype<FullAccessPermission>(this.data as u32) } static fromFunctionCall(input: FunctionCallPermission): AccessKeyPermissionValue { return new AccessKeyPermissionValue(AccessKeyPermissionKind.FUNCTION_CALL, changetype<u32>(input)) } static fromFullAccess(input: FullAccessPermission): AccessKeyPermissionValue { return new AccessKeyPermissionValue(AccessKeyPermissionKind.FULL_ACCESS, changetype<u32>(input)) } } export class AccessKey { constructor( public nonce: u64, public permission: AccessKeyPermissionValue, ) {} } export class DataReceiver { constructor( public dataId: CryptoHash, public receiverId: string, ) {} } export enum ActionKind { CREATE_ACCOUNT = 0, DEPLOY_CONTRACT = 1, FUNCTION_CALL = 2, TRANSFER = 3, STAKE = 4, ADD_KEY = 5, DELETE_KEY = 6, DELETE_ACCOUNT = 7, } export class CreateAccountAction {} export class DeployContractAction { constructor( public codeHash: Bytes, ) {} } export class FunctionCallAction { constructor( public methodName: string, public args: Bytes, public gas: u64, public deposit: BigInt, ) {} } export class TransferAction { constructor( public deposit: BigInt, ) {} } export class StakeAction { constructor( public stake: Balance, public publicKey: PublicKey, ) {} } export class AddKeyAction { constructor( public publicKey: PublicKey, public accessKey: AccessKey, ) {} } export class DeleteKeyAction { constructor( public publicKey: PublicKey, ) {} } export class DeleteAccountAction { constructor( public beneficiaryId: Account, ) {} } export class ActionValue { constructor( public kind: ActionKind, public data: Payload, ) {} toCreateAccount(): CreateAccountAction { assert(this.kind == ActionKind.CREATE_ACCOUNT, 'ActionValue is not a \'CreateAccount\'.') return changetype<CreateAccountAction>(this.data as u32) } toDeployContract(): DeployContractAction { assert(this.kind == ActionKind.DEPLOY_CONTRACT, 'ActionValue is not a \'DeployContract\'.') return changetype<DeployContractAction>(this.data as u32) } toFunctionCall(): FunctionCallAction { assert(this.kind == ActionKind.FUNCTION_CALL, 'ActionValue is not a \'FunctionCall\'.') return changetype<FunctionCallAction>(this.data as u32) } toTransfer(): TransferAction { assert(this.kind == ActionKind.TRANSFER, 'ActionValue is not a \'Transfer\'.') return changetype<TransferAction>(this.data as u32) } toStake(): StakeAction { assert(this.kind == ActionKind.STAKE, 'ActionValue is not a \'Stake\'.') return changetype<StakeAction>(this.data as u32) } toAddKey(): AddKeyAction { assert(this.kind == ActionKind.ADD_KEY, 'ActionValue is not a \'AddKey\'.') return changetype<AddKeyAction>(this.data as u32) } toDeleteKey(): DeleteKeyAction { assert(this.kind == ActionKind.DELETE_KEY, 'ActionValue is not a \'DeleteKey\'.') return changetype<DeleteKeyAction>(this.data as u32) } toDeleteAccount(): DeleteAccountAction { assert(this.kind == ActionKind.DELETE_ACCOUNT, 'ActionValue is not a \'DeleteAccount\'.') return changetype<DeleteAccountAction>(this.data as u32) } static fromCreateAccount(input: CreateAccountAction): ActionValue { return new ActionValue(ActionKind.CREATE_ACCOUNT, changetype<u32>(input)) } static fromDeployContract(input: DeployContractAction): ActionValue { return new ActionValue(ActionKind.DEPLOY_CONTRACT, changetype<u32>(input)) } static fromFunctionCall(input: FunctionCallAction): ActionValue { return new ActionValue(ActionKind.FUNCTION_CALL, changetype<u32>(input)) } static fromTransfer(input: TransferAction): ActionValue { return new ActionValue(ActionKind.TRANSFER, changetype<u32>(input)) } static fromStake(input: StakeAction): ActionValue { return new ActionValue(ActionKind.STAKE, changetype<u32>(input)) } static fromAddKey(input: AddKeyAction): ActionValue { return new ActionValue(ActionKind.ADD_KEY, changetype<u32>(input)) } static fromDeleteKey(input: DeleteKeyAction): ActionValue { return new ActionValue(ActionKind.DELETE_KEY, changetype<u32>(input)) } static fromDeleteAccount(input: DeleteAccountAction): ActionValue { return new ActionValue(ActionKind.DELETE_ACCOUNT, changetype<u32>(input)) } } // We don't map ReceiptData export class ActionReceipt { constructor( // Receipt fields public predecessorId: string, public receiverId: string, public id: CryptoHash, // ReceiptAction fields public signerId: string, public signerPublicKey: PublicKey, public gasPrice: BigInt, public outputDataReceivers: Array<DataReceiver>, public inputDataIds: Array<CryptoHash>, public actions: Array<ActionValue>, ) {} } export enum SuccessStatusKind { VALUE = 0, RECEIPT_ID = 1, } // Doesn't have Value suffix because it has // VALUE variant/kind, that would be confusing. export class SuccessStatus { constructor( public kind: SuccessStatusKind, public data: Payload, ) {} toValue(): Bytes { assert(this.kind == SuccessStatusKind.VALUE, 'SuccessStatus is not a \'Value\'.') return changetype<Bytes>(this.data as u32) } toReceiptId(): CryptoHash { assert(this.kind == SuccessStatusKind.RECEIPT_ID, 'SuccessStatus is not a \'ReceiptId\'.') return changetype<CryptoHash>(this.data as u32) } static fromValue(input: Bytes): SuccessStatus { return new SuccessStatus(SuccessStatusKind.VALUE, changetype<u32>(input)) } static fromReceiptId(input: CryptoHash): SuccessStatus { return new SuccessStatus(SuccessStatusKind.RECEIPT_ID, changetype<u32>(input)) } } export enum Direction { LEFT = 0, RIGHT = 1, } export class MerklePathItem { constructor( public hash: CryptoHash, public direction: Direction, ) {} @operator('<') lt(other: MerklePathItem): boolean { abort("Less than operator isn't supported in MerklePathItem") return false } @operator('>') gt(other: MerklePathItem): boolean { abort("Greater than operator isn't supported in MerklePathItem") return false } toString(): string { return `{hash: ${this.hash.toString()}}, direction: ${this.direction.toString()}` } } export class MerklePath extends Array<MerklePathItem> {} export class ExecutionOutcome { constructor( public gasBurnt: u64, public proof: MerklePath, public blockHash: CryptoHash, public id: CryptoHash, public logs: Array<string>, public receiptIds: Array<CryptoHash>, public tokensBurnt: BigInt, public executorId: string, public status: SuccessStatus, ) {} } export class SlashedValidator { constructor( public account: Account, public isDoubleSign: bool, ) {} } export class BlockHeader { constructor( public height: BlockHeight, public prevHeight: BlockHeight,// Always zero when version < V3 public blockOrdinal: NumBlocks,// Always zero when version < V3 public epochId: CryptoHash, public nextEpochId: CryptoHash, public chunksIncluded: u64, public hash: CryptoHash, public prevHash: CryptoHash, public timestampNanosec: u64, public prevStateRoot: CryptoHash, public chunkReceiptsRoot: CryptoHash, public chunkHeadersRoot: CryptoHash, public chunkTxRoot: CryptoHash, public outcomeRoot: CryptoHash, public challengesRoot: CryptoHash, public randomValue: CryptoHash, public validatorProposals: Array<ValidatorStake>, public chunkMask: Array<bool>, public gasPrice: Balance, public totalSupply: Balance, public challengesResult: Array<SlashedValidator>, public lastFinalBlock: CryptoHash, public lastDsFinalBlock: CryptoHash, public nextBpHash: CryptoHash, public blockMerkleRoot: CryptoHash, public epochSyncDataHash: CryptoHash,// Always empty when version < V3 public approvals: Array<Signature>,// Array<Option<Signature>> public signature: Signature, public latestProtocolVersion: ProtocolVersion, ) {} } export class ValidatorStake { constructor( public account: Account, public publicKey: PublicKey, public stake: Balance, ) {} } export class ChunkHeader { constructor( public encodedLength: u64, public gasUsed: Gas, public gasLimit: Gas, public shardId: ShardId, public heightCreated: BlockHeight, public heightIncluded: BlockHeight, public chunkHash: CryptoHash, public signature: Signature, public prevBlockHash: CryptoHash, public prevStateRoot: CryptoHash, public encodedMerkleRoot: CryptoHash, public balanceBurnt: Balance, public outgoingReceiptsRoot: CryptoHash, public txRoot: CryptoHash, public validatorProposals: Array<ValidatorStake>, ) {} } export class Block { constructor( public author: Account, public header: BlockHeader, public chunks: Array<ChunkHeader>, ) {} } export class ReceiptWithOutcome { constructor( public outcome: ExecutionOutcome, public receipt: ActionReceipt, public block: Block, ) {} } }
the_stack
import { Component, OnInit, OnDestroy } from '@angular/core'; import { environment } from './../../../../../environments/environment'; import { AssetGroupObservableService } from '../../../../core/services/asset-group-observable.service'; import { ActivatedRoute, Router } from '@angular/router'; import { Subscription } from 'rxjs/Subscription'; import { IssueListingService } from '../../../services/issue-listing.service'; import { UtilsService } from '../../../../shared/services/utils.service'; import { LoggerService } from '../../../../shared/services/logger.service'; import { ErrorHandlingService } from '../../../../shared/services/error-handling.service'; import 'rxjs/add/operator/filter'; import {RefactorFieldsService} from './../../../../shared/services/refactor-fields.service'; import {WorkflowService} from '../../../../core/services/workflow.service'; @Component({ selector: 'app-aws-notifications', templateUrl: './aws-notifications.component.html', styleUrls: ['./aws-notifications.component.css'], providers: [ IssueListingService, LoggerService, ErrorHandlingService ] }) export class AwsNotificationsComponent implements OnInit, OnDestroy { pageTitle = 'AWS Notifications'; issueListingdata: any; selectedAssetGroup: string; breadcrumbArray: any = ['Assets']; breadcrumbLinks: any = ['asset-dashboard']; breadcrumbPresent: any; outerArr: any = []; dataLoaded = false; errorMessage: any; showingArr: any = ['severity', 'owner', 'executionId']; allColumns: any = []; totalRows = 0; currentBucket: any = []; bucketNumber = 0; firstPaginator = 1; lastPaginator: number; currentPointer = 0; seekdata = false; showLoader = true; paginatorSize = 25; searchTxt = ''; filterTypeOptions: any = []; filterTagOptions: any = []; currentFilterType; filterTypeLabels = []; dataTableData: any = []; tableDataLoaded = false; filterTagLabels = []; filters: any = []; searchCriteria: any; filterText: any = {}; errorValue = 0; showGenericMessage = false; urlID = ''; public labels: any; FullQueryParams: any; private urlParams: any; queryParamsWithoutFilter: any; resourceId: string; resourceType: string; statuscode: string; public decodedResourceId: string; private assetGroupSubscription: Subscription; private routeSubscription: Subscription; private issueListingSubscription: Subscription; private querySubscription: Subscription; public pageLevel = 0; public backButtonRequired; constructor( private assetGroupObservableService: AssetGroupObservableService, private activatedRoute: ActivatedRoute, private issueListingService: IssueListingService, private router: Router, private utils: UtilsService, private logger: LoggerService, private errorHandling: ErrorHandlingService, private refactorFieldsService: RefactorFieldsService, private workflowService: WorkflowService ) { this.getRuleId(); this.assetGroupSubscription = this.assetGroupObservableService .getAssetGroup() .subscribe(assetGroupName => { this.backButtonRequired = this.workflowService.checkIfFlowExistsCurrently(this.pageLevel); this.selectedAssetGroup = assetGroupName; this.routerParam(); this.updateComponent(); this.deleteFilters(); this.getFilterArray(); }); } getRuleId() { /* * this funtion stores the URL params */ this.routeSubscription = this.activatedRoute.params.subscribe(params => { this.urlParams = params; // <<-- This urlParams is used while calling the api this.resourceId = this.urlParams.resourceId; this.decodedResourceId = decodeURIComponent(this.resourceId); this.resourceType = this.urlParams.resourceType; }); this.querySubscription = this.activatedRoute.queryParams.subscribe(queryParams => { this.statuscode = queryParams['statuscode']; }); } ngOnInit() { this.breadcrumbPresent = 'AWS Notifications'; // gets the current page url,which is used to come back to the same page after navigate } /* * This function gets the urlparameter and queryObj *based on that different apis are being hit with different queryparams */ routerParam() { try { // this.filterText saves the queryparam if (this.activatedRoute.snapshot.queryParams) { /** * FullQueryParams hold the entire queryobj(filter obj + the other obj) * queryParamsWithoutFilter holds only the part without the filter, * queryParamsWithoutFilter is used so that while deleting the filter we can append the remaining part * which is not part of filterobj(check in deleteFilters function) */ if (this.activatedRoute.snapshot.queryParams.filter !== '' && this.activatedRoute.snapshot.queryParams.filter !== undefined) { this.FullQueryParams = this.activatedRoute.snapshot.queryParams; this.queryParamsWithoutFilter = Object.keys(this.FullQueryParams).slice(1).map(key => ({[key]: this.FullQueryParams[key]})); const obj = {}; this.queryParamsWithoutFilter.forEach(element => { const localKeys = Object.keys(element); obj[localKeys[0]] = element[localKeys[0]]; }); this.queryParamsWithoutFilter = obj; } /** * The below code is added to get URLparameter and queryparameter * when the page loads ,only then this function runs and hits the api with the * filterText obj processed through processFilterObj function */ this.filterText = this.utils.processFilterObj(this.activatedRoute.snapshot.queryParams); } // this.urlID saves the urlparameter this.routeSubscription = this.activatedRoute.params.subscribe(params => { this.urlID = params['id']; }); } catch (error) { this.errorMessage = this.errorHandling.handleJavascriptError(error); this.logger.log('error', error); } } deleteFilters(event?) { try { if (!event) { this.filters = []; } else { if (event.clearAll) { this.filters = []; } else { this.filters.splice(event.index, 1); } this.filterText = this.utils.arrayToObject( this.filters, 'filterkey', 'value' ); // <-- TO update the queryparam which is passed in the filter of the api this.filterText = this.utils.makeFilterObj(this.filterText); /** * To change the url * with the deleted filter value along with the other existing paramter(ex-->tv:true) */ const updatedFilters = Object.assign(this.filterText , this.queryParamsWithoutFilter); this.router.navigate([], { relativeTo: this.activatedRoute, queryParams: updatedFilters }); /** * Finally after changing URL Link * api is again called with the updated filter */ this.filterText = this.utils.processFilterObj(this.filterText); this.updateComponent(); } } catch (error) {} /* TODO: Aditya: Why are we not calling any updateCompliance function in observable to update the filters */ } /* * this functin passes query params to filter component to show filter */ getFilterArray() { try { const localFilters = []; // <<-- this filter is used to store data for filter // let labelsKey = Object.keys(this.labels); const filterObjKeys = Object.keys(this.filterText); const dataArray = []; for (let i = 0; i < filterObjKeys.length; i++) { let obj = {}; obj = { 'name': filterObjKeys[i] }; dataArray.push(obj); } const filterValues = dataArray; const refactoredService = this.refactorFieldsService; const formattedFilters = dataArray.map(function(data){ data.name = refactoredService.getDisplayNameForAKey(data.name) || data.name; return data; }); for (let i = 0; i < formattedFilters.length; i++) { const eachObj = { key: formattedFilters[i].name, value: this.filterText[filterObjKeys[i]], filterkey: filterObjKeys[i] }; localFilters.push(eachObj); } this.filters = localFilters; } catch (error) { this.errorMessage = this.errorHandling.handleJavascriptError(error); this.logger.log('error', error); } } /** * This function get calls the keyword service before initializing * the filter array ,so that filter keynames are changed */ updateComponent() { this.outerArr = []; this.searchTxt = ''; this.currentBucket = []; this.bucketNumber = 0; this.firstPaginator = 1; this.dataTableData = []; this.tableDataLoaded = false; this.showLoader = true; this.currentPointer = 0; this.dataLoaded = false; this.seekdata = false; this.errorValue = 0; this.showGenericMessage = false; this.getData(); } navigateBack() { try { this.workflowService.goBackToLastOpenedPageAndUpdateLevel(this.router.routerState.snapshot.root); } catch (error) { this.logger.log('error', error); } /***********************************************************************************/ } getData() { try { let queryParams; if (this.issueListingSubscription) { this.issueListingSubscription.unsubscribe(); } queryParams = { filter: {'statuscode.keyword': this.statuscode}, from: this.bucketNumber * this.paginatorSize, searchtext: this.searchTxt, size: this.paginatorSize }; this.errorValue = 0; const url = environment.awsNotificationsDetails.url; const method = environment.awsNotificationsDetails.method; const newUrl = this.replaceUrl(url); this.issueListingSubscription = this.issueListingService .getData(queryParams, newUrl, method) .subscribe( response => { this.showGenericMessage = false; try { this.errorValue = 1; this.searchCriteria = undefined; this.tableDataLoaded = true; this.dataTableData = response[0]; const data = response[0]; this.showLoader = false; this.dataLoaded = true; if (response[0].length === 0) { this.errorValue = -1; this.outerArr = []; this.allColumns = []; } if (data.length > 0) { this.issueListingdata = data; this.seekdata = false; this.totalRows = data.total; if (response.hasOwnProperty('total')) { this.totalRows = response.total; } else { this.totalRows = response.length; } this.firstPaginator = this.bucketNumber * this.paginatorSize + 1; this.lastPaginator = this.bucketNumber * this.paginatorSize + this.paginatorSize; this.currentPointer = this.bucketNumber; if (this.lastPaginator > this.totalRows) { this.lastPaginator = this.totalRows; } // replace below this.issueListingdata to massaged data in case massage() is implemented this.currentBucket[this.bucketNumber] = this.issueListingdata; this.processData(this.issueListingdata); } } catch (e) { this.errorValue = 0; this.errorValue = -1; this.outerArr = []; this.dataLoaded = true; this.seekdata = true; this.errorMessage = this.errorHandling.handleJavascriptError(e); } }, error => { this.showGenericMessage = true; this.errorValue = -1; this.outerArr = []; this.dataLoaded = true; this.seekdata = true; this.errorMessage = 'apiResponseError'; } ); } catch (error) { this.showLoader = false; this.errorMessage = this.errorHandling.handleJavascriptError(error); this.logger.log('error', error); } } processData(data) { try { let innerArr = {}; const totalVariablesObj = {}; let cellObj = {}; this.outerArr = []; const getData = data; let getCols; if (getData.length) { getCols = Object.keys(getData[0]); } else { this.seekdata = true; } for (let row = 0; row < getData.length; row++) { innerArr = {}; for (let col = 0; col < getCols.length; col++) { cellObj = { link: '', properties: { color: '' }, colName: getCols[col], hasPreImg: false, imgLink: '', text: getData[row][getCols[col]], valText: getData[row][getCols[col]] }; innerArr[getCols[col]] = cellObj; totalVariablesObj[getCols[col]] = ''; } this.outerArr.push(innerArr); } if (this.outerArr.length > getData.length) { const halfLength = this.outerArr.length / 2; this.outerArr = this.outerArr.splice(halfLength); } this.allColumns = Object.keys(totalVariablesObj); } catch (error) { this.errorMessage = this.errorHandling.handleJavascriptError(error); this.logger.log('error', error); } } searchCalled(search) { this.searchTxt = search; } prevPg() { try { this.currentPointer--; this.processData(this.currentBucket[this.currentPointer]); this.firstPaginator = this.currentPointer * this.paginatorSize + 1; this.lastPaginator = this.currentPointer * this.paginatorSize + this.paginatorSize; } catch (error) { this.errorMessage = this.errorHandling.handleJavascriptError(error); this.logger.log('error', error); } } nextPg() { try { if (this.currentPointer < this.bucketNumber) { this.currentPointer++; this.processData(this.currentBucket[this.currentPointer]); this.firstPaginator = this.currentPointer * this.paginatorSize + 1; this.lastPaginator = this.currentPointer * this.paginatorSize + this.paginatorSize; if (this.lastPaginator > this.totalRows) { this.lastPaginator = this.totalRows; } } else { this.bucketNumber++; this.getData(); } } catch (error) { this.errorMessage = this.errorHandling.handleJavascriptError(error); this.logger.log('error', error); } } callNewSearch() { this.bucketNumber = 0; this.currentBucket = []; this.getData(); } replaceUrl(url) { let replacedUrl = url.replace('{resourceId}', this.resourceId.toString()); replacedUrl = replacedUrl.replace('{assetGroup}', this.selectedAssetGroup.toString()); replacedUrl = replacedUrl.replace('{resourceType}', this.resourceType.toString()); return replacedUrl; } ngOnDestroy() { try { if (this.assetGroupSubscription) { this.assetGroupSubscription.unsubscribe(); } if (this.routeSubscription) { this.routeSubscription.unsubscribe(); } if (this.issueListingSubscription) { this.issueListingSubscription.unsubscribe(); } } catch (error) { this.logger.log('error', '--- Error while unsubscribing ---'); } } }
the_stack
import BigNumber from 'bignumber.js' import { SmartBuffer } from 'smart-buffer' import { readVarUInt, writeVarUInt } from './varuint' import { getBitsFrom } from './bitmask' import { MAX_INT64, ONE_HUNDRED_MILLION, readBigNumberUInt64, writeBigNumberUInt64 } from './bignumber' export interface BufferComposer { fromBuffer: (buffer: SmartBuffer) => void toBuffer: (buffer: SmartBuffer) => void } /** * A highly composable buffer, by defining a list of composer, it allows bi-directional buffer to object serialization. * In short, you compose from a Buffer to Object or an Object to a Buffer. Little endian by design. * * It is also deeply recursive by default allow cascading object composing. */ export abstract class ComposableBuffer<T> implements BufferComposer { protected readonly data: T abstract composers (data: T): BufferComposer[] /** * @param data to create ComposableBuffer holder, nothing is done/composed yet. */ constructor (data: T) /** * @param {SmartBuffer} buffer to compose into Object */ constructor (buffer: SmartBuffer) /** * For typescript type checking */ constructor (data: SmartBuffer | T) constructor (data: SmartBuffer | T) { if (data instanceof SmartBuffer) { // @ts-expect-error as data will be mapped by fromBuffer() this.data = {} this.fromBuffer(data) } else { this.data = data } } fromBuffer (buffer: SmartBuffer): void { for (const mapping of this.composers(this.data)) { mapping.fromBuffer(buffer) } } toBuffer (buffer: SmartBuffer): void { for (const mapping of this.composers(this.data)) { mapping.toBuffer(buffer) } } toHex (): string { const buffer: SmartBuffer = new SmartBuffer() this.toBuffer(buffer) return buffer.toString('hex') } /** * Deeply toObject() mapper. * This unwrap the data in ComposableBuffer and convert all ComposableBuffer into their raw object. * This make it compatible to convert into JSON with JSON.stringify() * @return {Object} */ toObject (): any { function toObject (value: any): any { if (value instanceof ComposableBuffer) { return value.toObject() } if (Array.isArray(value) && value.length > 0) { return value.map(v => toObject(v)) } return value } const json: any = {} for (const [key, value] of Object.entries(this.data)) { json[key] = toObject(value) } return json } /** * @return BufferComposer that does nothing */ static empty (): BufferComposer { return { fromBuffer (_: SmartBuffer): void { }, toBuffer (_: SmartBuffer): void { } } } /** * The length of the array is set with VarUInt in the first sequence of 1 - 9 bytes. * * @param getter to read array of ComposableBuffer Object from to buffer * @param setter to set array of ComposableBuffer Object from buffer * @param asC map single object into ComposableBuffer Object * * @see array if length is not given but known */ static varUIntArray<T> ( getter: () => T[], setter: (data: T[]) => void, asC: (data: SmartBuffer | T) => ComposableBuffer<T> ): BufferComposer { return { fromBuffer: (buffer: SmartBuffer): void => { const length = readVarUInt(buffer) const array: T[] = [] for (let i = 0; i < length; i++) { array.push(asC(buffer).data) } setter(array) }, toBuffer: (buffer: SmartBuffer): void => { const array = getter() writeVarUInt(array.length, buffer) array.forEach(data => asC(data).toBuffer(buffer)) } } } /** * The length of the array must be known and given to the composer, use varUIntArray if length is set as VarUInt. * * @param getter to read array of ComposableBuffer Object from to buffer * @param setter to set array of ComposableBuffer Object from buffer * @param asC map single object into ComposableBuffer Object * @param getLength of the array * * @see use varUIntArray if length is set as VarUInt */ static array<T> ( getter: () => T[], setter: (data: T[]) => void, asC: (data: SmartBuffer | T) => ComposableBuffer<T>, getLength: () => number ): BufferComposer { return { fromBuffer: (buffer: SmartBuffer): void => { const array: T[] = [] for (let i = 0; i < getLength(); i++) { array.push(asC(buffer).data) } setter(array) }, toBuffer: (buffer: SmartBuffer): void => { const array = getter() array.forEach(data => asC(data).toBuffer(buffer)) } } } /** * The length depends on the Composable buffer composer configuration * * @param getter to read single ComposableBuffer Object from to buffer * @param setter to set single ComposableBuffer Object from buffer * @param asC map object into ComposableBuffer Object */ static single<T> ( getter: () => T, setter: (data: T) => void, asC: (data: SmartBuffer | T) => ComposableBuffer<T> ): BufferComposer { return { fromBuffer: (buffer: SmartBuffer): void => { setter(asC(buffer).data) }, toBuffer: (buffer: SmartBuffer): void => { asC(getter()).toBuffer(buffer) } } } /** * HEX String with length specified, encoded into Buffer as the same order of the Hex String. * In short this read a hex and push it into the Buffer. It will not re-order the endian. * * @param length of the bytes to read/set * @param getter to read HEX String and write as the same ordered Buffer * @param setter to read ordered Buffer and set as the same ordered HEX String * @throws Error if length != getter().length in set */ static hex (length: number, getter: () => string, setter: (data: string) => void): BufferComposer { return { fromBuffer: (buffer: SmartBuffer): void => { const buff = Buffer.from(buffer.readBuffer(length)) setter(buff.toString('hex')) }, toBuffer: (buffer: SmartBuffer): void => { const hex = getter() if (hex.length !== length * 2) { throw new Error('ComposableBuffer.hex.toBuffer invalid as length != getter().length') } const buff: Buffer = Buffer.from(hex, 'hex') buffer.writeBuffer(buff) } } } /** * HEX String with length specified, encoded into Buffer as the same order of the Hex String. * In short this read a hex and push it into the Buffer. It will not re-order the endian. * * When hex is `undefined` it will write `0x00` signifying zero byte length. * * @param getter to read HEX String. Writes its length then write the HEX string. Defaults to empty string. * @param setter to read ordered Buffer and set as the same ordered HEX String */ static varUIntOptionalHex (getter: () => string | undefined, setter: (data: string | undefined) => void): BufferComposer { return { fromBuffer: (buffer: SmartBuffer): void => { const length = readVarUInt(buffer) if (length > 0) { const buff = Buffer.from(buffer.readBuffer(length)) setter(buff.toString('hex')) } }, toBuffer: (buffer: SmartBuffer): void => { const hex = getter() if (hex !== undefined) { if (hex === '') { throw new Error('ComposableBuffer.varUIntOptionalHex.toBuffer attempting to write empty buffer') } const buff: Buffer = Buffer.from(hex, 'hex') writeVarUInt(buff.length, buffer) buffer.writeBuffer(buff) } else { writeVarUInt(0x00, buffer) } } } } /** * Same behavior with `hex` when the field is defined * `toBuffer` resulted empty SmartBuffer * * @param length of the bytes to read/set * @param getter to read HEX String and write as the same ordered Buffer * @param setter to read ordered Buffer and set as the same ordered HEX String * @throws Error if getter() is defined && length != getter().length in set */ static optionalHex (length: number, getter: () => string | undefined, setter: (data: string | undefined) => void): BufferComposer { return { fromBuffer: (buffer: SmartBuffer): void => { const buff = Buffer.from(buffer.readBuffer(length)) if (buff.length > 0) { setter(buff.toString('hex')) } }, toBuffer: (buffer: SmartBuffer): void => { const hex = getter() if (hex === undefined) { return } if (hex.length !== length * 2) { throw new Error('ComposableBuffer.optionalHex.toBuffer invalid as length != getter().length') } buffer.writeBuffer(Buffer.from(hex, 'hex')) } } } /** * BE ordered HEX String with length specified, encoded in LE order buffer. * Different from BufferComposer.hex, this will reorder the Buffer from LE to BE and BE to LE. * * @param length of the bytes to read/set * @param getter to read BE ordered HEX String and write as LE ordered Buffer * @param setter to read LE ordered Buffer and set as BE ordered HEX String * @throws Error if length != getter().length in set */ static hexBEBufferLE (length: number, getter: () => string, setter: (data: string) => void): BufferComposer { return { fromBuffer: (buffer: SmartBuffer): void => { const buff = Buffer.from(buffer.readBuffer(length)).reverse() setter(buff.toString('hex')) }, toBuffer: (buffer: SmartBuffer): void => { const hex = getter() if (hex.length !== length * 2) { throw new Error('ComposableBuffer.hexBEBufferLE.toBuffer invalid as length != getter().length') } const buff: Buffer = Buffer.from(hex, 'hex').reverse() buffer.writeBuffer(buff) } } } /** * UTF-8 string with length specified, encoded in LE order buffer. * String is always BE, as Javascript is uses BE by default. * * @param length of the bytes to read/set * @param getter to read BE ordered String and write as LE ordered Buffer * @param setter to read LE ordered Buffer and set as BE ordered String * @throws Error if length != getter().length in set */ static utf8LE (length: number, getter: () => string, setter: (data: string) => void): BufferComposer { return { fromBuffer: (buffer: SmartBuffer): void => { const buff = Buffer.from(buffer.readBuffer(length)).reverse() setter(buff.toString('utf-8')) }, toBuffer: (buffer: SmartBuffer): void => { const buff: Buffer = Buffer.from(getter(), 'utf-8').reverse() if (buff.length !== length) { throw new Error('ComposableBuffer.utf8LE.toBuffer invalid as length != getter().length') } buffer.writeBuffer(buff) } } } /** * UTF-8 string with length specified, encoded in BE order buffer. * String is always BE, as Javascript is uses BE by default. * * @param length of the bytes to read/set * @param getter to read BE ordered String and write as BE ordered Buffer * @param setter to read BE ordered Buffer and set as BE ordered String * @throws Error if length != getter().length in set */ static utf8BE (length: number, getter: () => string, setter: (data: string) => void): BufferComposer { return { fromBuffer: (buffer: SmartBuffer): void => { const buff = Buffer.from(buffer.readBuffer(length)) setter(buff.toString('utf-8')) }, toBuffer: (buffer: SmartBuffer): void => { const buff: Buffer = Buffer.from(getter(), 'utf-8') if (buff.length !== length) { throw new Error('ComposableBuffer.utf8BE.toBuffer invalid as length != getter().length') } buffer.writeBuffer(buff) } } } /** * VarUInt sized UTF-8 string, encoded in LE order buffer. * String is always BE, as Javascript is uses BE by default. * * @param getter to read BE ordered String and write as LE ordered Buffer * @param setter to read LE ordered Buffer and set as BE ordered String */ static varUIntUtf8LE (getter: () => string, setter: (data: string) => void): BufferComposer { return { fromBuffer: (buffer: SmartBuffer): void => { const length = readVarUInt(buffer) const buff = Buffer.from(buffer.readBuffer(length)).reverse() setter(buff.toString('utf-8')) }, toBuffer: (buffer: SmartBuffer): void => { const buff: Buffer = Buffer.from(getter(), 'utf-8').reverse() writeVarUInt(buff.length, buffer) buffer.writeBuffer(buff) } } } /** * VarUInt sized UTF-8 string, encoded in BE order buffer. * String is always BE, as Javascript is uses BE by default. * * @param getter to read BE ordered String and write as BE ordered Buffer * @param setter to read BE ordered Buffer and set as BE ordered String */ static varUIntUtf8BE (getter: () => string, setter: (data: string) => void): BufferComposer { return { fromBuffer: (buffer: SmartBuffer): void => { const length = readVarUInt(buffer) const buff = Buffer.from(buffer.readBuffer(length)) setter(buff.toString('utf-8')) }, toBuffer: (buffer: SmartBuffer): void => { const buff: Buffer = Buffer.from(getter(), 'utf-8') writeVarUInt(buff.length, buffer) buffer.writeBuffer(buff) } } } /** * VarUInt sized hex string, encoded into Buffer as the same order of the hex String. * In short this read a VarUInt sized hex and push it into the Buffer. It will not re-order the endian. * * @param getter to read hex String and write as the same ordered Buffer * @param setter to read ordered Buffer and set as the same ordered hex String */ static varUIntHex (getter: () => string, setter: (data: string) => void): BufferComposer { return { fromBuffer: (buffer: SmartBuffer): void => { const length = readVarUInt(buffer) const buff = Buffer.from(buffer.readBuffer(length)) setter(buff.toString('hex')) }, toBuffer: (buffer: SmartBuffer): void => { const buff: Buffer = Buffer.from(getter(), 'hex') writeVarUInt(buff.length, buffer) buffer.writeBuffer(buff) } } } /** * Unsigned Int8, 1 byte * * @param getter to read from to buffer * @param setter to set to from buffer */ static uInt8 (getter: () => number, setter: (data: number) => any): BufferComposer { return { fromBuffer: (buffer: SmartBuffer): void => { setter(buffer.readUInt8()) }, toBuffer: (buffer: SmartBuffer): void => { buffer.writeUInt8(getter()) } } } /** * Unsigned Int16, 2 bytes * * @param getter to read from to buffer * @param setter to set to from buffer */ static uInt16 (getter: () => number, setter: (data: number) => void): BufferComposer { return { fromBuffer: (buffer: SmartBuffer): void => { setter(buffer.readUInt16LE()) }, toBuffer: (buffer: SmartBuffer): void => { buffer.writeUInt16LE(getter()) } } } /** * Signed Int32, 4 bytes * * @param getter to read from to buffer * @param setter to set to from buffer */ static int32 (getter: () => number, setter: (data: number) => void): BufferComposer { return { fromBuffer: (buffer: SmartBuffer): void => { setter(buffer.readInt32LE()) }, toBuffer: (buffer: SmartBuffer): void => { buffer.writeInt32LE(getter()) } } } /** * Unsigned Int32, 4 bytes * * @param getter to read from to buffer * @param setter to set to from buffer */ static uInt32 (getter: () => number, setter: (data: number) => void): BufferComposer { return { fromBuffer: (buffer: SmartBuffer): void => { setter(buffer.readUInt32LE()) }, toBuffer: (buffer: SmartBuffer): void => { buffer.writeUInt32LE(getter()) } } } /** * Unsigned BigNumber, 8 bytes * * @param getter to read from to buffer * @param setter to set to from buffer */ static bigNumberUInt64 (getter: () => BigNumber, setter: (data: BigNumber) => void): BufferComposer { return { fromBuffer: (buffer: SmartBuffer): void => { setter(readBigNumberUInt64(buffer)) }, toBuffer: (buffer: SmartBuffer): void => { writeBigNumberUInt64(getter(), buffer) } } } /** * Unsigned satoshi as BigNumber, 8 bytes * BigNumber is multiplied/divided by 100,000,000 * * @param getter to read from to buffer * @param setter to set to from buffer */ static satoshiAsBigNumber (getter: () => BigNumber, setter: (data: BigNumber) => void): BufferComposer { return ComposableBuffer.bigNumberUInt64(() => { return getter().multipliedBy(ONE_HUNDRED_MILLION) }, v => { setter(v.dividedBy(ONE_HUNDRED_MILLION)) }) } /** * VarUInt helper method, 1 - 9 bytes * * @param getter to read from to buffer * @param setter to set to from buffer */ static varUInt (getter: () => number, setter: (data: number) => void): BufferComposer { return { fromBuffer: (buffer: SmartBuffer): void => { setter(readVarUInt(buffer)) }, toBuffer: (buffer: SmartBuffer): void => { writeVarUInt(getter(), buffer) } } } /** * Imposing mask over bits method, 1 byte * * @param length of the input array to read/set * @param getter to read from to buffer * @param setter to set to from buffer */ static bitmask1Byte ( length: number, getter: () => boolean[], setter: (data: boolean[]) => void ): BufferComposer { return { fromBuffer: (buffer: SmartBuffer): void => { const num = buffer.readUInt8() const array: boolean[] = [] for (let i = 0; i < length; i += 1) { array.unshift(getBitsFrom(num, i)) } setter(array) }, toBuffer: (buffer: SmartBuffer): void => { const bools = getter().map(bool => bool.toString().toLowerCase() === 'true' ? 1 : 0) const num = parseInt(bools.join(''), 2) buffer.writeBuffer(Buffer.from([num])) } } } /** * Unsigned Boolean 1 byte, 1 = true, 0 = false * * @param getter to read from to buffer * @param setter to set to from buffer */ static uBool8 (getter: () => boolean, setter: (data: boolean) => void): BufferComposer { return { fromBuffer: (buffer: SmartBuffer): void => { setter(buffer.readUInt8() === 1) }, toBuffer: (buffer: SmartBuffer): void => { const v = getter() ? 1 : 0 buffer.writeBuffer(Buffer.from([v])) } } } /** * Unsigned Boolean 4 bytes, 1 = true, 0 = false * * @param getter to read from to buffer * @param setter to set to from buffer */ static uBool32 (getter: () => boolean, setter: (data: boolean) => void): BufferComposer { return { fromBuffer: (buffer: SmartBuffer): void => { setter(buffer.readInt32BE() === 1) }, toBuffer: (buffer: SmartBuffer): void => { const v = getter() ? 1 : 0 buffer.writeBuffer(Buffer.from([0, 0, 0, v])) } } } /** * maxPrice as BigNumber, first 8 bytes for integer, last 8 bytes for fraction * * @param getter to read from to buffer * @param setter to set to from buffer */ static maxPriceAsBigNumber (getter: () => BigNumber, setter: (data: BigNumber) => void): BufferComposer { return { fromBuffer: (buffer: SmartBuffer): void => { const integer = readBigNumberUInt64(buffer) const fraction = readBigNumberUInt64(buffer) // Disabled as it's not enforced // NOTE(canonbrother): max price default value is max int64 (9223372036854775807) // https://github.com/DeFiCh/ain/blob/aed00d09075094a3a0cedebde5248c006216ba09/src/masternodes/rpc_poolpair.cpp#L115-L123 // if (fraction.gt(new BigNumber('99999999')) && !fraction.eq(MAX_INT64)) { // throw new Error('Too many decimals read from buffer. Will lose precision with more than 8 decimals') // } if (integer.eq(MAX_INT64) && fraction.eq(MAX_INT64)) { setter(MAX_INT64) } else { setter(integer.plus(fraction.dividedBy(ONE_HUNDRED_MILLION))) } }, toBuffer: (buffer: SmartBuffer): void => { const maxPrice = getter() if (maxPrice.decimalPlaces() > 8) { throw new Error('Too many decimals to be correctly represented. Will lose precision with more than 8 decimals') } if (maxPrice.eq(MAX_INT64)) { writeBigNumberUInt64(MAX_INT64, buffer) writeBigNumberUInt64(MAX_INT64, buffer) } else { const n = maxPrice.multipliedBy(ONE_HUNDRED_MILLION) const fraction = n.mod(ONE_HUNDRED_MILLION) const integer = n.minus(fraction).dividedBy(ONE_HUNDRED_MILLION) writeBigNumberUInt64(integer, buffer) writeBigNumberUInt64(fraction, buffer) } } } } }
the_stack
import { getOffsetSecondsFromTimezoneString, getTimezoneOffsetFromSeconds } from '../util/DateTimeUtil'; /** * ### Local time object * * Represents time in day without timezone. */ export class LocalTime { private static readonly timeStringRegex = /(\d\d):(\d\d):(\d\d)(\.\d+)?/; /** * @param hour The hour-of-day to represent, from 0 to 23 * @param minute The minute-of-hour to represent, from 0 to 59 * @param second The second-of-minute to represent, from 0 to 59 * @param nano The nano-of-second to represent, from 0 to 999,999,999 * @throws TypeError if any of the arguments are invalid * @throws RangeError if value of any of the arguments are invalid */ constructor(readonly hour: number, readonly minute: number, readonly second: number, readonly nano: number) { if (typeof hour !== 'number' || typeof minute !== 'number' || typeof second !== 'number' || typeof nano !== 'number') { throw new TypeError('Illegal arguments given to LocalTime. All arguments must be numbers.'); } if (!Number.isInteger(hour) || !Number.isInteger(minute) || !Number.isInteger(second) || !Number.isInteger(nano)) { throw new RangeError('Illegal arguments given to LocalTime. All arguments must be integers.'); } if (!(hour >= 0 && hour <= 23)) { throw new RangeError('Hour-of-day must be between 0-23'); } if (!(minute >= 0 && minute <= 59)) { throw new RangeError('Minute-of-hour must be between 0-59'); } if (!(second >= 0 && second <= 59)) { throw new RangeError('Second-of-minute must be between 0-59'); } if (!(nano >= 0 && nano <= 999_999_999)) { throw new RangeError('Nano-of-second must be between 0-999_999_999'); } } /** * Constructs a new {@link LocalTime} object from timeString. * @param timeString A string in the form HH:mm:ss.SSS, where the last part represents nanoseconds and optional. * At most 9 digits allowed for nanosecond value. If more than 9 digits are given, the first 9 of them are used. * @throws RangeError if given timeString is invalid * @throws TypeError if given argument is not string */ static fromString(timeString: string): LocalTime { if (typeof timeString !== 'string') { throw new TypeError('String expected.'); } const match = timeString.match(LocalTime.timeStringRegex); if (!match) { throw new RangeError('Illegal time string. Expected a string in HH:mm:ss.SSS format'); } const hours = +match[1]; const minutes = +match[2]; const seconds = +match[3]; let nano = 0; if (match[4] !== undefined) { // nano second included let nanoStr = match[4].substring(1, 10); // does not include first dot nanoStr = nanoStr.padEnd(9, '0'); nano = +nanoStr; } if (isNaN(hours) || isNaN(minutes) || isNaN(seconds) || isNaN(nano)) { throw new RangeError('Illegal time string. Expected a string in HH:mm:ss.SSS format'); } return new LocalTime(hours, minutes, seconds, nano); } /** * Returns the string representation of this local time. * * @returns A string in the form HH:mm:ss.SSS (9 digits, nano second precision). The constructed string is * zero-padded from left. If nanosecond is 0, it is not included in the constructed string. */ toString(): string { const hour = this.hour.toString().padStart(2, '0'); const minute = this.minute.toString().padStart(2, '0'); const second = this.second.toString().padStart(2, '0'); let hourMinuteSecondString = `${hour}:${minute}:${second}`; // Do not add .000000000 if nano is 0 if (this.nano !== 0) { hourMinuteSecondString += `.${this.nano.toString().padStart(9, '0')}`; } return hourMinuteSecondString; } } /** * Months for LocalDate * @internal */ enum Months { January = 1, February, March, April, May, June, July, August, September, October, November, December } /** * ### Local date object * * Represents date in year without timezone. */ export class LocalDate { private static readonly dateRegex = /(-?\d+)-(\d\d)-(\d\d)/; /** * @param year Must be between -999999999-999999999 * @param month Must be between 1-12 * @param date Must be between 1-31 depending on year and month * @throws RangeError if value of any of the arguments are invalid, or the date formed by them is invalid (e.g 02/29/2021) * @throws TypeError if any of the arguments are of wrong type */ constructor(readonly year: number, readonly month: number, readonly date: number) { if (typeof year !== 'number' || typeof month !== 'number' || typeof date !== 'number') { throw new TypeError('Illegal arguments given to LocalTime. All arguments must be numbers.'); } if (!Number.isInteger(year) || !Number.isInteger(month) || !Number.isInteger(date)) { throw new RangeError('Illegal arguments given to LocalTime. All arguments must be integers.'); } if (!(month >= 1 && month <= 12)) { throw new RangeError('Month must be between 1-12'); } if (!(year >= -999_999_999 && year <= 999_999_999)) { throw new RangeError('Year must be between -999_999_999 - 999_999_999'); } if (date < 1) { throw new RangeError('Invalid Date. Date cannot be less than 1'); } if (date > 28) { let maxDate = 31; switch (month) { case 2: maxDate = LocalDate.isLeapYear(this.year) ? 29 : 28; break; case 4: maxDate = 30; break; case 6: maxDate = 30; break; case 9: maxDate = 30; break; case 11: maxDate = 30; break; } if (date > maxDate) { if (date == 29) { throw new RangeError(`Invalid Date. February 29 as ${this.year} is not a leap year`); } throw new RangeError(`Invalid Date. ${Months[this.month]} ${this.date}`); } } } /** * @internal * Implementation is taken from java IsoChronology.isLeapYear() * @param year Year value */ private static isLeapYear(year: number): boolean { return (year & 3) == 0 && (year % 100 != 0 || year % 400 == 0); } /** * Constructs a {@link LocalDate} object from string. * @param dateString String in the form of yyyy-mm-dd * @throws TypeError if a string is not passed * @throws RangeError if the string format is wrong */ static fromString(dateString: string): LocalDate { if (typeof dateString !== 'string') { throw new TypeError('String expected.'); } const match = dateString.match(LocalDate.dateRegex); if (!match) { throw new RangeError('Invalid format. Expected a string in yyyy-mm-dd format'); } const yearNumber = +match[1]; const monthNumber = +match[2]; const dateNumber = +match[3]; if (isNaN(yearNumber) || isNaN(monthNumber) || isNaN(dateNumber)) { throw new RangeError('Invalid format. Expected a string in yyyy-mm-dd format'); } return new LocalDate(yearNumber, monthNumber, dateNumber); } /** * Returns the string representation of this local date. * @returns A string in the form yyyy:mm:dd. Values are zero padded from left */ toString(): string { const sign = this.year < 0 ? '-' : ''; const paddedYear = Math.abs(this.year).toString().padStart(4, '0'); const month = this.month.toString().padStart(2, '0'); const date = this.date.toString().padStart(2, '0'); return `${sign}${paddedYear}-${month}-${date}`; } } /** * ### Local datetime object * * Represents date and time without timezone. */ export class LocalDateTime { private static separatorRegex = /[Tt]/; /** * @param localDate a {@link LocalDate} object * @param localTime a {@link LocalTime} object * @throws TypeError if passed arguments are of wrong type */ constructor(readonly localDate: LocalDate, readonly localTime: LocalTime) { if (!(localDate instanceof LocalDate)) { throw new TypeError('Invalid local date.'); } if (!(localTime instanceof LocalTime)) { throw new TypeError('Invalid local time.'); } } /** * Constructs LocalDateTime from ISO 8601 string. * @param isoString Must not include timezone information. The string format is yyyy-mm-ss(T|t)HH:mm:ss.SSS. The last SSS * part represents nanoseconds and can be omitted. * @throws RangeError if ISO string is invalid or any of the values in ISO string is invalid * @throws TypeError if the value is not a string */ static fromString(isoString: string): LocalDateTime { if (typeof isoString !== 'string') { throw new TypeError('String expected.'); } const split = isoString.split(LocalDateTime.separatorRegex); if (split.length !== 2) { throw new RangeError('Invalid format. Expected a string in the form yyyy-mm-ss(T|t)HH:mm:ss.SSS'); } return new LocalDateTime(LocalDate.fromString(split[0]), LocalTime.fromString(split[1])); } /** * Returns this LocalDataTime as Date. */ asDate(): Date { return new Date( Date.UTC( this.localDate.year, this.localDate.month - 1, // month start with 0 in Date this.localDate.date, this.localTime.hour, this.localTime.minute, this.localTime.second, Math.floor(this.localTime.nano / 1_000_000) ) ); } /** * Constructs a new instance from Date. * @param date Must be a valid Date. So `date.getTime()` should be not NaN * @throws TypeError if the passed param is not a Date * @throws RangeError if an invalid Date is passed */ static fromDate(date: Date): LocalDateTime { if (!(date instanceof Date)) { throw new TypeError('A Date is not passed'); } if (isNaN(date.getTime())) { throw new RangeError('Invalid Date is passed.'); } return LocalDateTime.from( date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds() * 1_000_000 ); } /** * Static constructor for convenient construction. * * @param year Must be between -999999999-999999999 * @param month Must be between 1-12 * @param date Must be between 1-31 depending on year and month * @param hour The hour-of-day to represent, from 0 to 23 * @param minute The minute-of-hour to represent, from 0 to 59 * @param second The second-of-minute to represent, from 0 to 59 * @param nano The nano-of-second to represent, from 0 to 999,999,999 * @throws TypeError if passed arguments are of wrong type * @throws RangeError if value of any of the arguments are invalid */ static from( year: number, month: number, date: number, hour: number, minute: number, second: number, nano: number ): LocalDateTime { return new LocalDateTime( new LocalDate(year, month, date), new LocalTime(hour, minute, second, nano) ); } /** * Returns the string representation of this local datetime. * @returns A string in the form yyyy:mm:ddTHH:mm:ss.SSS. Values are zero padded from left. If nano second value * is zero, second decimal is not include in the returned string */ toString(): string { return `${this.localDate.toString()}T${this.localTime.toString()}`; } } /** * ### Offset datetime object * * Represents date and time with timezone. * * Timezone is specified with offset from UTC in seconds. This offset can be negative or positive. * * This class internally stores a {@link LocalDateTime} and offset number. */ export class OffsetDateTime { private static readonly timezoneRegex = /([Zz]|[+-]\d\d:\d\d)/; /** * @param localDateTime {@link LocalDateTime} object * @param offsetSeconds timezone offset in seconds. Must be in [-64800, 64800] range. * @throws TypeError if type of arguments are invalid */ constructor(readonly localDateTime: LocalDateTime, readonly offsetSeconds: number) { if (!(localDateTime instanceof LocalDateTime)) { throw new TypeError('Invalid local datetime'); } if (typeof offsetSeconds !== 'number') { throw new TypeError('offsetSeconds is not a number.'); } if (!Number.isInteger(offsetSeconds) || !(offsetSeconds >= -64800 && offsetSeconds <= 64800)) { throw new RangeError('Offset seconds can be between -64800(-18:00) and 64800(+18:00).'); } } /** * Constructs a new instance from Date and offset seconds. * @param date Must be a valid Date. So `date.getTime()` should be not NaN * @param offsetSeconds Offset in seconds, must be between [-64800, 64800] * @throws TypeError if a wrong type is passed as argument * @throws RangeError if an invalid argument value is passed */ static fromDate(date: Date, offsetSeconds: number): OffsetDateTime { if (!(date instanceof Date)) { throw new TypeError('A Date is not passed'); } if (typeof offsetSeconds !== 'number') { throw new TypeError('offsetSeconds is not a number'); } if (isNaN(date.getTime())) { throw new RangeError('Invalid Date is passed.'); } if (!Number.isInteger(offsetSeconds) || !(offsetSeconds >= -64800 && offsetSeconds <= 64800)) { throw new RangeError('Offset seconds can be between -64800(-18:00) and 64800(+18:00).'); } return new OffsetDateTime(LocalDateTime.fromDate(date), offsetSeconds); } /** * Constructs a new instance from ISO 8601 string. The string format is yyyy-mm-ddTHH-mm-ss.SSS(Z | (+|-)HH:mm). * @param isoString ISO 8601 string with timezone. If timezone is omitted, UTC is assumed * @throws TypeError if passed value is not a string * @throws RangeError if passed string is invalid */ static fromString(isoString: string): OffsetDateTime { if (typeof isoString !== 'string') { throw new TypeError('String expected'); } const indexOfFirstMatch = isoString.search(OffsetDateTime.timezoneRegex); const split = isoString.split(isoString[indexOfFirstMatch]); let offsetSeconds; if (split.length !== 2) { throw new RangeError('Invalid format'); } if (indexOfFirstMatch === -1) { offsetSeconds = 0; } else { offsetSeconds = getOffsetSecondsFromTimezoneString(isoString[indexOfFirstMatch] + split[1]); } return new OffsetDateTime(LocalDateTime.fromString(split[0]), offsetSeconds); } /** * Returns this offset datetime as Date. Note that the timezone information is not stored in Date objects and you * effectively get a timestamp.(an instance in time without timezone) */ asDate(): Date { return new Date(this.localDateTime.asDate().getTime() - this.offsetSeconds * 1000); } /** * Static constructor for convenient construction. * * @param year Must be between -999999999-999999999 * @param month Must be between 1-12 * @param date Must be between 1-31 depending on year and month * @param hour The hour-of-day to represent, from 0 to 23 * @param minute The minute-of-hour to represent, from 0 to 59 * @param second The second-of-minute to represent, from 0 to 59 * @param nano The nano-of-second to represent, from 0 to 999,999,999 * @param offsetSeconds timezone offset in seconds. Must be in [-64800, 64800] range. * @throws TypeError if passed arguments are of wrong type * @throws RangeError if value of any of the arguments are invalid */ static from( year: number, month: number, date: number, hour: number, minute: number, second: number, nano: number, offsetSeconds: number ): OffsetDateTime { return new OffsetDateTime( LocalDateTime.from(year, month, date, hour, minute, second, nano), offsetSeconds ); } /** * Returns ISO 8601 string with timezone of this instance. * @returns A string in the format yyyy-mm-ddTHH-mm-ss.SSS(Z | (+|-)HH:mm) * Timezone is denoted either with `Z` or timezone string like +-HH:mm */ toString(): string { const timezoneOffsetString = getTimezoneOffsetFromSeconds(this.offsetSeconds); return this.localDateTime.toString() + timezoneOffsetString; } }
the_stack
declare module '@emp-antd/base/App' { /// <reference types="react" /> import '@emp-antd/base/index.scss' import '@emp-antd/base/App.scss' import {RouterCompType} from '@emp-antd/base/types' const App: ({layout, routes, stores}: RouterCompType) => JSX.Element export default App } declare module '@emp-antd/base/bootstrap' { export {} } declare module '@emp-antd/base/components/common/BreadcrumbComp' { /// <reference types="react" /> import {RoutesType} from '@emp-antd/base/types' export const BreadcrumbComp: ({routers}: {routers?: RoutesType[] | undefined}) => JSX.Element } declare module '@emp-antd/base/components/common/HeaderUserProfile' { import React from 'react' import './HeaderUserProfile.less' export const HeaderUserProfile: React.FunctionComponent<any> } declare module '@emp-antd/base/components/common/LoadingComp' { /// <reference types="react" /> import './LoadingCompStyle.less' const LoadingComp: () => JSX.Element export default LoadingComp } declare module '@emp-antd/base/components/common/P403Comp' { /// <reference types="react" /> const P403Comp: () => JSX.Element export default P403Comp } declare module '@emp-antd/base/components/common/P404Comp' { /// <reference types="react" /> const P404Comp: () => JSX.Element export default P404Comp } declare module '@emp-antd/base/components/common/RouterComp' { /// <reference types="react" /> import {RoutesType, RouterCompType} from '@emp-antd/base/types' export default function RouterComp(props: RouterCompType): JSX.Element export const SwitchRouter: ({routes}: {routes?: RoutesType[] | undefined}) => JSX.Element } declare module '@emp-antd/base/components/common/crud/CrudComponent' { /// <reference types="react" /> import {PageListProps} from '@emp-antd/base/components/common/crud/PageList' import {SearchFormProps} from '@emp-antd/base/components/common/crud/SForm/inter' import {FormItemProps} from '@emp-antd/base/components/common/crud/SForm/inter' import {ModalFormProps} from '@emp-antd/base/components/common/crud/ModalForm' export interface DataModalProps { add?: ActionProps remove?: ActionProps edit?: ActionProps search?: SearchActionProps actions?: MoreActionProps[] } export interface MoreActionProps { name: string action?: (e: any) => any isShow?: (e: any) => boolean } export interface SearchActionProps extends Partial<SearchFormProps> { items: FormItemProps[] action?: (e: any) => any } export interface ActionProps extends Partial<ModalFormProps> { title?: string items: FormItemProps[] action?: (e: any) => any clickAction?: (e?: any) => any } const CrudComponent: (opt: PageListProps & DataModalProps) => JSX.Element export default CrudComponent } declare module '@emp-antd/base/components/common/crud/ModalForm' { import React from 'react' import {ModalProps} from 'antd/lib/modal/Modal' import {FormProps, FormInstance} from 'antd/lib/form' import {FormItemProps} from '@emp-antd/base/components/common/crud/SForm/inter' export interface ModalFormProps extends ModalProps { visible?: boolean title?: string name: string formOptions?: FormProps initialValues?: any fromItems: FormItemProps[] options?: ModalProps okText?: string cancelText?: string onCancel?: (e: React.MouseEvent<HTMLElement>) => void onSubmit?: (success: boolean, e: any) => void headerRender?: JSX.Element footerRender?: JSX.Element forceRender?: boolean form?: FormInstance dataRef?: React.RefObject<FormInstance> } const ModalForm: ({ options, initialValues, visible, title, onCancel, onSubmit, headerRender, footerRender, formOptions, name, fromItems, forceRender, destroyOnClose, okText, cancelText, dataRef, form, }: ModalFormProps) => JSX.Element export default ModalForm } declare module '@emp-antd/base/components/common/crud/PageList' { import React from 'react' import {ColumnsType} from 'antd/lib/table' import {TableRowSelection} from 'antd/lib/table/interface' import './PageList.scss' export type RecordType = { title: string dataIndex: string key: string render: (t: string | number | undefined, d: any) => void onCell: (record: any, rowIndex: any) => any sorter: any align: 'center' } export interface PageListProps { list: any loading?: boolean page: number | string pageSize: number | string count: number columnsKey: string columns: ColumnsType<RecordType> nextPage: (d: JSONObject) => void selectRow?: React.ReactText[] onSelectChange?: ((selectedRowKeys: React.ReactText[], selectedRows?: RecordType[]) => void) | undefined expandable?: any bordered?: boolean tableTitle?: string tableTopOption?: any onRow?: (record: any, index: any) => any isMultipleChecked?: boolean rowSelectionOpt?: TableRowSelection<RecordType> } const PageList: ({ tableTopOption, tableTitle, columns, list, loading, page, pageSize, count, nextPage, columnsKey, selectRow, onSelectChange, expandable, bordered, onRow, isMultipleChecked, rowSelectionOpt, }: PageListProps) => JSX.Element export default PageList } declare module '@emp-antd/base/components/common/crud/SForm/index' { /// <reference types="react" /> import {SFormProps} from '@emp-antd/base/components/common/crud/SForm/inter' export const FromItem: ({item}: {item: any}) => any const SForm: ({ options, dataRef, form, items, name, onFinish, onFinishFailed, initialValues, }: SFormProps) => JSX.Element export default SForm } declare module '@emp-antd/base/components/common/crud/SForm/inter' { /// <reference types="react" /> import {ButtonProps, ButtonShape, ButtonType} from 'antd/lib/button' import {InputProps, GroupProps, SearchProps, TextAreaProps, PasswordProps} from 'antd/lib/input' import {RadioGroupProps, RadioChangeEvent} from 'antd/lib/radio/interface' import {UploadProps} from 'antd/lib/upload' import {FormProps, Rule} from 'antd/lib/form' import {FormInstance} from 'antd/lib/form/util' import {DatePickerProps} from 'antd/lib/date-picker' import {TimePickerProps} from 'antd/lib/time-picker' import {SliderProps} from 'antd/lib/slider' import {InputNumberProps} from 'antd/lib/input-number' import {SelectProps} from 'rc-select/lib/' const ButtonHTMLTypes: ['submit', 'button', 'reset'] export type ButtonHTMLType = typeof ButtonHTMLTypes[number] export type SelectFormData = { value: React.ReactText label: React.ReactNode disabled?: boolean } export type RadioFormData = { value: React.ReactText label: React.ReactNode disabled?: boolean } export type renderForm = { disFormItem: boolean } export type textForm = { style?: any className: string } export type selectMultipleProps = { mode?: string defaultValue?: any value?: any } export interface ButtonGroupData { value: React.ReactText label: string options?: ButtonProps | ButtonShape | ButtonType onClick?: ((e: React.MouseEvent) => void) | undefined htmlType?: ButtonHTMLType } export type FormItemOptionsType = | RadioGroupProps | RadioGroupProps | InputProps | GroupProps | SearchProps | TextAreaProps | PasswordProps | renderForm | textForm | selectMultipleProps | DatePickerProps | TimePickerProps | UploadProps | SliderProps | InputNumberProps | SelectProps | undefined export interface FormItemProps { type: string label: string name?: string rules?: Rule[] render?: JSX.Element | any placeholder?: string col?: number options?: FormItemOptionsType data?: SelectFormData[] | RadioFormData[] | ButtonGroupData[] | string | number | undefined onChange?: ((e: RadioChangeEvent | React.MouseEvent) => void) | undefined onSelect?: ((e: RadioChangeEvent | React.MouseEvent) => void) | undefined onClick?: ((e: React.MouseEvent) => void) | undefined } export interface SFormProps { form?: FormInstance dataRef?: React.RefObject<FormInstance> name?: string options?: FormProps onFinish?: ((values: any) => void) | undefined onFinishFailed?: ((values: any) => void) | undefined items: FormItemProps[] initialValues?: any } export interface SearchFormProps extends Partial<SFormProps> { formItems: FormItemProps[] } export {} } declare module '@emp-antd/base/components/common/crud/SearchForm' { /// <reference types="react" /> import {SearchFormProps} from '@emp-antd/base/components/common/crud/SForm/inter' const SearchForm: ({ options, form, formItems, name, onFinish, onFinishFailed, initialValues, dataRef, }: SearchFormProps) => JSX.Element export default SearchForm } declare module '@emp-antd/base/components/common/crud/index' { import ModalForm from '@emp-antd/base/components/common/crud/ModalForm' import PageList from '@emp-antd/base/components/common/crud/PageList' import SearchForm from '@emp-antd/base/components/common/crud/SearchForm' import SForm from '@emp-antd/base/components/common/crud/SForm' import CrudComponent from '@emp-antd/base/components/common/crud/CrudComponent' import './index.scss' export {ModalForm, PageList, SearchForm, SForm, CrudComponent} } declare module '@emp-antd/base/components/layout/FixSlideLayout' { import React from 'react' import './FixSlideLayout.less' import {RoutesType} from '@emp-antd/base/types' const FixSlideLayout: ({ children, routes, }: { children?: React.ReactNode routes?: RoutesType[] | undefined }) => JSX.Element export default FixSlideLayout } declare module '@emp-antd/base/components/layout/MarginLayout' { import React from 'react' import {RoutesType} from '@emp-antd/base/types' import './MarginLayout.less' type THeaderComp = { theme?: 'light' | 'dark' | undefined } export const HeaderComp: ({theme}: THeaderComp) => JSX.Element export const SideComp: () => JSX.Element const MarginLayout: ({ children, routes, }: { children?: React.ReactNode routes?: RoutesType[] | undefined }) => JSX.Element export default MarginLayout } declare module '@emp-antd/base/helpers/envStorage' { const _default: { get(name: string): any set(name: string, value: any): void getJSON(name: string): any setJSON(name: string, value: any): void remove(name: string): void } export default _default } declare module '@emp-antd/base/helpers/http' { const http: import('axios').AxiosInstance export default http } declare module '@emp-antd/base/helpers/loadScript' { const loadScript: (url: string | string[]) => Promise<unknown> export default loadScript } declare module '@emp-antd/base/helpers/udb' { export function yyLogin(url?: string): Promise<void> } declare module '@emp-antd/base/helpers/useQuery' { /** * 使用方法 * const query = useQuery() * query.get('lang') */ export function useQuery(): URLSearchParams } declare module '@emp-antd/base/index' {} declare module '@emp-antd/base/stores/common/crud' { interface CrudAction { create?: any update?: any del?: any request?: any extend?: any } export const crudStore: (crud: CrudAction) => () => any export const useCrudStore: (action: CrudAction) => any export {} } declare module '@emp-antd/base/stores/config' { import {TuserStore} from '@emp-antd/base/stores/user/userStore' import {StoresType} from '@emp-antd/base/types' export interface EmpStoreType { userStore: TuserStore } const stores: StoresType export default stores } declare module '@emp-antd/base/stores/index' { import React from 'react' import {StoresType} from '@emp-antd/base/types' type TstoreProviderProps = { children: React.ReactNode stores?: StoresType } export const StoreProvider: ({children, stores}: TstoreProviderProps) => JSX.Element export const useStores: () => any export {} } declare module '@emp-antd/base/stores/lang/langStore' { export interface LangApi { Req: { project: string mod: string lang: string } Res: JSONObject } export const langStore: () => { $l: JSONObject country: string getLang({project, mod, lang}: LangApi['Req']): Promise<void> } export type TlangStore = ReturnType<typeof langStore> } declare module '@emp-antd/base/stores/user/userStore' { export const userStore: () => { user: TgetUserInfo permission: string[] permissionIsLoad: boolean getUserInfo(yyuid: string | number): Promise<void> logout(): void } export type TuserStore = ReturnType<typeof userStore> export type TgetUserInfo = { id?: string permission: [] yyuid: string yyno?: string nick?: string sex?: string birthday?: string province?: string sign?: string intro?: string jifen?: string register_time?: string passport?: string account?: string hdlogo?: string session_card?: string custom_logo?: string } } declare module '@emp-antd/base/types' { /// <reference types="react" /> export interface LayoutType { useStores: any routes: RoutesType[] children?: React.ReactNode pageview?: <T>(local: T) => void layout?: string | 'FixSlideLayout' } export type RoutesType = { path: string component?: any name?: string url?: string icon?: any routes?: RoutesType[] role?: string } export interface RouterCompType { routes?: RoutesType[] layout?: () => JSX.Element stores?: StoresType pageview?: () => void } export interface StoresType { [key: string]: (...args: any) => any } } declare module '@emp-antd/base' { import main = require('@emp-antd/base/index') export = main }
the_stack
import 'mocha' import { expect } from 'chai' import {spy} from 'sinon' import * as C from '../../constants' import { recordRequest } from './record-request' import { getTestMocks } from '../../test/helper/test-mocks' import { RECORD_ACTION } from '../../constants' import * as testHelper from '../../test/helper/test-helper' import { PromiseDelay } from '../../utils/utils'; describe('record request', () => { const completeCallback = spy() const errorCallback = spy() let testMocks let client let config let services const cacheData = { cache: true } const storageData = { storage: true } beforeEach(() => { const options = testHelper.getDeepstreamOptions() services = options.services config = Object.assign({}, options.config, { record: { cacheRetrievalTimeout: 100, storageRetrievalTimeout: 100, storageExclusionPrefixes: ['dont-save'] } }) services.cache.set('existingRecord', 1, cacheData, () => {}) services.storage.set('onlyExistsInStorage', 1, storageData, () => {}) testMocks = getTestMocks() client = testMocks.getSocketWrapper('someUser') completeCallback.resetHistory() errorCallback.resetHistory() }) describe('records are requested from cache and storage sequentially', () => { it('requests a record that exists in a synchronous cache', () => { services.cache.nextOperationWillBeSynchronous = true recordRequest( 'existingRecord', config, services, client.socketWrapper, completeCallback, errorCallback, null ) expect(services.cache.lastRequestedKey).to.equal('existingRecord') expect(services.storage.lastRequestedKey).to.equal(null) expect(completeCallback).to.have.been.calledWith( 'existingRecord', 1, cacheData, client.socketWrapper ) expect(errorCallback).to.have.callCount(0) }) it('requests a record that exists in an asynchronous cache', async () => { services.cache.nextGetWillBeSynchronous = false recordRequest( 'existingRecord', config, services, client.socketWrapper, completeCallback, errorCallback, null ) await PromiseDelay(30) expect(completeCallback).to.have.been.calledWith( 'existingRecord', 1, cacheData, client.socketWrapper ) expect(errorCallback).to.have.callCount(0) expect(services.cache.lastRequestedKey).to.equal('existingRecord') expect(services.storage.lastRequestedKey).to.equal(null) }) it('requests a record that doesn\'t exists in a synchronous cache, but in storage', () => { services.cache.nextGetWillBeSynchronous = true recordRequest( 'onlyExistsInStorage', config, services, client.socketWrapper, completeCallback, errorCallback, null ) expect(services.cache.lastRequestedKey).to.equal('onlyExistsInStorage') expect(services.storage.lastRequestedKey).to.equal('onlyExistsInStorage') expect(completeCallback).to.have.been.calledWith('onlyExistsInStorage', 1, storageData, client.socketWrapper) expect(errorCallback).to.have.callCount(0) }) it('requests a record that doesn\'t exists in an asynchronous cache, but in asynchronous storage', async () => { services.cache.nextGetWillBeSynchronous = false services.storage.nextGetWillBeSynchronous = false recordRequest( 'onlyExistsInStorage', config, services, client.socketWrapper, completeCallback, errorCallback, null ) await PromiseDelay(75) expect(services.cache.lastRequestedKey).to.equal('onlyExistsInStorage') expect(services.storage.lastRequestedKey).to.equal('onlyExistsInStorage') expect(errorCallback).to.have.callCount(0) expect(completeCallback).to.have.been.calledWith( 'onlyExistsInStorage', 1, storageData, client.socketWrapper ) }) it('returns null for non existent records', () => { services.cache.nextGetWillBeSynchronous = true recordRequest( 'doesNotExist', config, services, client.socketWrapper, completeCallback, errorCallback, null ) expect(completeCallback).to.have.been.calledWith('doesNotExist', -1, null, client.socketWrapper) expect(errorCallback).to.have.callCount(0) expect(services.cache.lastRequestedKey).to.equal('doesNotExist') expect(services.storage.lastRequestedKey).to.equal('doesNotExist') }) it('handles cache errors', () => { services.cache.nextGetWillBeSynchronous = true services.cache.nextOperationWillBeSuccessful = false recordRequest( 'cacheError', config, services, client.socketWrapper, completeCallback, errorCallback, null ) expect(errorCallback).to.have.been.calledWith( RECORD_ACTION.RECORD_LOAD_ERROR, 'error while loading cacheError from cache:storageError', 'cacheError', client.socketWrapper ) expect(completeCallback).to.have.callCount(0) expect(services.logger.logSpy).to.have.been.calledWith( 3, RECORD_ACTION[RECORD_ACTION.RECORD_LOAD_ERROR], 'error while loading cacheError from cache:storageError' ) // expect(client.socketWrapper.socket.lastSendMessage).to.equal( // msg('R|E|RECORD_LOAD_ERROR|error while loading cacheError from cache:storageError+' // )) }) it('handles storage errors', () => { services.cache.nextGetWillBeSynchronous = true services.cache.nextOperationWillBeSuccessful = true services.storage.nextGetWillBeSynchronous = true services.storage.nextOperationWillBeSuccessful = false recordRequest( 'storageError', config, services, client.socketWrapper, completeCallback, errorCallback, null ) expect(errorCallback).to.have.been.calledWith( RECORD_ACTION.RECORD_LOAD_ERROR, 'error while loading storageError from storage:storageError', 'storageError', client.socketWrapper ) expect(completeCallback).to.have.callCount(0) expect(services.logger.logSpy).to.have.been.calledWith(3, RECORD_ACTION[RECORD_ACTION.RECORD_LOAD_ERROR], 'error while loading storageError from storage:storageError') // expect(socketWrapper.socket.lastSendMessage).to.equal(msg('R|E|RECORD_LOAD_ERROR|error while loading storageError from storage:storageError+')) }) describe('handles cache timeouts', () => { beforeEach(() => { config.record.cacheRetrievalTimeout = 1 services.cache.nextGetWillBeSynchronous = false services.cache.nextOperationWillBeSuccessful = true }) afterEach(() => { config.cacheRetrievalTimeout = 10 }) it('sends a CACHE_RETRIEVAL_TIMEOUT message when cache times out', (done) => { recordRequest( 'willTimeoutCache', config, services, client.socketWrapper, completeCallback, errorCallback, null ) setTimeout(() => { expect(errorCallback).to.have.been.calledWith( C.RECORD_ACTION.CACHE_RETRIEVAL_TIMEOUT, 'willTimeoutCache', 'willTimeoutCache', client.socketWrapper ) expect(completeCallback).to.have.callCount(0) // ignores update from cache that may occur afterwards services.cache.triggerLastGetCallback(null, '{ data: "value" }') expect(completeCallback).to.have.callCount(0) done() }, 1) }) }) describe('handles storage timeouts', () => { beforeEach(() => { config.record.storageRetrievalTimeout = 1 services.cache.nextGetWillBeSynchronous = true services.cache.nextOperationWillBeSuccessful = true services.storage.nextGetWillBeSynchronous = false services.storage.nextOperationWillBeSuccessful = true }) it('sends a STORAGE_RETRIEVAL_TIMEOUT message when storage times out', async () => { recordRequest( 'willTimeoutStorage', config, services, client.socketWrapper, completeCallback, errorCallback, null ) await PromiseDelay(1) expect(errorCallback).to.have.been.calledWith( C.RECORD_ACTION.STORAGE_RETRIEVAL_TIMEOUT, 'willTimeoutStorage', 'willTimeoutStorage', client.socketWrapper ) expect(completeCallback).to.have.callCount(0) // ignores update from storage that may occur afterwards services.storage.triggerLastGetCallback(null, '{ data: "value" }') expect(completeCallback).to.have.callCount(0) }) }) }) describe('excluded records are not put into storage', () => { beforeEach(() => { services.cache.nextGetWillBeSynchronous = true services.storage.nextGetWillBeSynchronous = true services.storage.delete = spy() services.storage.set('dont-save/1', 1, {}, () => {}) }) it('returns null when requesting a record that doesn\'t exists in a synchronous cache, and is excluded from storage', () => { recordRequest( 'dont-save/1', config, services, client.socketWrapper, completeCallback, errorCallback, null ) expect(completeCallback).to.have.been.calledWith( 'dont-save/1', -1, null, client.socketWrapper ) expect(errorCallback).to.have.callCount(0) expect(services.storage.lastRequestedKey).to.equal(null) }) }) describe('promoting to cache can be disabled', () => { beforeEach(() => { services.cache.nextGetWillBeSynchronous = true services.storage.nextGetWillBeSynchronous = true services.cache.set = spy() services.storage.set('dont-save/1', 1, {}, () => {}) }) it('doesnt call set on cache if promoteToCache is disabled', () => { recordRequest( 'onlyExistsInStorage', config, services, client.socketWrapper, completeCallback, errorCallback, this, null, null, false ) expect(completeCallback).to.have.been.calledWith( 'onlyExistsInStorage', 1, { storage: true }, client.socketWrapper ) expect(services.cache.set).to.have.callCount(0) expect(errorCallback).to.have.callCount(0) expect(services.cache.lastRequestedKey).to.equal('onlyExistsInStorage') expect(services.storage.lastRequestedKey).to.equal('onlyExistsInStorage') }) }) })
the_stack
import * as React from 'react'; import { useState } from 'react'; import { NavLink, useHistory, useLocation, useParams } from 'react-router-dom'; import { Button, Dropdown, message, Modal, MessageArgsProps, Tooltip, notification } from 'antd'; // @Components import { BreadcrumbsProps, withHome, Breadcrumbs } from 'ui/components/Breadcrumbs/Breadcrumbs'; import { NotificationsWidget } from 'lib/components/NotificationsWidget/NotificationsWidget'; import { CurrentPlan } from 'ui/components/CurrentPlan/CurrentPlan'; import { handleError } from 'lib/components/components'; // @Icons import Icon, { SettingOutlined, AreaChartOutlined, UnlockOutlined, ApiOutlined, NotificationOutlined, CloudOutlined, DownloadOutlined, UserOutlined, UserSwitchOutlined, LogoutOutlined, PartitionOutlined, ThunderboltOutlined } from '@ant-design/icons'; import logo from 'icons/logo.svg'; import logoMini from 'icons/logo-square.svg'; import { ReactComponent as DbtCloudIcon } from 'icons/dbtCloud.svg'; import { ReactComponent as KeyIcon } from 'icons/key.svg'; import classNames from 'classnames'; // @Model import { Permission, User } from 'lib/services/model'; // @Utils import { reloadPage } from 'lib/commons/utils'; import { Page, usePageLocation } from 'navigation'; // @Services import { useServices } from 'hooks/useServices'; import { AnalyticsBlock } from 'lib/services/analytics'; import { CurrentSubscription } from 'lib/services/billing'; // @Styles import styles from './Layout.module.less'; // @Misc import { settingsPageRoutes } from './ui/pages/SettingsPage/SettingsPage'; import { FeatureSettings } from './lib/services/ApplicationServices'; import { usePersistentState } from './hooks/usePersistentState'; import githubLogo from './icons/github.svg'; type MenuItem = { icon: React.ReactNode title: React.ReactNode link: string, enabled: (f: FeatureSettings) => boolean } const makeItem = (icon: React.ReactNode, title: React.ReactNode, link: string, enabled = (f: FeatureSettings) => true): MenuItem => { return { icon, title, link, enabled }; } const menuItems = [ makeItem(<PartitionOutlined/>, 'Home', '/connections'), makeItem(<ThunderboltOutlined/>, 'Live Events', '/events_stream'), makeItem(<AreaChartOutlined/>, 'Statistics', '/dashboard'), makeItem(<Icon component={KeyIcon}/>, 'API Keys', '/api_keys'), makeItem(<ApiOutlined/>, 'Sources', '/sources'), makeItem(<NotificationOutlined/>, 'Destinations', '/destinations'), makeItem(<Icon component={DbtCloudIcon}/>, 'dbt Cloud Integration', '/dbtcloud'), makeItem(<CloudOutlined/>, 'Custom Domains', '/domains', (f) => f.enableCustomDomains), makeItem(<DownloadOutlined/>, 'Download Config', '/cfg_download', (f) => f.enableCustomDomains) ]; export const ApplicationMenu: React.FC<{ expanded: boolean }> = ({ expanded }) => { const key = usePageLocation().mainMenuKey; return <div className="pt-3"> {menuItems.map(item => { const selected = item.link === '/' + key; return <NavLink to={item.link} key={item.link}> <div key={item.link} className={`${selected && 'bg-bgPrimary'} whitespace-nowrap text-textPale hover:text-primaryHover py-3 ml-2 pl-4 pr-6 rounded-l-xl`}> {!expanded && <Tooltip title={item.title} placement="right" mouseEnterDelay={0}> {item.icon} </Tooltip>} {expanded && <>{item.icon}<span className="pl-2 whitespace-nowrap">{item.title}</span></>} </div> </NavLink> })} </div> }; export const ApplicationSidebar: React.FC<{}> = () => { const [expanded, setExpanded] = usePersistentState(true, 'jitsu_menuExpanded'); return <div className={`relative ${styles.sideBarContent}`}> <div> <div className={`${expanded ? 'w-3' : 'w-2'} absolute inline-block top-3 right-0 bg-bgTableHeader h-12 flex items-center justify-center rounded-l cursor-pointer`} onClick={() => setExpanded(!expanded)}> <svg xmlns="http://www.w3.org/2000/svg" className={`transform ${expanded ? 'rotate-90' : '-rotate-90'}`} viewBox="0 0 24 24"> <path d="M14.121,13.879c-0.586-0.586-6.414-6.414-7-7c-1.172-1.172-3.071-1.172-4.243,0 c-1.172,1.172-1.172,3.071,0,4.243c0.586,0.586,6.414,6.414,7,7c1.172,1.172,3.071,1.172,4.243,0 C15.293,16.95,15.293,15.05,14.121,13.879z" opacity=".35"/> <path d="M14.121,18.121c0.586-0.586,6.414-6.414,7-7c1.172-1.172,1.172-3.071,0-4.243c-1.172-1.172-3.071-1.172-4.243,0 c-0.586,0.586-6.414,6.414-7,7c-1.172,1.172-1.172,3.071,0,4.243C11.05,19.293,12.95,19.293,14.121,18.121z"/> </svg> </div> <a href="https://jitsu.com" className="text-center block pt-5 h-14"> <img src={expanded ? logo : logoMini} alt="[logo]" className="h-8 mx-auto"/> </a> <ApplicationMenu expanded={expanded}/> </div> </div> } export type PageHeaderProps = { user: User plan: CurrentSubscription } function abbr(user: User) { return user.name?.split(' ').filter(part => part.length > 0).map(part => part[0]).join('').toUpperCase(); } export const PageHeader: React.FC<PageHeaderProps> = ({ plan, user, children }) => { const [dropdownVisible, setDropdownVisible] = useState(false); return ( <div className="border-b border-splitBorder mb-4 h-12 flex flex-nowrap"> <div className="flex-grow"> <div className="h-12 flex items-center">{children}</div> </div> <div className={ `flex-shrink flex justify-center items-center mx-1` } > <NotificationsWidget/> </div> <div className="flex-shrink flex justify-center items-center"> <Dropdown trigger={['click']} onVisibleChange={(vis) => setDropdownVisible(vis)} visible={dropdownVisible} overlay={ <DropdownMenu user={user} plan={plan} hideMenu={() => setDropdownVisible(false)} /> } > <Button className="ml-1 border-primary border-2 hover:border-text text-text hover:text-text" size="large" shape="circle" > {abbr(user) || <UserOutlined/>} </Button> </Dropdown> </div> </div> ); } export const DropdownMenu: React.FC<{ user: User, plan: CurrentSubscription, hideMenu: () => void }> = ({ plan, user, hideMenu }) => { const services = useServices(); const history = useHistory(); const showSettings = React.useCallback<() => void>(() => history.push(settingsPageRoutes[0]), [history]) const becomeUser = async() => { let email = prompt('Please enter e-mail of the user', ''); if (!email) { return; } try { AnalyticsBlock.blockAll(); await services.userService.becomeUser(email); } catch (e) { handleError(e, 'Can\'t login as other user'); AnalyticsBlock.unblockAll(); } }; return ( <div className="bg-bgSecondary"> <div className="py-5 border-b border-main px-5 flex flex-col items-center"> <div className="text-center text-text text-lg">{user.name}</div> <div className="text-secondaryText text-xs underline">{user.email}</div> </div> <div className="py-2 border-b border-main px-5 flex flex-col items-start"> <div>Project: <b>{services.activeProject.name || 'Unspecified'}</b></div> </div> {services.features.billingEnabled && services.applicationConfiguration.billingUrl && <div className="py-5 border-b border-main px-5 flex flex-col items-start"> <CurrentPlan planStatus={plan} onPlanChangeModalOpen={hideMenu}/> </div>} <div className="p-2 flex flex-col items-stretch"> <Button type="text" className="text-left" key="settings" icon={<SettingOutlined/>} onClick={showSettings}> Settings </Button> {services.userService.getUser().hasPermission(Permission.BECOME_OTHER_USER) && <Button className="text-left" type="text" key="become" icon={<UserSwitchOutlined/>} onClick={becomeUser}> Become User </Button> } <Button className="text-left" type="text" key="logout" icon={<LogoutOutlined/>} onClick={() => services.userService.removeAuth(reloadPage) }>Logout</Button> </div> </div> ); } export type ApplicationPageWrapperProps = { page: Page user: User plan: CurrentSubscription [propName: string]: any } function handleBillingMessage(params) { if (!params.get('billingMessage')) { return; } (params.get('billingStatus') === 'error' ? notification.error : notification.success)({ message: params.get('billingMessage'), duration: 5 }); } export const ApplicationPage: React.FC<ApplicationPageWrapperProps> = ({ plan, page, user, ...rest }) => { const [breadcrumbs, setBreadcrumbs] = useState<BreadcrumbsProps>(withHome({ elements: [{ title: page.pageHeader }] })); handleBillingMessage(new URLSearchParams(useLocation().search)) let Component = page.component as React.ExoticComponent; let props = { setBreadcrumbs } return <div className={styles.applicationPage}> <div className={classNames(styles.sidebar)}> <ApplicationSidebar/> </div> <div className={classNames(styles.rightbar)}> <PageHeader user={user} plan={plan}><Breadcrumbs {...breadcrumbs} /></PageHeader> <div className={styles.applicationPageComponent}> <Component {...(props as any)} /> </div> </div> </div>; } export const SlackChatWidget: React.FC<{}> = () => { const services = useServices(); const [modalVisible, setModalVisible] = useState(false); return <> <div id="jitsuSlackWidget" onClick={() => { services.analyticsService.track('slack_invitation_open'); setModalVisible(true) }} className="fixed bottom-5 right-5 rounded-full bg-primary text-text w-12 h-12 flex justify-center items-center cursor-pointer hover:bg-primaryHover"> <svg className="h-6 w-6" fill="currentColor" viewBox="0 0 24 24"> <path d="M 4 3 C 2.9 3 2 3.9 2 5 L 2 15.792969 C 2 16.237969 2.5385156 16.461484 2.8535156 16.146484 L 5 14 L 14 14 C 15.1 14 16 13.1 16 12 L 16 5 C 16 3.9 15.1 3 14 3 L 4 3 z M 18 8 L 18 12 C 18 14.209 16.209 16 14 16 L 8 16 L 8 17 C 8 18.1 8.9 19 10 19 L 19 19 L 21.146484 21.146484 C 21.461484 21.461484 22 21.237969 22 20.792969 L 22 10 C 22 8.9 21.1 8 20 8 L 18 8 z"/> </svg> </div> <SlackInvitationModal visible={modalVisible} hide={() => { setModalVisible(false); }}/></> } export const SlackInvitationModal: React.FC<{ visible: boolean, hide: () => void }> = ({ visible, hide }) => { return <Modal title="Join Jitsu Slack" visible={visible} onCancel={() => { hide(); }} footer={null} > <div className="text-lg"> We'd be delighted to assist you with any issues in our <b>public Slack</b>! 100+ members already received help from our community </div> <div className="flex justify-center pt-6"> <Button onClick={() => { window.open('https://jitsu.com/slack', '_blank') hide(); }} size="large" type="primary" icon={<Icon component={() => <svg className="fill-current" viewBox="0 0 24 24" height="1em" width="1em"> <path d="m8.843 12.651c-1.392 0-2.521 1.129-2.521 2.521v6.306c0 1.392 1.129 2.521 2.521 2.521s2.521-1.129 2.521-2.521v-6.306c-.001-1.392-1.13-2.521-2.521-2.521z"/> <path d="m.019 15.172c0 1.393 1.13 2.523 2.523 2.523s2.523-1.13 2.523-2.523v-2.523h-2.521c-.001 0-.001 0-.002 0-1.393 0-2.523 1.13-2.523 2.523z"/> <path d="m8.846-.001c-.001 0-.002 0-.003 0-1.393 0-2.523 1.13-2.523 2.523s1.13 2.523 2.523 2.523h2.521v-2.523c0-.001 0-.003 0-.005-.001-1.391-1.128-2.518-2.518-2.518z"/> <path d="m2.525 11.37h6.318c1.393 0 2.523-1.13 2.523-2.523s-1.13-2.523-2.523-2.523h-6.318c-1.393 0-2.523 1.13-2.523 2.523s1.13 2.523 2.523 2.523z"/> <path d="m21.457 6.323c-1.391 0-2.518 1.127-2.518 2.518v.005 2.523h2.521c1.393 0 2.523-1.13 2.523-2.523s-1.13-2.523-2.523-2.523c-.001 0-.002 0-.003 0z"/> <path d="m12.641 2.522v6.325c0 1.392 1.129 2.521 2.521 2.521s2.521-1.129 2.521-2.521v-6.325c0-1.392-1.129-2.521-2.521-2.521-1.392 0-2.521 1.129-2.521 2.521z"/> <g> <path d="m17.682 21.476c0-1.392-1.129-2.521-2.521-2.521h-2.521v2.523c.001 1.391 1.129 2.519 2.521 2.519s2.521-1.129 2.521-2.521z"/> <path d="m21.479 12.649h-6.318c-1.393 0-2.523 1.13-2.523 2.523s1.13 2.523 2.523 2.523h6.318c1.393 0 2.523-1.13 2.523-2.523s-1.13-2.523-2.523-2.523z"/> </g> </svg>}/>}>Join Jitsu Slack</Button> </div> </Modal> } const EmailIsNotConfirmedMessage: React.FC<{ messageKey: React.Key }> = ({ messageKey }) => { const services = useServices(); const [isSendingVerification, setIsSendingVerification] = useState<boolean>(false); const handleDestroyMessage = () => message.destroy(messageKey); const handleresendConfirmationLink = async() => { setIsSendingVerification(true); try { await services.userService.sendConfirmationEmail(); } finally { setIsSendingVerification(false); } handleDestroyMessage(); }; return ( <span className="flex flex-col items-center mt-1"> <span> <span>{'Email '}</span> {services.userService.getUser()?.email ? ( <span className={`font-semibold ${styles.emailHighlight}`}> {services.userService.getUser()?.email} </span> ) : ( '' )} <span> {` is not verified. Please, follow the instructions in your email to complete the verification process.`} </span> </span> <span> <Button type="link" loading={isSendingVerification} onClick={handleresendConfirmationLink} > {'Resend verification link'} </Button> <Button type="text" onClick={handleDestroyMessage}> {'Close'} </Button> </span> </span> ); }; const MESSAGE_KEY = 'email-not-confirmed-message'; export const emailIsNotConfirmedMessageConfig: MessageArgsProps = { type: 'error', key: MESSAGE_KEY, duration: null, icon: <>{null}</>, content: <EmailIsNotConfirmedMessage messageKey={MESSAGE_KEY}/> };
the_stack
import { PluginStateObject, PluginStateTransform } from '../../mol-plugin-state/objects'; import { createSphericalCollocationGrid } from './orbitals'; import { ParamDefinition as PD } from '../../mol-util/param-definition'; import { Task } from '../../mol-task'; import { CustomProperties } from '../../mol-model/custom-property'; import { SphericalBasisOrder } from './spherical-functions'; import { Volume } from '../../mol-model/volume'; import { PluginContext } from '../../mol-plugin/context'; import { ColorNames } from '../../mol-util/color/names'; import { createVolumeRepresentationParams } from '../../mol-plugin-state/helpers/volume-representation-params'; import { StateTransformer } from '../../mol-state'; import { Theme } from '../../mol-theme/theme'; import { VolumeRepresentation3DHelpers } from '../../mol-plugin-state/transforms/representation'; import { AlphaOrbital, Basis, CubeGrid, CubeGridFormat, isCubeGridData } from './data-model'; import { createSphericalCollocationDensityGrid } from './density'; import { Tensor } from '../../mol-math/linear-algebra'; export class BasisAndOrbitals extends PluginStateObject.Create<{ basis: Basis, order: SphericalBasisOrder, orbitals: AlphaOrbital[] }>({ name: 'Basis', typeClass: 'Object' }) { } export const StaticBasisAndOrbitals = PluginStateTransform.BuiltIn({ name: 'static-basis-and-orbitals', display: 'Basis and Orbitals', from: PluginStateObject.Root, to: BasisAndOrbitals, params: { label: PD.Text('Orbital Data', { isHidden: true }), basis: PD.Value<Basis>(void 0 as any, { isHidden: true }), order: PD.Text<SphericalBasisOrder>('gaussian' as SphericalBasisOrder, { isHidden: true }), orbitals: PD.Value<AlphaOrbital[]>([], { isHidden: true }) }, })({ apply({ params }) { return new BasisAndOrbitals({ basis: params.basis, order: params.order, orbitals: params.orbitals }, { label: params.label }); } }); const CreateOrbitalVolumeParamBase = { cutoffThreshold: PD.Numeric(0.0015, { min: 0, max: 0.1, step: 0.0001 }), boxExpand: PD.Numeric(4.5, { min: 0, max: 7, step: 0.1 }), gridSpacing: PD.ObjectList({ atomCount: PD.Numeric(0), spacing: PD.Numeric(0.35, { min: 0.1, max: 2, step: 0.01 }) }, e => `Atoms ${e.atomCount}: ${e.spacing}`, { defaultValue: [ { atomCount: 55, spacing: 0.5 }, { atomCount: 40, spacing: 0.45 }, { atomCount: 25, spacing: 0.4 }, { atomCount: 0, spacing: 0.35 }, ] }), clampValues: PD.MappedStatic('off', { off: PD.EmptyGroup(), on: PD.Group({ sigma: PD.Numeric(8, { min: 1, max: 20 }, { description: 'Clamp values to range [sigma * negIsoValue, sigma * posIsoValue].' }) }) }) }; function clampData(matrix: Tensor.Data, min: number, max: number) { for (let i = 0, _i = matrix.length; i < _i; i++) { const v = matrix[i]; if (v < min) matrix[i] = min; else if (v > max) matrix[i] = max; } } function clampGrid(data: CubeGrid, v: number) { const grid = data.grid; const min = (data.isovalues?.negative ?? data.grid.stats.min) * v; const max = (data.isovalues?.positive ?? data.grid.stats.max) * v; // clamp values for better direct volume resolution // current implementation uses Byte array for values // if this is not enough, update mol* to use float // textures instead if (grid.stats.min < min || grid.stats.max > max) { clampData(data.grid.cells.data, min, max); if (grid.stats.min < min) { (grid.stats.min as number) = min; } if (grid.stats.max > max) { (grid.stats.max as number) = max; } } } export const CreateOrbitalVolume = PluginStateTransform.BuiltIn({ name: 'create-orbital-volume', display: 'Orbital Volume', from: BasisAndOrbitals, to: PluginStateObject.Volume.Data, params: (a) => { if (!a) { return { index: PD.Numeric(0), ...CreateOrbitalVolumeParamBase }; } return { index: PD.Select(0, a.data.orbitals.map((o, i) => [i, `[${i + 1}] ${o.energy.toFixed(4)}`])), ...CreateOrbitalVolumeParamBase }; } })({ apply({ a, params }, plugin: PluginContext) { return Task.create('Orbital Volume', async ctx => { const data = await createSphericalCollocationGrid({ basis: a.data.basis, cutoffThreshold: params.cutoffThreshold, sphericalOrder: a.data.order, boxExpand: params.boxExpand, gridSpacing: params.gridSpacing.map(e => [e.atomCount, e.spacing] as [number, number]) }, a.data.orbitals[params.index], plugin.canvas3d?.webgl).runInContext(ctx); const volume: Volume = { grid: data.grid, sourceData: CubeGridFormat(data), customProperties: new CustomProperties(), _propertyData: Object.create(null), }; if (params.clampValues?.name === 'on') { clampGrid(data, params.clampValues?.params?.sigma ?? 8); } return new PluginStateObject.Volume.Data(volume, { label: 'Orbital Volume' }); }); } }); export const CreateOrbitalDensityVolume = PluginStateTransform.BuiltIn({ name: 'create-orbital-density-volume', display: 'Orbital Density Volume', from: BasisAndOrbitals, to: PluginStateObject.Volume.Data, params: CreateOrbitalVolumeParamBase })({ apply({ a, params }, plugin: PluginContext) { return Task.create('Orbital Volume', async ctx => { const data = await createSphericalCollocationDensityGrid({ basis: a.data.basis, cutoffThreshold: params.cutoffThreshold, sphericalOrder: a.data.order, boxExpand: params.boxExpand, gridSpacing: params.gridSpacing.map(e => [e.atomCount, e.spacing] as [number, number]) }, a.data.orbitals, plugin.canvas3d?.webgl).runInContext(ctx); const volume: Volume = { grid: data.grid, sourceData: CubeGridFormat(data), customProperties: new CustomProperties(), _propertyData: Object.create(null), }; if (params.clampValues?.name === 'on') { clampGrid(data, params.clampValues?.params?.sigma ?? 8); } return new PluginStateObject.Volume.Data(volume, { label: 'Orbital Volume' }); }); } }); export const CreateOrbitalRepresentation3D = PluginStateTransform.BuiltIn({ name: 'create-orbital-representation-3d', display: 'Orbital Representation 3D', from: PluginStateObject.Volume.Data, to: PluginStateObject.Volume.Representation3D, params: { directVolume: PD.Boolean(false), relativeIsovalue: PD.Numeric(1, { min: 0.01, max: 5, step: 0.01 }), kind: PD.Select<'positive' | 'negative'>('positive', [['positive', 'Positive'], ['negative', 'Negative']]), color: PD.Color(ColorNames.blue), alpha: PD.Numeric(1, { min: 0, max: 1, step: 0.01 }), xrayShaded: PD.Boolean(false), pickable: PD.Boolean(true), tryUseGpu: PD.Boolean(true) } })({ canAutoUpdate() { return true; }, apply({ a, params: srcParams }, plugin: PluginContext) { return Task.create('Orbitals Representation 3D', async ctx => { const params = volumeParams(plugin, a, srcParams); const propertyCtx = { runtime: ctx, assetManager: plugin.managers.asset }; const provider = plugin.representation.volume.registry.get(params.type.name); if (provider.ensureCustomProperties) await provider.ensureCustomProperties.attach(propertyCtx, a.data); const props = params.type.params || {}; const repr = provider.factory({ webgl: plugin.canvas3d?.webgl, ...plugin.representation.volume.themes }, provider.getParams); repr.setTheme(Theme.create(plugin.representation.volume.themes, { volume: a.data }, params)); await repr.createOrUpdate(props, a.data).runInContext(ctx); repr.setState({ pickable: srcParams.pickable }); return new PluginStateObject.Volume.Representation3D({ repr, sourceData: a.data }, { label: provider.label, description: VolumeRepresentation3DHelpers.getDescription(props) }); }); }, update({ a, b, newParams: srcParams }, plugin: PluginContext) { return Task.create('Orbitals Representation 3D', async ctx => { const newParams = volumeParams(plugin, a, srcParams); const props = { ...b.data.repr.props, ...newParams.type.params }; b.data.repr.setTheme(Theme.create(plugin.representation.volume.themes, { volume: a.data }, newParams)); await b.data.repr.createOrUpdate(props, a.data).runInContext(ctx); b.data.sourceData = a.data; b.data.repr.setState({ pickable: srcParams.pickable }); b.description = VolumeRepresentation3DHelpers.getDescription(props); return StateTransformer.UpdateResult.Updated; }); } }); function volumeParams(plugin: PluginContext, volume: PluginStateObject.Volume.Data, params: StateTransformer.Params<typeof CreateOrbitalRepresentation3D>) { if (!isCubeGridData(volume.data.sourceData)) throw new Error('Invalid data source kind.'); const { isovalues } = volume.data.sourceData.data; if (!isovalues) throw new Error('Isovalues are not computed.'); const value = isovalues[params.kind]; return createVolumeRepresentationParams(plugin, volume.data, params.directVolume ? { type: 'direct-volume', typeParams: { alpha: params.alpha, renderMode: { name: 'isosurface', params: { isoValue: { kind: 'absolute', absoluteValue: (value ?? 1000) * params.relativeIsovalue }, singleLayer: false } }, xrayShaded: params.xrayShaded }, color: 'uniform', colorParams: { value: params.color } } : { type: 'isosurface', typeParams: { isoValue: { kind: 'absolute', absoluteValue: (value ?? 1000) * params.relativeIsovalue }, alpha: params.alpha, xrayShaded: params.xrayShaded, tryUseGpu: params.tryUseGpu }, color: 'uniform', colorParams: { value: params.color } }); }
the_stack
import React, { ComponentType, isValidElement, ReactElement, useCallback, useMemo, useRef, useState } from 'react'; import { Animated, FlatList, FlatListProps, ListRenderItem, ListRenderItemInfo, NativeScrollEvent, NativeSyntheticEvent, StyleProp, StyleSheet, Text, TextStyle, TouchableOpacity, View, ViewStyle } from 'react-native'; import { ChunkOptions, getAbsoluteWidth, GridItem, InsertAfterTable, InsertRowTable, useGridChunks, WidthTable } from '../hooks/grid-chunks.hook'; const DEFAULT_COLUMNS = 2; const DEFAULT_MIN_COLUMNS = 175; const DEFAULT_BACK_TOP_BUTTON_SHOW_AT_HEIGHT = 100; const DEFAULT_KEY_EXTRACTOR = <ItemT extends GridItem<{ id?: string; key?: string } | null>>( items: ItemT[], index: number ): string => { const key = items .map(item => item.value?.key ?? item.value?.id) .filter(Boolean) .join(); return key || `${index}`; }; const gridStyle = StyleSheet.create({ row: { flexGrow: 1, flexDirection: 'row', flexWrap: 'nowrap' }, item: { flexDirection: 'row', flexWrap: 'nowrap' }, itemRow: { flex: 1, justifyContent: 'space-between' }, rowSeparator: { width: '100%', height: 1, backgroundColor: '#8E8E8E' }, columnSeparator: { height: '100%', width: 1, backgroundColor: '#8E8E8E' }, scrollTopButtonContainer: { position: 'absolute', bottom: 30, right: 30, zIndex: 200 }, scrollTopButton: { backgroundColor: '#eee', padding: 10 } }); export type GridScrollToTopFunc = () => void; export interface BackToTopComponentProps { backToTop: GridScrollToTopFunc; } export interface GridRenderItemInfo<ItemT> extends ListRenderItemInfo<ItemT> { totalColumns: number; columns: number; } export type GridRenderItem<ItemT> = (info: GridRenderItemInfo<ItemT>) => React.ReactElement | null; export type GridRow<ItemT> = GridItem<ItemT | null>[]; export interface GridProps<ItemT> extends Pick< FlatListProps<ItemT>, | 'accessible' | 'accessibilityHint' | 'accessibilityLabel' | 'accessibilityRole' | 'style' | 'data' | 'refreshing' | 'refreshControl' | 'onRefresh' | 'onEndReachedThreshold' | 'onEndReached' | 'onLayout' | 'ListEmptyComponent' | 'ListFooterComponent' | 'ListFooterComponentStyle' | 'ListHeaderComponent' | 'ListHeaderComponentStyle' > { /** * Takes an item from data and renders it into the list. Typical usage: * ``` * _renderItem = ({item}) => ( * <TouchableOpacity onPress={() => this._onPress(item)}> * <Text>{item.title}</Text> * <TouchableOpacity/> * ); * ... * <FlatList data={[{title: 'Title Text', key: 'item1'}]} renderItem={this._renderItem} /> * ``` * Provides additional metadata like `index` if you need it. */ renderItem: GridRenderItem<ItemT>; /** * The number of columns to display in the grid. * @deprecated to be removed in fs12, use numColumns instead */ columns?: number; /** * Whether or not a back to top button should appear after the user scrolls down. Defaults to * false. * @deprecated to be removed in fs12, use BackToTopButton instead */ showBackToTop?: boolean; /** * An optional function to render a header component displayed at the top of the grid. * @deprecated to be removed in fs12, use ListHeaderComponent instead */ renderHeader?: () => JSX.Element | null; /** * An optional function to render a footer component, displayed at the bottom of the grid. * @deprecated to be removed in fs12, use ListFooterComponent instead */ renderFooter?: () => JSX.Element | null; /** * Styles to apply to the container around the back to top button * @deprecated to be removed in fs12, use BackToTopStyle instead */ backToTopContainerStyle?: StyleProp<ViewStyle>; /** * Styles to apply to the back to top button. Does not apply if a custom back to top render * function is used. * @deprecated to be removed in fs12, use BackToTopButton instead */ backToTopButtonStyle?: StyleProp<ViewStyle>; /** * Styles to apply to the default back to top text. Does not apply if a custom back to top render * function is used. * @deprecated to be removed in fs12, use BackToTopButton instead */ backToTopTextStyle?: StyleProp<TextStyle>; /** * Copy to show inside the back to top button. Defaults to "Top". Does not apply if a custom back * to top render function is used. * @deprecated to be removed in fs12, use BackToTopButton instead */ backToTopText?: string; /** * The distance the user needs to scroll down before the back to top button appears. Defaults to * 100. * @deprecated to be removed in fs12, use BackToTopShowAtHeight instead */ backToTopShowAtHeight?: number; /** * An optional custom render function to render a back to top button. * @deprecated use BackToTopButton instead */ renderBackToTopButton?: (scrollToTop: GridScrollToTopFunc) => JSX.Element; /** * Props to pass to the underlying FlatList. * @deprecated to be removed in fs12 */ listViewProps?: Partial<FlatListProps<GridRow<ItemT>>>; /** * Whether or not to show a separator between columns in the grid. * @deprecated to be removed in fs12 */ showColumnSeparators?: boolean; /** * Style to apply to the separator between columns in the grid. */ columnSeparatorStyle?: StyleProp<ViewStyle>; /** * Whether or not to show a separator between rows in the grid. * @deprecated to be removed in fs12 */ showRowSeparators?: boolean; /** * Style to apply to the separator between rows in the grid. */ rowSeparatorStyle?: StyleProp<ViewStyle>; /** * Style to apply to parent view component. */ gridContainerStyle?: StyleProp<ViewStyle>; /** * The distance the user needs to scroll down before the back to top button appears. Defaults to * 100. */ BackToTopShowAtHeight?: number; /** * Styles to apply to the container around the back to top button */ BackToTopStyle?: StyleProp<ViewStyle>; /** * An optional custom render function to render a back to top button. */ BackToTopComponent?: ComponentType<BackToTopComponentProps> | ReactElement; /** * The number of columns to display in the grid. Defaults to 'auto'. * * Note: When using `auto` there will always be at least 1 blank render * prior to items being rendered while the container is measured. */ numColumns?: number | 'auto'; /** * The minium column width when `numColumns` is set to `auto` * Defaults to 175 */ minColumnWidth?: number; /** * A map of index with the preferred columns of the item at that index. */ columnWidthTable?: WidthTable; insertRows?: InsertRowTable<ItemT>; insertAfter?: InsertAfterTable<ItemT>; insertEveryFrequency?: number; insertEveryValues?: ItemT | GridItem<ItemT> | (ItemT | GridItem<ItemT>)[]; } export interface GridState<ItemT> extends Pick<FlatListProps<ItemT[]>, 'data'> { /** * Whether or not the back to top button is currently visible. */ backToTopVisible: boolean; } // TODO: wSedlacek remove deprecated props in fs12 export const Grid = <ItemT, >(props: GridProps<ItemT>) => { const { accessible, accessibilityHint, accessibilityLabel, accessibilityRole, data, renderItem, BackToTopComponent, BackToTopShowAtHeight, BackToTopStyle, ListEmptyComponent, ListFooterComponent, ListFooterComponentStyle, ListHeaderComponent, ListHeaderComponentStyle, columnWidthTable, columnSeparatorStyle, gridContainerStyle, insertRows, insertAfter, insertEveryFrequency, insertEveryValues, minColumnWidth, numColumns, onEndReached, onEndReachedThreshold, onLayout, onRefresh, refreshControl, refreshing, rowSeparatorStyle, style, backToTopButtonStyle, backToTopContainerStyle, backToTopShowAtHeight, backToTopText, backToTopTextStyle, columns, listViewProps, renderBackToTopButton, renderFooter, renderHeader, showBackToTop, showColumnSeparators, showRowSeparators } = props; const listView = useRef<FlatList<GridRow<ItemT>>>(null); const [width, setWidth] = useState<number | undefined>(() => { const containerWidth = StyleSheet.flatten([gridContainerStyle]).width; if (typeof containerWidth === 'number') { return containerWidth; } const gridWidth = StyleSheet.flatten([style]).width; if (typeof gridWidth === 'number') { return gridWidth; } return undefined; }); const [backTopOpacity] = useState(new Animated.Value(0)); const [backToTopVisible, setBackToTopVisible] = useState(false); const totalColumns = useMemo(() => { if (typeof numColumns !== 'number' || columns !== undefined) { if (width) { const calculatedColumns = Math.floor(width / (minColumnWidth ?? DEFAULT_MIN_COLUMNS)); return Math.max(calculatedColumns, 1); } else { return 0; } } else { return columns ?? numColumns ?? DEFAULT_COLUMNS; } }, [columns, numColumns, minColumnWidth, width]); const chunkOptions = useMemo<ChunkOptions<ItemT, null>>( () => ({ widthTable: columnWidthTable, insertRows, insertAfter, insertEvery: insertEveryFrequency && insertEveryValues ? { frequency: insertEveryFrequency, values: insertEveryValues } : undefined, emptyValue: null }), [columnWidthTable, insertRows, insertAfter, insertEveryFrequency, insertEveryValues] ); const chunkedData = useGridChunks(data ?? [], totalColumns, chunkOptions); const chunkedArray = useMemo(() => Array.from(chunkedData), [chunkedData]); const handleBackToTop = useCallback(() => { listView.current?.scrollToOffset({ offset: 0 }); }, [listView]); const handleScroll = useCallback( (event?: NativeSyntheticEvent<NativeScrollEvent>) => { if (event) { const scrollY = event.nativeEvent.contentOffset.y; const threshold = BackToTopShowAtHeight ?? backToTopShowAtHeight ?? DEFAULT_BACK_TOP_BUTTON_SHOW_AT_HEIGHT; if (scrollY > threshold && !backToTopVisible) { setBackToTopVisible(true); Animated.timing(backTopOpacity, { toValue: 1, useNativeDriver: true }).start(); } else if (scrollY < threshold && backToTopVisible) { setBackToTopVisible(false); Animated.timing(backTopOpacity, { toValue: 0, useNativeDriver: true }).start(); } } }, [ backTopOpacity, BackToTopShowAtHeight, backToTopShowAtHeight, backToTopVisible, setBackToTopVisible ] ); const renderRow = useCallback<ListRenderItem<GridRow<ItemT>>>( ({ index, item, separators }) => { const showRowSeparator = chunkedArray?.length > index + 1; const columnWidth = (100 / totalColumns); return ( <View style={gridStyle.row}> {item.map((item, index) => { const columns = getAbsoluteWidth(item.width, totalColumns); const widthPercent = Math.floor((columnWidth * columns) * 100) / 100; const showColumnSeparator = (index + 1) % totalColumns !== 0; return ( <View key={index} style={[gridStyle.item, { width: widthPercent + '%' }]}> <View style={gridStyle.itemRow}> {item.value && renderItem && renderItem({ item: item.value, index, separators, totalColumns, columns })} {(showRowSeparators || rowSeparatorStyle) && showRowSeparator && ( <View style={[gridStyle.rowSeparator, rowSeparatorStyle]} /> )} </View> {(showColumnSeparators || columnSeparatorStyle) && showColumnSeparator && ( <View style={[gridStyle.columnSeparator, columnSeparatorStyle]} /> )} </View> ); })} </View> ); }, [ chunkedArray, totalColumns, renderItem, showRowSeparators, rowSeparatorStyle, showColumnSeparators, columnSeparatorStyle ] ); const rerenderTrigger = useMemo(() => { return Symbol('This is used to mark a change that requires a rerender'); }, [listViewProps?.extraData, renderRow]); return ( <View style={gridContainerStyle}> <FlatList ref={listView} accessible={accessible} accessibilityHint={accessibilityHint} accessibilityLabel={accessibilityLabel} accessibilityRole={accessibilityRole} data={chunkedArray} renderItem={renderRow} keyExtractor={DEFAULT_KEY_EXTRACTOR} ListEmptyComponent={ListEmptyComponent} ListFooterComponent={ListFooterComponent ?? renderFooter} ListFooterComponentStyle={ListFooterComponentStyle} ListHeaderComponent={ListHeaderComponent ?? renderHeader} ListHeaderComponentStyle={ListHeaderComponentStyle} style={style} refreshControl={refreshControl} refreshing={refreshing} onRefresh={onRefresh} onScroll={showBackToTop || BackToTopComponent ? handleScroll : undefined} onEndReached={onEndReached} onEndReachedThreshold={onEndReachedThreshold} onLayout={onLayout} onContentSizeChange={setWidth} extraData={rerenderTrigger} {...listViewProps} /> {(showBackToTop || BackToTopComponent) && ( <Animated.View style={[ gridStyle.scrollTopButtonContainer, { opacity: backTopOpacity }, BackToTopStyle ?? backToTopContainerStyle ]} > {isValidElement(BackToTopComponent) ? ( BackToTopComponent ) : BackToTopComponent ? ( <BackToTopComponent backToTop={handleBackToTop} /> ) : renderBackToTopButton ? ( renderBackToTopButton(handleBackToTop) ) : ( <TouchableOpacity style={[gridStyle.scrollTopButton, backToTopButtonStyle]} onPress={handleBackToTop} > <Text style={backToTopTextStyle}>{backToTopText ?? 'Top'}</Text> </TouchableOpacity> )} </Animated.View> )} </View> ); };
the_stack
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest'; import * as models from '../models'; /** * @class * Operations * __NOTE__: An instance of this class is automatically created for an * instance of the DataFactoryManagementClient. */ export interface Operations { /** * Lists the available Azure Data Factory API operations. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<OperationListResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationListResponse>>; /** * Lists the available Azure Data Factory API operations. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {OperationListResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {OperationListResponse} [result] - The deserialized result object if an error did not occur. * See {@link OperationListResponse} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationListResponse>; list(callback: ServiceCallback<models.OperationListResponse>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationListResponse>): void; /** * Lists the available Azure Data Factory API operations. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<OperationListResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationListResponse>>; /** * Lists the available Azure Data Factory API operations. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {OperationListResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {OperationListResponse} [result] - The deserialized result object if an error did not occur. * See {@link OperationListResponse} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationListResponse>; listNext(nextPageLink: string, callback: ServiceCallback<models.OperationListResponse>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationListResponse>): void; } /** * @class * Factories * __NOTE__: An instance of this class is automatically created for an * instance of the DataFactoryManagementClient. */ export interface Factories { /** * Lists factories under the specified subscription. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<FactoryListResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.FactoryListResponse>>; /** * Lists factories under the specified subscription. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {FactoryListResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {FactoryListResponse} [result] - The deserialized result object if an error did not occur. * See {@link FactoryListResponse} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.FactoryListResponse>; list(callback: ServiceCallback<models.FactoryListResponse>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.FactoryListResponse>): void; /** * Updates a factory's repo information. * * @param {string} locationId The location identifier. * * @param {object} factoryRepoUpdate Update factory repo request definition. * * @param {string} [factoryRepoUpdate.factoryResourceId] The factory resource * id. * * @param {object} [factoryRepoUpdate.repoConfiguration] Git repo information * of the factory. * * @param {string} factoryRepoUpdate.repoConfiguration.accountName Account * name. * * @param {string} factoryRepoUpdate.repoConfiguration.repositoryName * Rrepository name. * * @param {string} factoryRepoUpdate.repoConfiguration.collaborationBranch * Collaboration branch. * * @param {string} factoryRepoUpdate.repoConfiguration.rootFolder Root folder. * * @param {string} [factoryRepoUpdate.repoConfiguration.lastCommitId] Last * commit id. * * @param {string} factoryRepoUpdate.repoConfiguration.type Polymorphic * Discriminator * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Factory>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ configureFactoryRepoWithHttpOperationResponse(locationId: string, factoryRepoUpdate: models.FactoryRepoUpdate, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Factory>>; /** * Updates a factory's repo information. * * @param {string} locationId The location identifier. * * @param {object} factoryRepoUpdate Update factory repo request definition. * * @param {string} [factoryRepoUpdate.factoryResourceId] The factory resource * id. * * @param {object} [factoryRepoUpdate.repoConfiguration] Git repo information * of the factory. * * @param {string} factoryRepoUpdate.repoConfiguration.accountName Account * name. * * @param {string} factoryRepoUpdate.repoConfiguration.repositoryName * Rrepository name. * * @param {string} factoryRepoUpdate.repoConfiguration.collaborationBranch * Collaboration branch. * * @param {string} factoryRepoUpdate.repoConfiguration.rootFolder Root folder. * * @param {string} [factoryRepoUpdate.repoConfiguration.lastCommitId] Last * commit id. * * @param {string} factoryRepoUpdate.repoConfiguration.type Polymorphic * Discriminator * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Factory} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Factory} [result] - The deserialized result object if an error did not occur. * See {@link Factory} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ configureFactoryRepo(locationId: string, factoryRepoUpdate: models.FactoryRepoUpdate, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Factory>; configureFactoryRepo(locationId: string, factoryRepoUpdate: models.FactoryRepoUpdate, callback: ServiceCallback<models.Factory>): void; configureFactoryRepo(locationId: string, factoryRepoUpdate: models.FactoryRepoUpdate, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Factory>): void; /** * Lists factories. * * @param {string} resourceGroupName The resource group name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<FactoryListResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.FactoryListResponse>>; /** * Lists factories. * * @param {string} resourceGroupName The resource group name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {FactoryListResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {FactoryListResponse} [result] - The deserialized result object if an error did not occur. * See {@link FactoryListResponse} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroup(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.FactoryListResponse>; listByResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.FactoryListResponse>): void; listByResourceGroup(resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.FactoryListResponse>): void; /** * Creates or updates a factory. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {object} factory Factory resource definition. * * @param {object} [factory.identity] Managed service identity of the factory. * * @param {object} [factory.repoConfiguration] Git repo information of the * factory. * * @param {string} factory.repoConfiguration.accountName Account name. * * @param {string} factory.repoConfiguration.repositoryName Rrepository name. * * @param {string} factory.repoConfiguration.collaborationBranch Collaboration * branch. * * @param {string} factory.repoConfiguration.rootFolder Root folder. * * @param {string} [factory.repoConfiguration.lastCommitId] Last commit id. * * @param {string} factory.repoConfiguration.type Polymorphic Discriminator * * @param {string} [factory.location] The resource location. * * @param {object} [factory.tags] The resource tags. * * @param {object} [options] Optional Parameters. * * @param {string} [options.ifMatch] ETag of the factory entity. Should only be * specified for update, for which it should match existing entity or can be * * for unconditional update. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Factory>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(resourceGroupName: string, factoryName: string, factory: models.Factory, options?: { ifMatch? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Factory>>; /** * Creates or updates a factory. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {object} factory Factory resource definition. * * @param {object} [factory.identity] Managed service identity of the factory. * * @param {object} [factory.repoConfiguration] Git repo information of the * factory. * * @param {string} factory.repoConfiguration.accountName Account name. * * @param {string} factory.repoConfiguration.repositoryName Rrepository name. * * @param {string} factory.repoConfiguration.collaborationBranch Collaboration * branch. * * @param {string} factory.repoConfiguration.rootFolder Root folder. * * @param {string} [factory.repoConfiguration.lastCommitId] Last commit id. * * @param {string} factory.repoConfiguration.type Polymorphic Discriminator * * @param {string} [factory.location] The resource location. * * @param {object} [factory.tags] The resource tags. * * @param {object} [options] Optional Parameters. * * @param {string} [options.ifMatch] ETag of the factory entity. Should only be * specified for update, for which it should match existing entity or can be * * for unconditional update. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Factory} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Factory} [result] - The deserialized result object if an error did not occur. * See {@link Factory} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(resourceGroupName: string, factoryName: string, factory: models.Factory, options?: { ifMatch? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.Factory>; createOrUpdate(resourceGroupName: string, factoryName: string, factory: models.Factory, callback: ServiceCallback<models.Factory>): void; createOrUpdate(resourceGroupName: string, factoryName: string, factory: models.Factory, options: { ifMatch? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Factory>): void; /** * Updates a factory. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {object} factoryUpdateParameters The parameters for updating a * factory. * * @param {object} [factoryUpdateParameters.tags] The resource tags. * * @param {object} [factoryUpdateParameters.identity] Managed service identity * of the factory. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Factory>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateWithHttpOperationResponse(resourceGroupName: string, factoryName: string, factoryUpdateParameters: models.FactoryUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Factory>>; /** * Updates a factory. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {object} factoryUpdateParameters The parameters for updating a * factory. * * @param {object} [factoryUpdateParameters.tags] The resource tags. * * @param {object} [factoryUpdateParameters.identity] Managed service identity * of the factory. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Factory} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Factory} [result] - The deserialized result object if an error did not occur. * See {@link Factory} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ update(resourceGroupName: string, factoryName: string, factoryUpdateParameters: models.FactoryUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Factory>; update(resourceGroupName: string, factoryName: string, factoryUpdateParameters: models.FactoryUpdateParameters, callback: ServiceCallback<models.Factory>): void; update(resourceGroupName: string, factoryName: string, factoryUpdateParameters: models.FactoryUpdateParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Factory>): void; /** * Gets a factory. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.ifNoneMatch] ETag of the factory entity. Should * only be specified for get. If the ETag matches the existing entity tag, or * if * was provided, then no content will be returned. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Factory>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, factoryName: string, options?: { ifNoneMatch? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Factory>>; /** * Gets a factory. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.ifNoneMatch] ETag of the factory entity. Should * only be specified for get. If the ETag matches the existing entity tag, or * if * was provided, then no content will be returned. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Factory} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Factory} [result] - The deserialized result object if an error did not occur. * See {@link Factory} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, factoryName: string, options?: { ifNoneMatch? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.Factory>; get(resourceGroupName: string, factoryName: string, callback: ServiceCallback<models.Factory>): void; get(resourceGroupName: string, factoryName: string, options: { ifNoneMatch? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Factory>): void; /** * Deletes a factory. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, factoryName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes a factory. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, factoryName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, factoryName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, factoryName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Get GitHub Access Token. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {object} gitHubAccessTokenRequest Get GitHub access token request * definition. * * @param {string} gitHubAccessTokenRequest.gitHubAccessCode GitHub access * code. * * @param {string} [gitHubAccessTokenRequest.gitHubClientId] GitHub application * client ID. * * @param {string} gitHubAccessTokenRequest.gitHubAccessTokenBaseUrl GitHub * access token base URL. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<GitHubAccessTokenResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getGitHubAccessTokenWithHttpOperationResponse(resourceGroupName: string, factoryName: string, gitHubAccessTokenRequest: models.GitHubAccessTokenRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.GitHubAccessTokenResponse>>; /** * Get GitHub Access Token. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {object} gitHubAccessTokenRequest Get GitHub access token request * definition. * * @param {string} gitHubAccessTokenRequest.gitHubAccessCode GitHub access * code. * * @param {string} [gitHubAccessTokenRequest.gitHubClientId] GitHub application * client ID. * * @param {string} gitHubAccessTokenRequest.gitHubAccessTokenBaseUrl GitHub * access token base URL. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {GitHubAccessTokenResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {GitHubAccessTokenResponse} [result] - The deserialized result object if an error did not occur. * See {@link GitHubAccessTokenResponse} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getGitHubAccessToken(resourceGroupName: string, factoryName: string, gitHubAccessTokenRequest: models.GitHubAccessTokenRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.GitHubAccessTokenResponse>; getGitHubAccessToken(resourceGroupName: string, factoryName: string, gitHubAccessTokenRequest: models.GitHubAccessTokenRequest, callback: ServiceCallback<models.GitHubAccessTokenResponse>): void; getGitHubAccessToken(resourceGroupName: string, factoryName: string, gitHubAccessTokenRequest: models.GitHubAccessTokenRequest, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.GitHubAccessTokenResponse>): void; /** * Lists factories under the specified subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<FactoryListResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.FactoryListResponse>>; /** * Lists factories under the specified subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {FactoryListResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {FactoryListResponse} [result] - The deserialized result object if an error did not occur. * See {@link FactoryListResponse} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.FactoryListResponse>; listNext(nextPageLink: string, callback: ServiceCallback<models.FactoryListResponse>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.FactoryListResponse>): void; /** * Lists factories. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<FactoryListResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.FactoryListResponse>>; /** * Lists factories. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {FactoryListResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {FactoryListResponse} [result] - The deserialized result object if an error did not occur. * See {@link FactoryListResponse} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroupNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.FactoryListResponse>; listByResourceGroupNext(nextPageLink: string, callback: ServiceCallback<models.FactoryListResponse>): void; listByResourceGroupNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.FactoryListResponse>): void; } /** * @class * IntegrationRuntimes * __NOTE__: An instance of this class is automatically created for an * instance of the DataFactoryManagementClient. */ export interface IntegrationRuntimes { /** * Lists integration runtimes. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<IntegrationRuntimeListResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByFactoryWithHttpOperationResponse(resourceGroupName: string, factoryName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.IntegrationRuntimeListResponse>>; /** * Lists integration runtimes. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {IntegrationRuntimeListResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {IntegrationRuntimeListResponse} [result] - The deserialized result object if an error did not occur. * See {@link IntegrationRuntimeListResponse} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByFactory(resourceGroupName: string, factoryName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.IntegrationRuntimeListResponse>; listByFactory(resourceGroupName: string, factoryName: string, callback: ServiceCallback<models.IntegrationRuntimeListResponse>): void; listByFactory(resourceGroupName: string, factoryName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.IntegrationRuntimeListResponse>): void; /** * Creates or updates an integration runtime. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {object} integrationRuntime Integration runtime resource definition. * * @param {object} integrationRuntime.properties Integration runtime * properties. * * @param {string} [integrationRuntime.properties.description] Integration * runtime description. * * @param {string} integrationRuntime.properties.type Polymorphic Discriminator * * @param {object} [options] Optional Parameters. * * @param {string} [options.ifMatch] ETag of the integration runtime entity. * Should only be specified for update, for which it should match existing * entity or can be * for unconditional update. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<IntegrationRuntimeResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, integrationRuntime: models.IntegrationRuntimeResource, options?: { ifMatch? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.IntegrationRuntimeResource>>; /** * Creates or updates an integration runtime. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {object} integrationRuntime Integration runtime resource definition. * * @param {object} integrationRuntime.properties Integration runtime * properties. * * @param {string} [integrationRuntime.properties.description] Integration * runtime description. * * @param {string} integrationRuntime.properties.type Polymorphic Discriminator * * @param {object} [options] Optional Parameters. * * @param {string} [options.ifMatch] ETag of the integration runtime entity. * Should only be specified for update, for which it should match existing * entity or can be * for unconditional update. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {IntegrationRuntimeResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {IntegrationRuntimeResource} [result] - The deserialized result object if an error did not occur. * See {@link IntegrationRuntimeResource} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, integrationRuntime: models.IntegrationRuntimeResource, options?: { ifMatch? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.IntegrationRuntimeResource>; createOrUpdate(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, integrationRuntime: models.IntegrationRuntimeResource, callback: ServiceCallback<models.IntegrationRuntimeResource>): void; createOrUpdate(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, integrationRuntime: models.IntegrationRuntimeResource, options: { ifMatch? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.IntegrationRuntimeResource>): void; /** * Gets an integration runtime. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.ifNoneMatch] ETag of the integration runtime * entity. Should only be specified for get. If the ETag matches the existing * entity tag, or if * was provided, then no content will be returned. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<IntegrationRuntimeResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: { ifNoneMatch? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.IntegrationRuntimeResource>>; /** * Gets an integration runtime. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.ifNoneMatch] ETag of the integration runtime * entity. Should only be specified for get. If the ETag matches the existing * entity tag, or if * was provided, then no content will be returned. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {IntegrationRuntimeResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {IntegrationRuntimeResource} [result] - The deserialized result object if an error did not occur. * See {@link IntegrationRuntimeResource} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: { ifNoneMatch? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.IntegrationRuntimeResource>; get(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, callback: ServiceCallback<models.IntegrationRuntimeResource>): void; get(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options: { ifNoneMatch? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.IntegrationRuntimeResource>): void; /** * Updates an integration runtime. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {object} updateIntegrationRuntimeRequest The parameters for updating * an integration runtime. * * @param {string} [updateIntegrationRuntimeRequest.autoUpdate] Enables or * disables the auto-update feature of the self-hosted integration runtime. See * https://go.microsoft.com/fwlink/?linkid=854189. Possible values include: * 'On', 'Off' * * @param {string} [updateIntegrationRuntimeRequest.updateDelayOffset] The time * offset (in hours) in the day, e.g., PT03H is 3 hours. The integration * runtime auto update will happen on that time. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<IntegrationRuntimeResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateWithHttpOperationResponse(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, updateIntegrationRuntimeRequest: models.UpdateIntegrationRuntimeRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.IntegrationRuntimeResource>>; /** * Updates an integration runtime. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {object} updateIntegrationRuntimeRequest The parameters for updating * an integration runtime. * * @param {string} [updateIntegrationRuntimeRequest.autoUpdate] Enables or * disables the auto-update feature of the self-hosted integration runtime. See * https://go.microsoft.com/fwlink/?linkid=854189. Possible values include: * 'On', 'Off' * * @param {string} [updateIntegrationRuntimeRequest.updateDelayOffset] The time * offset (in hours) in the day, e.g., PT03H is 3 hours. The integration * runtime auto update will happen on that time. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {IntegrationRuntimeResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {IntegrationRuntimeResource} [result] - The deserialized result object if an error did not occur. * See {@link IntegrationRuntimeResource} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ update(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, updateIntegrationRuntimeRequest: models.UpdateIntegrationRuntimeRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.IntegrationRuntimeResource>; update(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, updateIntegrationRuntimeRequest: models.UpdateIntegrationRuntimeRequest, callback: ServiceCallback<models.IntegrationRuntimeResource>): void; update(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, updateIntegrationRuntimeRequest: models.UpdateIntegrationRuntimeRequest, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.IntegrationRuntimeResource>): void; /** * Deletes an integration runtime. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes an integration runtime. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Gets detailed status information for an integration runtime. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<IntegrationRuntimeStatusResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getStatusWithHttpOperationResponse(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.IntegrationRuntimeStatusResponse>>; /** * Gets detailed status information for an integration runtime. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {IntegrationRuntimeStatusResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {IntegrationRuntimeStatusResponse} [result] - The deserialized result object if an error did not occur. * See {@link IntegrationRuntimeStatusResponse} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getStatus(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.IntegrationRuntimeStatusResponse>; getStatus(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, callback: ServiceCallback<models.IntegrationRuntimeStatusResponse>): void; getStatus(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.IntegrationRuntimeStatusResponse>): void; /** * Gets the on-premises integration runtime connection information for * encrypting the on-premises data source credentials. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<IntegrationRuntimeConnectionInfo>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getConnectionInfoWithHttpOperationResponse(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.IntegrationRuntimeConnectionInfo>>; /** * Gets the on-premises integration runtime connection information for * encrypting the on-premises data source credentials. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {IntegrationRuntimeConnectionInfo} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {IntegrationRuntimeConnectionInfo} [result] - The deserialized result object if an error did not occur. * See {@link IntegrationRuntimeConnectionInfo} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getConnectionInfo(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.IntegrationRuntimeConnectionInfo>; getConnectionInfo(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, callback: ServiceCallback<models.IntegrationRuntimeConnectionInfo>): void; getConnectionInfo(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.IntegrationRuntimeConnectionInfo>): void; /** * Regenerates the authentication key for an integration runtime. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {object} regenerateKeyParameters The parameters for regenerating * integration runtime authentication key. * * @param {string} [regenerateKeyParameters.keyName] The name of the * authentication key to regenerate. Possible values include: 'authKey1', * 'authKey2' * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<IntegrationRuntimeAuthKeys>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ regenerateAuthKeyWithHttpOperationResponse(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, regenerateKeyParameters: models.IntegrationRuntimeRegenerateKeyParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.IntegrationRuntimeAuthKeys>>; /** * Regenerates the authentication key for an integration runtime. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {object} regenerateKeyParameters The parameters for regenerating * integration runtime authentication key. * * @param {string} [regenerateKeyParameters.keyName] The name of the * authentication key to regenerate. Possible values include: 'authKey1', * 'authKey2' * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {IntegrationRuntimeAuthKeys} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {IntegrationRuntimeAuthKeys} [result] - The deserialized result object if an error did not occur. * See {@link IntegrationRuntimeAuthKeys} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ regenerateAuthKey(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, regenerateKeyParameters: models.IntegrationRuntimeRegenerateKeyParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.IntegrationRuntimeAuthKeys>; regenerateAuthKey(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, regenerateKeyParameters: models.IntegrationRuntimeRegenerateKeyParameters, callback: ServiceCallback<models.IntegrationRuntimeAuthKeys>): void; regenerateAuthKey(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, regenerateKeyParameters: models.IntegrationRuntimeRegenerateKeyParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.IntegrationRuntimeAuthKeys>): void; /** * Retrieves the authentication keys for an integration runtime. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<IntegrationRuntimeAuthKeys>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listAuthKeysWithHttpOperationResponse(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.IntegrationRuntimeAuthKeys>>; /** * Retrieves the authentication keys for an integration runtime. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {IntegrationRuntimeAuthKeys} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {IntegrationRuntimeAuthKeys} [result] - The deserialized result object if an error did not occur. * See {@link IntegrationRuntimeAuthKeys} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listAuthKeys(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.IntegrationRuntimeAuthKeys>; listAuthKeys(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, callback: ServiceCallback<models.IntegrationRuntimeAuthKeys>): void; listAuthKeys(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.IntegrationRuntimeAuthKeys>): void; /** * Starts a ManagedReserved type integration runtime. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<IntegrationRuntimeStatusResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ startWithHttpOperationResponse(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.IntegrationRuntimeStatusResponse>>; /** * Starts a ManagedReserved type integration runtime. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {IntegrationRuntimeStatusResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {IntegrationRuntimeStatusResponse} [result] - The deserialized result object if an error did not occur. * See {@link IntegrationRuntimeStatusResponse} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ start(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.IntegrationRuntimeStatusResponse>; start(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, callback: ServiceCallback<models.IntegrationRuntimeStatusResponse>): void; start(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.IntegrationRuntimeStatusResponse>): void; /** * Stops a ManagedReserved type integration runtime. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ stopWithHttpOperationResponse(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Stops a ManagedReserved type integration runtime. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ stop(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; stop(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, callback: ServiceCallback<void>): void; stop(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Force the integration runtime to synchronize credentials across integration * runtime nodes, and this will override the credentials across all worker * nodes with those available on the dispatcher node. If you already have the * latest credential backup file, you should manually import it (preferred) on * any self-hosted integration runtime node than using this API directly. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ syncCredentialsWithHttpOperationResponse(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Force the integration runtime to synchronize credentials across integration * runtime nodes, and this will override the credentials across all worker * nodes with those available on the dispatcher node. If you already have the * latest credential backup file, you should manually import it (preferred) on * any self-hosted integration runtime node than using this API directly. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ syncCredentials(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; syncCredentials(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, callback: ServiceCallback<void>): void; syncCredentials(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Get the integration runtime monitoring data, which includes the monitor data * for all the nodes under this integration runtime. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<IntegrationRuntimeMonitoringData>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getMonitoringDataWithHttpOperationResponse(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.IntegrationRuntimeMonitoringData>>; /** * Get the integration runtime monitoring data, which includes the monitor data * for all the nodes under this integration runtime. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {IntegrationRuntimeMonitoringData} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {IntegrationRuntimeMonitoringData} [result] - The deserialized result object if an error did not occur. * See {@link IntegrationRuntimeMonitoringData} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getMonitoringData(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.IntegrationRuntimeMonitoringData>; getMonitoringData(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, callback: ServiceCallback<models.IntegrationRuntimeMonitoringData>): void; getMonitoringData(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.IntegrationRuntimeMonitoringData>): void; /** * Upgrade self-hosted integration runtime to latest version if availably. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ upgradeWithHttpOperationResponse(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Upgrade self-hosted integration runtime to latest version if availably. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ upgrade(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; upgrade(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, callback: ServiceCallback<void>): void; upgrade(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Remove all linked integration runtimes under specific data factory in a * self-hosted integration runtime. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {object} linkedIntegrationRuntimeRequest The data factory name for * the linked integration runtime. * * @param {string} linkedIntegrationRuntimeRequest.linkedFactoryName The data * factory name for linked integration runtime. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ removeLinksWithHttpOperationResponse(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, linkedIntegrationRuntimeRequest: models.LinkedIntegrationRuntimeRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Remove all linked integration runtimes under specific data factory in a * self-hosted integration runtime. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {object} linkedIntegrationRuntimeRequest The data factory name for * the linked integration runtime. * * @param {string} linkedIntegrationRuntimeRequest.linkedFactoryName The data * factory name for linked integration runtime. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ removeLinks(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, linkedIntegrationRuntimeRequest: models.LinkedIntegrationRuntimeRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; removeLinks(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, linkedIntegrationRuntimeRequest: models.LinkedIntegrationRuntimeRequest, callback: ServiceCallback<void>): void; removeLinks(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, linkedIntegrationRuntimeRequest: models.LinkedIntegrationRuntimeRequest, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Create a linked integration runtime entry in a shared integration runtime. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {object} createLinkedIntegrationRuntimeRequest The linked integration * runtime properties. * * @param {string} [createLinkedIntegrationRuntimeRequest.name] The name of the * linked integration runtime. * * @param {string} [createLinkedIntegrationRuntimeRequest.subscriptionId] The * ID of the subscription that the linked integration runtime belongs to. * * @param {string} [createLinkedIntegrationRuntimeRequest.dataFactoryName] The * name of the data factory that the linked integration runtime belongs to. * * @param {string} [createLinkedIntegrationRuntimeRequest.dataFactoryLocation] * The location of the data factory that the linked integration runtime belongs * to. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<IntegrationRuntimeStatusResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createLinkedIntegrationRuntimeWithHttpOperationResponse(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, createLinkedIntegrationRuntimeRequest: models.CreateLinkedIntegrationRuntimeRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.IntegrationRuntimeStatusResponse>>; /** * Create a linked integration runtime entry in a shared integration runtime. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {object} createLinkedIntegrationRuntimeRequest The linked integration * runtime properties. * * @param {string} [createLinkedIntegrationRuntimeRequest.name] The name of the * linked integration runtime. * * @param {string} [createLinkedIntegrationRuntimeRequest.subscriptionId] The * ID of the subscription that the linked integration runtime belongs to. * * @param {string} [createLinkedIntegrationRuntimeRequest.dataFactoryName] The * name of the data factory that the linked integration runtime belongs to. * * @param {string} [createLinkedIntegrationRuntimeRequest.dataFactoryLocation] * The location of the data factory that the linked integration runtime belongs * to. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {IntegrationRuntimeStatusResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {IntegrationRuntimeStatusResponse} [result] - The deserialized result object if an error did not occur. * See {@link IntegrationRuntimeStatusResponse} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createLinkedIntegrationRuntime(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, createLinkedIntegrationRuntimeRequest: models.CreateLinkedIntegrationRuntimeRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.IntegrationRuntimeStatusResponse>; createLinkedIntegrationRuntime(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, createLinkedIntegrationRuntimeRequest: models.CreateLinkedIntegrationRuntimeRequest, callback: ServiceCallback<models.IntegrationRuntimeStatusResponse>): void; createLinkedIntegrationRuntime(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, createLinkedIntegrationRuntimeRequest: models.CreateLinkedIntegrationRuntimeRequest, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.IntegrationRuntimeStatusResponse>): void; /** * Starts a ManagedReserved type integration runtime. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<IntegrationRuntimeStatusResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginStartWithHttpOperationResponse(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.IntegrationRuntimeStatusResponse>>; /** * Starts a ManagedReserved type integration runtime. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {IntegrationRuntimeStatusResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {IntegrationRuntimeStatusResponse} [result] - The deserialized result object if an error did not occur. * See {@link IntegrationRuntimeStatusResponse} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginStart(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.IntegrationRuntimeStatusResponse>; beginStart(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, callback: ServiceCallback<models.IntegrationRuntimeStatusResponse>): void; beginStart(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.IntegrationRuntimeStatusResponse>): void; /** * Stops a ManagedReserved type integration runtime. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginStopWithHttpOperationResponse(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Stops a ManagedReserved type integration runtime. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginStop(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginStop(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, callback: ServiceCallback<void>): void; beginStop(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Lists integration runtimes. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<IntegrationRuntimeListResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByFactoryNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.IntegrationRuntimeListResponse>>; /** * Lists integration runtimes. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {IntegrationRuntimeListResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {IntegrationRuntimeListResponse} [result] - The deserialized result object if an error did not occur. * See {@link IntegrationRuntimeListResponse} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByFactoryNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.IntegrationRuntimeListResponse>; listByFactoryNext(nextPageLink: string, callback: ServiceCallback<models.IntegrationRuntimeListResponse>): void; listByFactoryNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.IntegrationRuntimeListResponse>): void; } /** * @class * IntegrationRuntimeNodes * __NOTE__: An instance of this class is automatically created for an * instance of the DataFactoryManagementClient. */ export interface IntegrationRuntimeNodes { /** * Gets a self-hosted integration runtime node. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {string} nodeName The integration runtime node name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SelfHostedIntegrationRuntimeNode>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, nodeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SelfHostedIntegrationRuntimeNode>>; /** * Gets a self-hosted integration runtime node. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {string} nodeName The integration runtime node name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SelfHostedIntegrationRuntimeNode} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SelfHostedIntegrationRuntimeNode} [result] - The deserialized result object if an error did not occur. * See {@link SelfHostedIntegrationRuntimeNode} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, nodeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SelfHostedIntegrationRuntimeNode>; get(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, nodeName: string, callback: ServiceCallback<models.SelfHostedIntegrationRuntimeNode>): void; get(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, nodeName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SelfHostedIntegrationRuntimeNode>): void; /** * Deletes a self-hosted integration runtime node. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {string} nodeName The integration runtime node name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, nodeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes a self-hosted integration runtime node. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {string} nodeName The integration runtime node name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, nodeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, nodeName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, nodeName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Updates a self-hosted integration runtime node. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {string} nodeName The integration runtime node name. * * @param {object} updateIntegrationRuntimeNodeRequest The parameters for * updating an integration runtime node. * * @param {number} [updateIntegrationRuntimeNodeRequest.concurrentJobsLimit] * The number of concurrent jobs permitted to run on the integration runtime * node. Values between 1 and maxConcurrentJobs(inclusive) are allowed. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SelfHostedIntegrationRuntimeNode>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateWithHttpOperationResponse(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, nodeName: string, updateIntegrationRuntimeNodeRequest: models.UpdateIntegrationRuntimeNodeRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SelfHostedIntegrationRuntimeNode>>; /** * Updates a self-hosted integration runtime node. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {string} nodeName The integration runtime node name. * * @param {object} updateIntegrationRuntimeNodeRequest The parameters for * updating an integration runtime node. * * @param {number} [updateIntegrationRuntimeNodeRequest.concurrentJobsLimit] * The number of concurrent jobs permitted to run on the integration runtime * node. Values between 1 and maxConcurrentJobs(inclusive) are allowed. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SelfHostedIntegrationRuntimeNode} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SelfHostedIntegrationRuntimeNode} [result] - The deserialized result object if an error did not occur. * See {@link SelfHostedIntegrationRuntimeNode} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ update(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, nodeName: string, updateIntegrationRuntimeNodeRequest: models.UpdateIntegrationRuntimeNodeRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SelfHostedIntegrationRuntimeNode>; update(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, nodeName: string, updateIntegrationRuntimeNodeRequest: models.UpdateIntegrationRuntimeNodeRequest, callback: ServiceCallback<models.SelfHostedIntegrationRuntimeNode>): void; update(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, nodeName: string, updateIntegrationRuntimeNodeRequest: models.UpdateIntegrationRuntimeNodeRequest, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SelfHostedIntegrationRuntimeNode>): void; /** * Get the IP address of self-hosted integration runtime node. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {string} nodeName The integration runtime node name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<IntegrationRuntimeNodeIpAddress>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getIpAddressWithHttpOperationResponse(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, nodeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.IntegrationRuntimeNodeIpAddress>>; /** * Get the IP address of self-hosted integration runtime node. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} integrationRuntimeName The integration runtime name. * * @param {string} nodeName The integration runtime node name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {IntegrationRuntimeNodeIpAddress} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {IntegrationRuntimeNodeIpAddress} [result] - The deserialized result object if an error did not occur. * See {@link IntegrationRuntimeNodeIpAddress} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getIpAddress(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, nodeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.IntegrationRuntimeNodeIpAddress>; getIpAddress(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, nodeName: string, callback: ServiceCallback<models.IntegrationRuntimeNodeIpAddress>): void; getIpAddress(resourceGroupName: string, factoryName: string, integrationRuntimeName: string, nodeName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.IntegrationRuntimeNodeIpAddress>): void; } /** * @class * LinkedServices * __NOTE__: An instance of this class is automatically created for an * instance of the DataFactoryManagementClient. */ export interface LinkedServices { /** * Lists linked services. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<LinkedServiceListResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByFactoryWithHttpOperationResponse(resourceGroupName: string, factoryName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.LinkedServiceListResponse>>; /** * Lists linked services. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {LinkedServiceListResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {LinkedServiceListResponse} [result] - The deserialized result object if an error did not occur. * See {@link LinkedServiceListResponse} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByFactory(resourceGroupName: string, factoryName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.LinkedServiceListResponse>; listByFactory(resourceGroupName: string, factoryName: string, callback: ServiceCallback<models.LinkedServiceListResponse>): void; listByFactory(resourceGroupName: string, factoryName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.LinkedServiceListResponse>): void; /** * Creates or updates a linked service. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} linkedServiceName The linked service name. * * @param {object} linkedService Linked service resource definition. * * @param {object} linkedService.properties Properties of linked service. * * @param {object} [linkedService.properties.connectVia] The integration * runtime reference. * * @param {string} linkedService.properties.connectVia.referenceName Reference * integration runtime name. * * @param {object} [linkedService.properties.connectVia.parameters] Arguments * for integration runtime. * * @param {string} [linkedService.properties.description] Linked service * description. * * @param {object} [linkedService.properties.parameters] Parameters for linked * service. * * @param {array} [linkedService.properties.annotations] List of tags that can * be used for describing the Dataset. * * @param {string} linkedService.properties.type Polymorphic Discriminator * * @param {object} [options] Optional Parameters. * * @param {string} [options.ifMatch] ETag of the linkedService entity. Should * only be specified for update, for which it should match existing entity or * can be * for unconditional update. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<LinkedServiceResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(resourceGroupName: string, factoryName: string, linkedServiceName: string, linkedService: models.LinkedServiceResource, options?: { ifMatch? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.LinkedServiceResource>>; /** * Creates or updates a linked service. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} linkedServiceName The linked service name. * * @param {object} linkedService Linked service resource definition. * * @param {object} linkedService.properties Properties of linked service. * * @param {object} [linkedService.properties.connectVia] The integration * runtime reference. * * @param {string} linkedService.properties.connectVia.referenceName Reference * integration runtime name. * * @param {object} [linkedService.properties.connectVia.parameters] Arguments * for integration runtime. * * @param {string} [linkedService.properties.description] Linked service * description. * * @param {object} [linkedService.properties.parameters] Parameters for linked * service. * * @param {array} [linkedService.properties.annotations] List of tags that can * be used for describing the Dataset. * * @param {string} linkedService.properties.type Polymorphic Discriminator * * @param {object} [options] Optional Parameters. * * @param {string} [options.ifMatch] ETag of the linkedService entity. Should * only be specified for update, for which it should match existing entity or * can be * for unconditional update. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {LinkedServiceResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {LinkedServiceResource} [result] - The deserialized result object if an error did not occur. * See {@link LinkedServiceResource} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(resourceGroupName: string, factoryName: string, linkedServiceName: string, linkedService: models.LinkedServiceResource, options?: { ifMatch? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.LinkedServiceResource>; createOrUpdate(resourceGroupName: string, factoryName: string, linkedServiceName: string, linkedService: models.LinkedServiceResource, callback: ServiceCallback<models.LinkedServiceResource>): void; createOrUpdate(resourceGroupName: string, factoryName: string, linkedServiceName: string, linkedService: models.LinkedServiceResource, options: { ifMatch? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.LinkedServiceResource>): void; /** * Gets a linked service. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} linkedServiceName The linked service name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.ifNoneMatch] ETag of the linked service entity. * Should only be specified for get. If the ETag matches the existing entity * tag, or if * was provided, then no content will be returned. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<LinkedServiceResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, factoryName: string, linkedServiceName: string, options?: { ifNoneMatch? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.LinkedServiceResource>>; /** * Gets a linked service. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} linkedServiceName The linked service name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.ifNoneMatch] ETag of the linked service entity. * Should only be specified for get. If the ETag matches the existing entity * tag, or if * was provided, then no content will be returned. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {LinkedServiceResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {LinkedServiceResource} [result] - The deserialized result object if an error did not occur. * See {@link LinkedServiceResource} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, factoryName: string, linkedServiceName: string, options?: { ifNoneMatch? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.LinkedServiceResource>; get(resourceGroupName: string, factoryName: string, linkedServiceName: string, callback: ServiceCallback<models.LinkedServiceResource>): void; get(resourceGroupName: string, factoryName: string, linkedServiceName: string, options: { ifNoneMatch? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.LinkedServiceResource>): void; /** * Deletes a linked service. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} linkedServiceName The linked service name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, factoryName: string, linkedServiceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes a linked service. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} linkedServiceName The linked service name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, factoryName: string, linkedServiceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, factoryName: string, linkedServiceName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, factoryName: string, linkedServiceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Lists linked services. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<LinkedServiceListResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByFactoryNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.LinkedServiceListResponse>>; /** * Lists linked services. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {LinkedServiceListResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {LinkedServiceListResponse} [result] - The deserialized result object if an error did not occur. * See {@link LinkedServiceListResponse} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByFactoryNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.LinkedServiceListResponse>; listByFactoryNext(nextPageLink: string, callback: ServiceCallback<models.LinkedServiceListResponse>): void; listByFactoryNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.LinkedServiceListResponse>): void; } /** * @class * Datasets * __NOTE__: An instance of this class is automatically created for an * instance of the DataFactoryManagementClient. */ export interface Datasets { /** * Lists datasets. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<DatasetListResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByFactoryWithHttpOperationResponse(resourceGroupName: string, factoryName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DatasetListResponse>>; /** * Lists datasets. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {DatasetListResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {DatasetListResponse} [result] - The deserialized result object if an error did not occur. * See {@link DatasetListResponse} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByFactory(resourceGroupName: string, factoryName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.DatasetListResponse>; listByFactory(resourceGroupName: string, factoryName: string, callback: ServiceCallback<models.DatasetListResponse>): void; listByFactory(resourceGroupName: string, factoryName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DatasetListResponse>): void; /** * Creates or updates a dataset. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} datasetName The dataset name. * * @param {object} dataset Dataset resource definition. * * @param {object} dataset.properties Dataset properties. * * @param {string} [dataset.properties.description] Dataset description. * * @param {object} [dataset.properties.structure] Columns that define the * structure of the dataset. Type: array (or Expression with resultType array), * itemType: DatasetDataElement. * * @param {object} dataset.properties.linkedServiceName Linked service * reference. * * @param {string} dataset.properties.linkedServiceName.referenceName Reference * LinkedService name. * * @param {object} [dataset.properties.linkedServiceName.parameters] Arguments * for LinkedService. * * @param {object} [dataset.properties.parameters] Parameters for dataset. * * @param {array} [dataset.properties.annotations] List of tags that can be * used for describing the Dataset. * * @param {object} [dataset.properties.folder] The folder that this Dataset is * in. If not specified, Dataset will appear at the root level. * * @param {string} [dataset.properties.folder.name] The name of the folder that * this Dataset is in. * * @param {string} dataset.properties.type Polymorphic Discriminator * * @param {object} [options] Optional Parameters. * * @param {string} [options.ifMatch] ETag of the dataset entity. Should only * be specified for update, for which it should match existing entity or can be * * for unconditional update. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<DatasetResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(resourceGroupName: string, factoryName: string, datasetName: string, dataset: models.DatasetResource, options?: { ifMatch? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DatasetResource>>; /** * Creates or updates a dataset. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} datasetName The dataset name. * * @param {object} dataset Dataset resource definition. * * @param {object} dataset.properties Dataset properties. * * @param {string} [dataset.properties.description] Dataset description. * * @param {object} [dataset.properties.structure] Columns that define the * structure of the dataset. Type: array (or Expression with resultType array), * itemType: DatasetDataElement. * * @param {object} dataset.properties.linkedServiceName Linked service * reference. * * @param {string} dataset.properties.linkedServiceName.referenceName Reference * LinkedService name. * * @param {object} [dataset.properties.linkedServiceName.parameters] Arguments * for LinkedService. * * @param {object} [dataset.properties.parameters] Parameters for dataset. * * @param {array} [dataset.properties.annotations] List of tags that can be * used for describing the Dataset. * * @param {object} [dataset.properties.folder] The folder that this Dataset is * in. If not specified, Dataset will appear at the root level. * * @param {string} [dataset.properties.folder.name] The name of the folder that * this Dataset is in. * * @param {string} dataset.properties.type Polymorphic Discriminator * * @param {object} [options] Optional Parameters. * * @param {string} [options.ifMatch] ETag of the dataset entity. Should only * be specified for update, for which it should match existing entity or can be * * for unconditional update. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {DatasetResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {DatasetResource} [result] - The deserialized result object if an error did not occur. * See {@link DatasetResource} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(resourceGroupName: string, factoryName: string, datasetName: string, dataset: models.DatasetResource, options?: { ifMatch? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.DatasetResource>; createOrUpdate(resourceGroupName: string, factoryName: string, datasetName: string, dataset: models.DatasetResource, callback: ServiceCallback<models.DatasetResource>): void; createOrUpdate(resourceGroupName: string, factoryName: string, datasetName: string, dataset: models.DatasetResource, options: { ifMatch? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DatasetResource>): void; /** * Gets a dataset. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} datasetName The dataset name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.ifNoneMatch] ETag of the dataset entity. Should * only be specified for get. If the ETag matches the existing entity tag, or * if * was provided, then no content will be returned. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<DatasetResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, factoryName: string, datasetName: string, options?: { ifNoneMatch? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DatasetResource>>; /** * Gets a dataset. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} datasetName The dataset name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.ifNoneMatch] ETag of the dataset entity. Should * only be specified for get. If the ETag matches the existing entity tag, or * if * was provided, then no content will be returned. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {DatasetResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {DatasetResource} [result] - The deserialized result object if an error did not occur. * See {@link DatasetResource} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, factoryName: string, datasetName: string, options?: { ifNoneMatch? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.DatasetResource>; get(resourceGroupName: string, factoryName: string, datasetName: string, callback: ServiceCallback<models.DatasetResource>): void; get(resourceGroupName: string, factoryName: string, datasetName: string, options: { ifNoneMatch? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DatasetResource>): void; /** * Deletes a dataset. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} datasetName The dataset name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, factoryName: string, datasetName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes a dataset. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} datasetName The dataset name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, factoryName: string, datasetName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, factoryName: string, datasetName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, factoryName: string, datasetName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Lists datasets. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<DatasetListResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByFactoryNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DatasetListResponse>>; /** * Lists datasets. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {DatasetListResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {DatasetListResponse} [result] - The deserialized result object if an error did not occur. * See {@link DatasetListResponse} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByFactoryNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.DatasetListResponse>; listByFactoryNext(nextPageLink: string, callback: ServiceCallback<models.DatasetListResponse>): void; listByFactoryNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DatasetListResponse>): void; } /** * @class * Pipelines * __NOTE__: An instance of this class is automatically created for an * instance of the DataFactoryManagementClient. */ export interface Pipelines { /** * Lists pipelines. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<PipelineListResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByFactoryWithHttpOperationResponse(resourceGroupName: string, factoryName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PipelineListResponse>>; /** * Lists pipelines. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {PipelineListResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {PipelineListResponse} [result] - The deserialized result object if an error did not occur. * See {@link PipelineListResponse} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByFactory(resourceGroupName: string, factoryName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.PipelineListResponse>; listByFactory(resourceGroupName: string, factoryName: string, callback: ServiceCallback<models.PipelineListResponse>): void; listByFactory(resourceGroupName: string, factoryName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PipelineListResponse>): void; /** * Creates or updates a pipeline. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} pipelineName The pipeline name. * * @param {object} pipelineParameter Pipeline resource definition. * * @param {string} [pipelineParameter.description] The description of the * pipeline. * * @param {array} [pipelineParameter.activities] List of activities in * pipeline. * * @param {object} [pipelineParameter.parameters] List of parameters for * pipeline. * * @param {object} [pipelineParameter.variables] List of variables for * pipeline. * * @param {number} [pipelineParameter.concurrency] The max number of concurrent * runs for the pipeline. * * @param {array} [pipelineParameter.annotations] List of tags that can be used * for describing the Pipeline. * * @param {object} [pipelineParameter.folder] The folder that this Pipeline is * in. If not specified, Pipeline will appear at the root level. * * @param {string} [pipelineParameter.folder.name] The name of the folder that * this Pipeline is in. * * @param {object} [options] Optional Parameters. * * @param {string} [options.ifMatch] ETag of the pipeline entity. Should only * be specified for update, for which it should match existing entity or can be * * for unconditional update. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<PipelineResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(resourceGroupName: string, factoryName: string, pipelineName: string, pipelineParameter: models.PipelineResource, options?: { ifMatch? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PipelineResource>>; /** * Creates or updates a pipeline. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} pipelineName The pipeline name. * * @param {object} pipelineParameter Pipeline resource definition. * * @param {string} [pipelineParameter.description] The description of the * pipeline. * * @param {array} [pipelineParameter.activities] List of activities in * pipeline. * * @param {object} [pipelineParameter.parameters] List of parameters for * pipeline. * * @param {object} [pipelineParameter.variables] List of variables for * pipeline. * * @param {number} [pipelineParameter.concurrency] The max number of concurrent * runs for the pipeline. * * @param {array} [pipelineParameter.annotations] List of tags that can be used * for describing the Pipeline. * * @param {object} [pipelineParameter.folder] The folder that this Pipeline is * in. If not specified, Pipeline will appear at the root level. * * @param {string} [pipelineParameter.folder.name] The name of the folder that * this Pipeline is in. * * @param {object} [options] Optional Parameters. * * @param {string} [options.ifMatch] ETag of the pipeline entity. Should only * be specified for update, for which it should match existing entity or can be * * for unconditional update. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {PipelineResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {PipelineResource} [result] - The deserialized result object if an error did not occur. * See {@link PipelineResource} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(resourceGroupName: string, factoryName: string, pipelineName: string, pipelineParameter: models.PipelineResource, options?: { ifMatch? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.PipelineResource>; createOrUpdate(resourceGroupName: string, factoryName: string, pipelineName: string, pipelineParameter: models.PipelineResource, callback: ServiceCallback<models.PipelineResource>): void; createOrUpdate(resourceGroupName: string, factoryName: string, pipelineName: string, pipelineParameter: models.PipelineResource, options: { ifMatch? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PipelineResource>): void; /** * Gets a pipeline. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} pipelineName The pipeline name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.ifNoneMatch] ETag of the pipeline entity. Should * only be specified for get. If the ETag matches the existing entity tag, or * if * was provided, then no content will be returned. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<PipelineResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, factoryName: string, pipelineName: string, options?: { ifNoneMatch? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PipelineResource>>; /** * Gets a pipeline. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} pipelineName The pipeline name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.ifNoneMatch] ETag of the pipeline entity. Should * only be specified for get. If the ETag matches the existing entity tag, or * if * was provided, then no content will be returned. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {PipelineResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {PipelineResource} [result] - The deserialized result object if an error did not occur. * See {@link PipelineResource} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, factoryName: string, pipelineName: string, options?: { ifNoneMatch? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.PipelineResource>; get(resourceGroupName: string, factoryName: string, pipelineName: string, callback: ServiceCallback<models.PipelineResource>): void; get(resourceGroupName: string, factoryName: string, pipelineName: string, options: { ifNoneMatch? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PipelineResource>): void; /** * Deletes a pipeline. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} pipelineName The pipeline name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, factoryName: string, pipelineName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes a pipeline. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} pipelineName The pipeline name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, factoryName: string, pipelineName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, factoryName: string, pipelineName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, factoryName: string, pipelineName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Creates a run of a pipeline. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} pipelineName The pipeline name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.referencePipelineRunId] The pipeline run * identifier. If run ID is specified the parameters of the the specified run * will be used to create a new run. * * @param {object} [options.parameters] Parameters of the pipeline run. These * parameters will be used only if the runId is not specified. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<CreateRunResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createRunWithHttpOperationResponse(resourceGroupName: string, factoryName: string, pipelineName: string, options?: { referencePipelineRunId? : string, parameters? : { [propertyName: string]: any }, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.CreateRunResponse>>; /** * Creates a run of a pipeline. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} pipelineName The pipeline name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.referencePipelineRunId] The pipeline run * identifier. If run ID is specified the parameters of the the specified run * will be used to create a new run. * * @param {object} [options.parameters] Parameters of the pipeline run. These * parameters will be used only if the runId is not specified. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {CreateRunResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {CreateRunResponse} [result] - The deserialized result object if an error did not occur. * See {@link CreateRunResponse} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createRun(resourceGroupName: string, factoryName: string, pipelineName: string, options?: { referencePipelineRunId? : string, parameters? : { [propertyName: string]: any }, customHeaders? : { [headerName: string]: string; } }): Promise<models.CreateRunResponse>; createRun(resourceGroupName: string, factoryName: string, pipelineName: string, callback: ServiceCallback<models.CreateRunResponse>): void; createRun(resourceGroupName: string, factoryName: string, pipelineName: string, options: { referencePipelineRunId? : string, parameters? : { [propertyName: string]: any }, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.CreateRunResponse>): void; /** * Lists pipelines. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<PipelineListResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByFactoryNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PipelineListResponse>>; /** * Lists pipelines. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {PipelineListResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {PipelineListResponse} [result] - The deserialized result object if an error did not occur. * See {@link PipelineListResponse} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByFactoryNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.PipelineListResponse>; listByFactoryNext(nextPageLink: string, callback: ServiceCallback<models.PipelineListResponse>): void; listByFactoryNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PipelineListResponse>): void; } /** * @class * PipelineRuns * __NOTE__: An instance of this class is automatically created for an * instance of the DataFactoryManagementClient. */ export interface PipelineRuns { /** * Query pipeline runs in the factory based on input filter conditions. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {object} filterParameters Parameters to filter the pipeline run. * * @param {string} [filterParameters.continuationToken] The continuation token * for getting the next page of results. Null for first page. * * @param {date} filterParameters.lastUpdatedAfter The time at or after which * the run event was updated in 'ISO 8601' format. * * @param {date} filterParameters.lastUpdatedBefore The time at or before which * the run event was updated in 'ISO 8601' format. * * @param {array} [filterParameters.filters] List of filters. * * @param {array} [filterParameters.orderBy] List of OrderBy option. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<PipelineRunsQueryResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ queryByFactoryWithHttpOperationResponse(resourceGroupName: string, factoryName: string, filterParameters: models.RunFilterParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PipelineRunsQueryResponse>>; /** * Query pipeline runs in the factory based on input filter conditions. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {object} filterParameters Parameters to filter the pipeline run. * * @param {string} [filterParameters.continuationToken] The continuation token * for getting the next page of results. Null for first page. * * @param {date} filterParameters.lastUpdatedAfter The time at or after which * the run event was updated in 'ISO 8601' format. * * @param {date} filterParameters.lastUpdatedBefore The time at or before which * the run event was updated in 'ISO 8601' format. * * @param {array} [filterParameters.filters] List of filters. * * @param {array} [filterParameters.orderBy] List of OrderBy option. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {PipelineRunsQueryResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {PipelineRunsQueryResponse} [result] - The deserialized result object if an error did not occur. * See {@link PipelineRunsQueryResponse} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ queryByFactory(resourceGroupName: string, factoryName: string, filterParameters: models.RunFilterParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.PipelineRunsQueryResponse>; queryByFactory(resourceGroupName: string, factoryName: string, filterParameters: models.RunFilterParameters, callback: ServiceCallback<models.PipelineRunsQueryResponse>): void; queryByFactory(resourceGroupName: string, factoryName: string, filterParameters: models.RunFilterParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PipelineRunsQueryResponse>): void; /** * Get a pipeline run by its run ID. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} runId The pipeline run identifier. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<PipelineRun>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, factoryName: string, runId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PipelineRun>>; /** * Get a pipeline run by its run ID. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} runId The pipeline run identifier. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {PipelineRun} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {PipelineRun} [result] - The deserialized result object if an error did not occur. * See {@link PipelineRun} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, factoryName: string, runId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.PipelineRun>; get(resourceGroupName: string, factoryName: string, runId: string, callback: ServiceCallback<models.PipelineRun>): void; get(resourceGroupName: string, factoryName: string, runId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PipelineRun>): void; /** * Cancel a pipeline run by its run ID. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} runId The pipeline run identifier. * * @param {object} [options] Optional Parameters. * * @param {boolean} [options.isRecursive] If true, cancel all the Child * pipelines that are triggered by the current pipeline. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ cancelWithHttpOperationResponse(resourceGroupName: string, factoryName: string, runId: string, options?: { isRecursive? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Cancel a pipeline run by its run ID. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} runId The pipeline run identifier. * * @param {object} [options] Optional Parameters. * * @param {boolean} [options.isRecursive] If true, cancel all the Child * pipelines that are triggered by the current pipeline. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ cancel(resourceGroupName: string, factoryName: string, runId: string, options?: { isRecursive? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<void>; cancel(resourceGroupName: string, factoryName: string, runId: string, callback: ServiceCallback<void>): void; cancel(resourceGroupName: string, factoryName: string, runId: string, options: { isRecursive? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; } /** * @class * ActivityRuns * __NOTE__: An instance of this class is automatically created for an * instance of the DataFactoryManagementClient. */ export interface ActivityRuns { /** * Query activity runs based on input filter conditions. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} runId The pipeline run identifier. * * @param {object} filterParameters Parameters to filter the activity runs. * * @param {string} [filterParameters.continuationToken] The continuation token * for getting the next page of results. Null for first page. * * @param {date} filterParameters.lastUpdatedAfter The time at or after which * the run event was updated in 'ISO 8601' format. * * @param {date} filterParameters.lastUpdatedBefore The time at or before which * the run event was updated in 'ISO 8601' format. * * @param {array} [filterParameters.filters] List of filters. * * @param {array} [filterParameters.orderBy] List of OrderBy option. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ActivityRunsQueryResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ queryByPipelineRunWithHttpOperationResponse(resourceGroupName: string, factoryName: string, runId: string, filterParameters: models.RunFilterParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ActivityRunsQueryResponse>>; /** * Query activity runs based on input filter conditions. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} runId The pipeline run identifier. * * @param {object} filterParameters Parameters to filter the activity runs. * * @param {string} [filterParameters.continuationToken] The continuation token * for getting the next page of results. Null for first page. * * @param {date} filterParameters.lastUpdatedAfter The time at or after which * the run event was updated in 'ISO 8601' format. * * @param {date} filterParameters.lastUpdatedBefore The time at or before which * the run event was updated in 'ISO 8601' format. * * @param {array} [filterParameters.filters] List of filters. * * @param {array} [filterParameters.orderBy] List of OrderBy option. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ActivityRunsQueryResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ActivityRunsQueryResponse} [result] - The deserialized result object if an error did not occur. * See {@link ActivityRunsQueryResponse} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ queryByPipelineRun(resourceGroupName: string, factoryName: string, runId: string, filterParameters: models.RunFilterParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ActivityRunsQueryResponse>; queryByPipelineRun(resourceGroupName: string, factoryName: string, runId: string, filterParameters: models.RunFilterParameters, callback: ServiceCallback<models.ActivityRunsQueryResponse>): void; queryByPipelineRun(resourceGroupName: string, factoryName: string, runId: string, filterParameters: models.RunFilterParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ActivityRunsQueryResponse>): void; } /** * @class * Triggers * __NOTE__: An instance of this class is automatically created for an * instance of the DataFactoryManagementClient. */ export interface Triggers { /** * Lists triggers. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<TriggerListResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByFactoryWithHttpOperationResponse(resourceGroupName: string, factoryName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.TriggerListResponse>>; /** * Lists triggers. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {TriggerListResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {TriggerListResponse} [result] - The deserialized result object if an error did not occur. * See {@link TriggerListResponse} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByFactory(resourceGroupName: string, factoryName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.TriggerListResponse>; listByFactory(resourceGroupName: string, factoryName: string, callback: ServiceCallback<models.TriggerListResponse>): void; listByFactory(resourceGroupName: string, factoryName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.TriggerListResponse>): void; /** * Creates or updates a trigger. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} triggerName The trigger name. * * @param {object} trigger Trigger resource definition. * * @param {object} trigger.properties Properties of the trigger. * * @param {string} [trigger.properties.description] Trigger description. * * @param {string} trigger.properties.type Polymorphic Discriminator * * @param {object} [options] Optional Parameters. * * @param {string} [options.ifMatch] ETag of the trigger entity. Should only * be specified for update, for which it should match existing entity or can be * * for unconditional update. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<TriggerResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(resourceGroupName: string, factoryName: string, triggerName: string, trigger: models.TriggerResource, options?: { ifMatch? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.TriggerResource>>; /** * Creates or updates a trigger. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} triggerName The trigger name. * * @param {object} trigger Trigger resource definition. * * @param {object} trigger.properties Properties of the trigger. * * @param {string} [trigger.properties.description] Trigger description. * * @param {string} trigger.properties.type Polymorphic Discriminator * * @param {object} [options] Optional Parameters. * * @param {string} [options.ifMatch] ETag of the trigger entity. Should only * be specified for update, for which it should match existing entity or can be * * for unconditional update. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {TriggerResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {TriggerResource} [result] - The deserialized result object if an error did not occur. * See {@link TriggerResource} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(resourceGroupName: string, factoryName: string, triggerName: string, trigger: models.TriggerResource, options?: { ifMatch? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.TriggerResource>; createOrUpdate(resourceGroupName: string, factoryName: string, triggerName: string, trigger: models.TriggerResource, callback: ServiceCallback<models.TriggerResource>): void; createOrUpdate(resourceGroupName: string, factoryName: string, triggerName: string, trigger: models.TriggerResource, options: { ifMatch? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.TriggerResource>): void; /** * Gets a trigger. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} triggerName The trigger name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.ifNoneMatch] ETag of the trigger entity. Should * only be specified for get. If the ETag matches the existing entity tag, or * if * was provided, then no content will be returned. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<TriggerResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, factoryName: string, triggerName: string, options?: { ifNoneMatch? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.TriggerResource>>; /** * Gets a trigger. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} triggerName The trigger name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.ifNoneMatch] ETag of the trigger entity. Should * only be specified for get. If the ETag matches the existing entity tag, or * if * was provided, then no content will be returned. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {TriggerResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {TriggerResource} [result] - The deserialized result object if an error did not occur. * See {@link TriggerResource} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, factoryName: string, triggerName: string, options?: { ifNoneMatch? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.TriggerResource>; get(resourceGroupName: string, factoryName: string, triggerName: string, callback: ServiceCallback<models.TriggerResource>): void; get(resourceGroupName: string, factoryName: string, triggerName: string, options: { ifNoneMatch? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.TriggerResource>): void; /** * Deletes a trigger. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} triggerName The trigger name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, factoryName: string, triggerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes a trigger. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} triggerName The trigger name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, factoryName: string, triggerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, factoryName: string, triggerName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, factoryName: string, triggerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Starts a trigger. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} triggerName The trigger name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ startWithHttpOperationResponse(resourceGroupName: string, factoryName: string, triggerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Starts a trigger. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} triggerName The trigger name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ start(resourceGroupName: string, factoryName: string, triggerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; start(resourceGroupName: string, factoryName: string, triggerName: string, callback: ServiceCallback<void>): void; start(resourceGroupName: string, factoryName: string, triggerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Stops a trigger. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} triggerName The trigger name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ stopWithHttpOperationResponse(resourceGroupName: string, factoryName: string, triggerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Stops a trigger. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} triggerName The trigger name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ stop(resourceGroupName: string, factoryName: string, triggerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; stop(resourceGroupName: string, factoryName: string, triggerName: string, callback: ServiceCallback<void>): void; stop(resourceGroupName: string, factoryName: string, triggerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Starts a trigger. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} triggerName The trigger name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginStartWithHttpOperationResponse(resourceGroupName: string, factoryName: string, triggerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Starts a trigger. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} triggerName The trigger name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginStart(resourceGroupName: string, factoryName: string, triggerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginStart(resourceGroupName: string, factoryName: string, triggerName: string, callback: ServiceCallback<void>): void; beginStart(resourceGroupName: string, factoryName: string, triggerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Stops a trigger. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} triggerName The trigger name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginStopWithHttpOperationResponse(resourceGroupName: string, factoryName: string, triggerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Stops a trigger. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} triggerName The trigger name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginStop(resourceGroupName: string, factoryName: string, triggerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginStop(resourceGroupName: string, factoryName: string, triggerName: string, callback: ServiceCallback<void>): void; beginStop(resourceGroupName: string, factoryName: string, triggerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Lists triggers. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<TriggerListResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByFactoryNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.TriggerListResponse>>; /** * Lists triggers. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {TriggerListResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {TriggerListResponse} [result] - The deserialized result object if an error did not occur. * See {@link TriggerListResponse} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByFactoryNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.TriggerListResponse>; listByFactoryNext(nextPageLink: string, callback: ServiceCallback<models.TriggerListResponse>): void; listByFactoryNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.TriggerListResponse>): void; } /** * @class * RerunTriggers * __NOTE__: An instance of this class is automatically created for an * instance of the DataFactoryManagementClient. */ export interface RerunTriggers { /** * Creates a rerun trigger. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} triggerName The trigger name. * * @param {string} rerunTriggerName The rerun trigger name. * * @param {object} rerunTumblingWindowTriggerActionParameters Rerun tumbling * window trigger action parameters. * * @param {date} rerunTumblingWindowTriggerActionParameters.startTime The start * time for the time period for which restatement is initiated. Only UTC time * is currently supported. * * @param {date} rerunTumblingWindowTriggerActionParameters.endTime The end * time for the time period for which restatement is initiated. Only UTC time * is currently supported. * * @param {number} rerunTumblingWindowTriggerActionParameters.maxConcurrency * The max number of parallel time windows (ready for execution) for which a * rerun is triggered. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<TriggerResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createWithHttpOperationResponse(resourceGroupName: string, factoryName: string, triggerName: string, rerunTriggerName: string, rerunTumblingWindowTriggerActionParameters: models.RerunTumblingWindowTriggerActionParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.TriggerResource>>; /** * Creates a rerun trigger. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} triggerName The trigger name. * * @param {string} rerunTriggerName The rerun trigger name. * * @param {object} rerunTumblingWindowTriggerActionParameters Rerun tumbling * window trigger action parameters. * * @param {date} rerunTumblingWindowTriggerActionParameters.startTime The start * time for the time period for which restatement is initiated. Only UTC time * is currently supported. * * @param {date} rerunTumblingWindowTriggerActionParameters.endTime The end * time for the time period for which restatement is initiated. Only UTC time * is currently supported. * * @param {number} rerunTumblingWindowTriggerActionParameters.maxConcurrency * The max number of parallel time windows (ready for execution) for which a * rerun is triggered. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {TriggerResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {TriggerResource} [result] - The deserialized result object if an error did not occur. * See {@link TriggerResource} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ create(resourceGroupName: string, factoryName: string, triggerName: string, rerunTriggerName: string, rerunTumblingWindowTriggerActionParameters: models.RerunTumblingWindowTriggerActionParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.TriggerResource>; create(resourceGroupName: string, factoryName: string, triggerName: string, rerunTriggerName: string, rerunTumblingWindowTriggerActionParameters: models.RerunTumblingWindowTriggerActionParameters, callback: ServiceCallback<models.TriggerResource>): void; create(resourceGroupName: string, factoryName: string, triggerName: string, rerunTriggerName: string, rerunTumblingWindowTriggerActionParameters: models.RerunTumblingWindowTriggerActionParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.TriggerResource>): void; /** * Starts a trigger. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} triggerName The trigger name. * * @param {string} rerunTriggerName The rerun trigger name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ startWithHttpOperationResponse(resourceGroupName: string, factoryName: string, triggerName: string, rerunTriggerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Starts a trigger. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} triggerName The trigger name. * * @param {string} rerunTriggerName The rerun trigger name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ start(resourceGroupName: string, factoryName: string, triggerName: string, rerunTriggerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; start(resourceGroupName: string, factoryName: string, triggerName: string, rerunTriggerName: string, callback: ServiceCallback<void>): void; start(resourceGroupName: string, factoryName: string, triggerName: string, rerunTriggerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Stops a trigger. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} triggerName The trigger name. * * @param {string} rerunTriggerName The rerun trigger name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ stopWithHttpOperationResponse(resourceGroupName: string, factoryName: string, triggerName: string, rerunTriggerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Stops a trigger. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} triggerName The trigger name. * * @param {string} rerunTriggerName The rerun trigger name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ stop(resourceGroupName: string, factoryName: string, triggerName: string, rerunTriggerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; stop(resourceGroupName: string, factoryName: string, triggerName: string, rerunTriggerName: string, callback: ServiceCallback<void>): void; stop(resourceGroupName: string, factoryName: string, triggerName: string, rerunTriggerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Cancels a trigger. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} triggerName The trigger name. * * @param {string} rerunTriggerName The rerun trigger name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ cancelWithHttpOperationResponse(resourceGroupName: string, factoryName: string, triggerName: string, rerunTriggerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Cancels a trigger. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} triggerName The trigger name. * * @param {string} rerunTriggerName The rerun trigger name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ cancel(resourceGroupName: string, factoryName: string, triggerName: string, rerunTriggerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; cancel(resourceGroupName: string, factoryName: string, triggerName: string, rerunTriggerName: string, callback: ServiceCallback<void>): void; cancel(resourceGroupName: string, factoryName: string, triggerName: string, rerunTriggerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Lists rerun triggers by an original trigger name. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} triggerName The trigger name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RerunTriggerListResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByTriggerWithHttpOperationResponse(resourceGroupName: string, factoryName: string, triggerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RerunTriggerListResponse>>; /** * Lists rerun triggers by an original trigger name. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} triggerName The trigger name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RerunTriggerListResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {RerunTriggerListResponse} [result] - The deserialized result object if an error did not occur. * See {@link RerunTriggerListResponse} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByTrigger(resourceGroupName: string, factoryName: string, triggerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RerunTriggerListResponse>; listByTrigger(resourceGroupName: string, factoryName: string, triggerName: string, callback: ServiceCallback<models.RerunTriggerListResponse>): void; listByTrigger(resourceGroupName: string, factoryName: string, triggerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RerunTriggerListResponse>): void; /** * Starts a trigger. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} triggerName The trigger name. * * @param {string} rerunTriggerName The rerun trigger name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginStartWithHttpOperationResponse(resourceGroupName: string, factoryName: string, triggerName: string, rerunTriggerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Starts a trigger. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} triggerName The trigger name. * * @param {string} rerunTriggerName The rerun trigger name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginStart(resourceGroupName: string, factoryName: string, triggerName: string, rerunTriggerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginStart(resourceGroupName: string, factoryName: string, triggerName: string, rerunTriggerName: string, callback: ServiceCallback<void>): void; beginStart(resourceGroupName: string, factoryName: string, triggerName: string, rerunTriggerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Stops a trigger. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} triggerName The trigger name. * * @param {string} rerunTriggerName The rerun trigger name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginStopWithHttpOperationResponse(resourceGroupName: string, factoryName: string, triggerName: string, rerunTriggerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Stops a trigger. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} triggerName The trigger name. * * @param {string} rerunTriggerName The rerun trigger name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginStop(resourceGroupName: string, factoryName: string, triggerName: string, rerunTriggerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginStop(resourceGroupName: string, factoryName: string, triggerName: string, rerunTriggerName: string, callback: ServiceCallback<void>): void; beginStop(resourceGroupName: string, factoryName: string, triggerName: string, rerunTriggerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Cancels a trigger. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} triggerName The trigger name. * * @param {string} rerunTriggerName The rerun trigger name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCancelWithHttpOperationResponse(resourceGroupName: string, factoryName: string, triggerName: string, rerunTriggerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Cancels a trigger. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {string} triggerName The trigger name. * * @param {string} rerunTriggerName The rerun trigger name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginCancel(resourceGroupName: string, factoryName: string, triggerName: string, rerunTriggerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginCancel(resourceGroupName: string, factoryName: string, triggerName: string, rerunTriggerName: string, callback: ServiceCallback<void>): void; beginCancel(resourceGroupName: string, factoryName: string, triggerName: string, rerunTriggerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Lists rerun triggers by an original trigger name. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RerunTriggerListResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByTriggerNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RerunTriggerListResponse>>; /** * Lists rerun triggers by an original trigger name. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RerunTriggerListResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {RerunTriggerListResponse} [result] - The deserialized result object if an error did not occur. * See {@link RerunTriggerListResponse} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByTriggerNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RerunTriggerListResponse>; listByTriggerNext(nextPageLink: string, callback: ServiceCallback<models.RerunTriggerListResponse>): void; listByTriggerNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RerunTriggerListResponse>): void; } /** * @class * TriggerRuns * __NOTE__: An instance of this class is automatically created for an * instance of the DataFactoryManagementClient. */ export interface TriggerRuns { /** * Query trigger runs. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {object} filterParameters Parameters to filter the pipeline run. * * @param {string} [filterParameters.continuationToken] The continuation token * for getting the next page of results. Null for first page. * * @param {date} filterParameters.lastUpdatedAfter The time at or after which * the run event was updated in 'ISO 8601' format. * * @param {date} filterParameters.lastUpdatedBefore The time at or before which * the run event was updated in 'ISO 8601' format. * * @param {array} [filterParameters.filters] List of filters. * * @param {array} [filterParameters.orderBy] List of OrderBy option. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<TriggerRunsQueryResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ queryByFactoryWithHttpOperationResponse(resourceGroupName: string, factoryName: string, filterParameters: models.RunFilterParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.TriggerRunsQueryResponse>>; /** * Query trigger runs. * * @param {string} resourceGroupName The resource group name. * * @param {string} factoryName The factory name. * * @param {object} filterParameters Parameters to filter the pipeline run. * * @param {string} [filterParameters.continuationToken] The continuation token * for getting the next page of results. Null for first page. * * @param {date} filterParameters.lastUpdatedAfter The time at or after which * the run event was updated in 'ISO 8601' format. * * @param {date} filterParameters.lastUpdatedBefore The time at or before which * the run event was updated in 'ISO 8601' format. * * @param {array} [filterParameters.filters] List of filters. * * @param {array} [filterParameters.orderBy] List of OrderBy option. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {TriggerRunsQueryResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {TriggerRunsQueryResponse} [result] - The deserialized result object if an error did not occur. * See {@link TriggerRunsQueryResponse} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ queryByFactory(resourceGroupName: string, factoryName: string, filterParameters: models.RunFilterParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.TriggerRunsQueryResponse>; queryByFactory(resourceGroupName: string, factoryName: string, filterParameters: models.RunFilterParameters, callback: ServiceCallback<models.TriggerRunsQueryResponse>): void; queryByFactory(resourceGroupName: string, factoryName: string, filterParameters: models.RunFilterParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.TriggerRunsQueryResponse>): void; }
the_stack
import {AfterViewInit, Component, ElementRef, Injector, OnDestroy, OnInit, ViewChild} from '@angular/core'; import {Alert} from '@common/util/alert.util'; import {StringUtil} from '@common/util/string.util'; import {EventBroadcaster} from '@common/event/event.broadcaster'; import {Field} from '@domain/data-preparation/pr-dataset'; import {SetTypeRule} from '@domain/data-preparation/prep-rules'; import {DataflowService} from '../../../../service/dataflow.service'; import {PrepSelectBoxComponent} from '../../../../../util/prep-select-box.component'; import {PrepSelectBoxCustomComponent} from '../../../../../util/prep-select-box-custom.component'; import {EditRuleComponent} from './edit-rule.component'; @Component({ selector: 'edit-rule-settype', templateUrl: './edit-rule-settype.component.html' }) export class EditRuleSettypeComponent extends EditRuleComponent implements OnInit, AfterViewInit, OnDestroy { /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Protected Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ public selectedFields: Field[] = []; public timestampFormats: any = []; public dsId: string = ''; public colDescs: any; public isTimestamp: boolean = false; public colTypes: any = []; public hasEditTimestamp: boolean = false; // for status T/F public isFocus: boolean = false; // Input Focus t/f public isTooltipShow: boolean = false; // Tooltip Show/Hide public selectedTimestamp: string = ''; public selectedType: string = ''; public typeList: string [] = ['long', 'double', 'string', 'boolean', 'timestamp', 'map', 'array']; public defaultIndex: number = -1; @ViewChild(PrepSelectBoxComponent) protected prepSelectBoxComponent: PrepSelectBoxComponent; @ViewChild(PrepSelectBoxCustomComponent) protected _custom: PrepSelectBoxCustomComponent; /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Constructor |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ constructor(protected broadCaster: EventBroadcaster, protected elementRef: ElementRef, protected injector: Injector, protected dataflowService: DataflowService) { super(elementRef, injector); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Override Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ public ngOnInit() { super.ngOnInit(); } public ngAfterViewInit() { super.ngAfterViewInit(); } public ngOnDestroy() { super.ngOnDestroy(); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Method - API |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * When type is selected * @param data */ public selectItem(data) { this.selectedType = data; if ('timestamp' === this.selectedType) { this.isTimestamp = true; this.getTimestampFormats(); } else if ('string' === this.selectedType) { if (-1 !== this._checkIfAtLeastOneColumnIsSelType(this.selectedFields, 'timestamp')) { this.isTimestamp = true; this.getTimestampFormats(); } else { this.isTimestamp = false; } } else { this.isTimestamp = false; } } /** * When timestamp format is selected * @param data */ public selectTimestamp(data) { this.selectedTimestamp = data.value; } /** * Set selected timestamp index in select box * @param {string} selectedTimestamp */ public setSelectedTimestamp(selectedTimestamp: string) { let tempnum: number = -1; try { if (selectedTimestamp !== null && selectedTimestamp !== '' && -1 !== this._timestampValueArray().indexOf(selectedTimestamp)) { tempnum = this._timestampValueArray().indexOf(selectedTimestamp); } } catch (error) { } this._custom.setSelectedItem(this.timestampFormats, selectedTimestamp, tempnum); } /** * Make timestamp list from formats from server * @param result */ public makeTimestampList(result: any) { const keyList = []; this.timestampFormats = []; // tslint:disable-next-line:forin for (const key in result) { // if (result.hasOwnProperty(key)) { keyList.push(key); // } } for (const i in result[keyList[0]]) { if (result[keyList[0]].hasOwnProperty(i)) { this.timestampFormats.push({value: i, isHover: false, matchValue: result[keyList[0]][i]}) } } } /** * Gets timestamp formats from the server */ private getTimestampFormats() { const cols = this.selectedFields.map((item) => { return item.name }); this.dataflowService.getTimestampFormatSuggestions(this.dsId, {colNames: cols}).then((result) => { if (!this.isNullOrUndefined(result)) { this.makeTimestampList(result); // timestamp --> string (max x) // string --> timestamp (max o) // timestamp --> timestamp (max x) if (!this.isNullOrUndefined(this.selectedTimestamp) && '' !== this.selectedTimestamp) { // } else if (cols.length > 0) { // 선택된 컬럼이 있다면 this.selectedTimestamp = ''; if ('string' === this.selectedType.toLowerCase()) { // timestamp -> string (set current column timestamp type) if ('timestamp' === this.selectedFields[0].type.toLowerCase()) { const idx = this._getFieldNameArray().indexOf(this.selectedFields[0].name); this.selectedTimestamp = this.colTypes[idx].timestampStyle; } } else if ('timestamp' === this.selectedType.toLowerCase()) { if ('timestamp' === this.selectedFields[0].type.toLowerCase()) { // timestamp -> timestamp (set current column timestamp type) const idx = this._getFieldNameArray().indexOf(this.selectedFields[0].name); this.selectedTimestamp = this.colTypes[idx].timestampStyle; } else if ('string' === this.selectedFields[0].type.toLowerCase()) { // string -> timestamp (suggestion) const max = this.timestampFormats.reduce((acc, curr) => Math.max(acc, curr.matchValue), this.timestampFormats[0].matchValue); const idx = this.timestampFormats.map((item) => { return item.matchValue }).findIndex((data) => { return data === max }); this.selectedTimestamp = this.timestampFormats[idx].value; } } } else { // 선택된 컬럼이 없다면 선택된 타임스탬프는 없다 this.selectedTimestamp = ''; } this.setSelectedTimestamp(this.selectedTimestamp); } }); } /** * Set rule string and returns it * @return {{command: string, col: string, ruleString: string}} */ public getRuleData(): { command: string, ruleString: string, uiRuleString: object } { // selected column if (0 === this.selectedFields.length) { Alert.warning(this.translateService.instant('msg.dp.alert.sel.col')); return undefined } // selected type if ('' === this.selectedType) { Alert.warning(this.translateService.instant('msg.dp.alert.sel.type')); return undefined; } let ruleString = 'settype col: ' + this.getColumnNamesInArray(this.selectedFields, true).toString() + ` type: ${this.selectedType}`; const copiedTimestamp: string = this.selectedTimestamp; // Timestamp if (this.isTimestamp && '' !== copiedTimestamp) { ruleString += ' format: '; const check: any = StringUtil.checkSingleQuote(this.selectedTimestamp, {isPairQuote: true, isWrapQuote: true}); if (check[0] === false) { Alert.warning(this.translateService.instant('msg.dp.alert.invalid.timestamp.val')); return undefined; } else { this.selectedTimestamp = check[1]; } ruleString += this.selectedTimestamp; } return { command: 'settype', ruleString: ruleString, uiRuleString: { name: 'settype', col: this.getColumnNamesInArray(this.selectedFields), type: this.selectedType, format: copiedTimestamp, isBuilder: true } }; } // function - getRuleData /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * Change fields * @param {{target: Field, isSelect: boolean, selectedList: Field[]}} data */ public changeFields(data: { target?: Field, isSelect?: boolean, selectedList: Field[] }) { // Selected columns this.selectedFields = data.selectedList; // 선택된 컬럼이 타임스탬프 타입이라면 new Type 셀렉트박스에서 타임스탬프를 지운다 let hasTimestampType = false; let isAllString = true; data.selectedList.forEach((item) => { if (item.type === 'TIMESTAMP') { hasTimestampType = true; } if (item.type !== 'STRING') { isAllString = false; } }); if (hasTimestampType) { // 타임스탬프 타입이 하나라도 있다면 splice const pos = this.typeList.indexOf('timestamp'); if (-1 !== pos) { this.typeList.splice(pos, 1); this.selectedType = ''; this.prepSelectBoxComponent.selectedItem = null; this.isTimestamp = false; } } else { // 타임스탬프 타입이 없다면 if (-1 === this.typeList.indexOf('timestamp')) { this.typeList.push('timestamp'); } } if (!this.hasEditTimestamp) { this.selectedTimestamp = ''; this.hasEditTimestamp = false; } if ('timestamp' === this.selectedType.toLowerCase()) { this.isTimestamp = true; this.getTimestampFormats(); } else if ('string' === this.selectedType.toLowerCase()) { if (-1 !== this._checkIfAtLeastOneColumnIsSelType(this.selectedFields, 'timestamp')) { this.isTimestamp = true; this.getTimestampFormats(); } else { this.isTimestamp = false; } } else { this.isTimestamp = false; } // 선택된 컬럼이 STRING인 경우에만 MAP, ARRAY로 settype 가능하다 if (!isAllString) { let pos = this.typeList.indexOf('map'); if (-1 !== pos) { this.typeList.splice(this.typeList.length - 1, 1); this.selectedType = ''; this.prepSelectBoxComponent.selectedItem = null; } pos = this.typeList.indexOf('array'); if (-1 !== pos) { this.typeList.splice(this.typeList.length - 1, 1); this.selectedType = ''; this.prepSelectBoxComponent.selectedItem = null; } } else { if (-1 === this.typeList.indexOf('map')) { this.typeList.push('map'); } if (-1 === this.typeList.indexOf('array')) { this.typeList.push('array'); } } this.typeList.sort(); } /** * Show/hide pattern tooltip * @param {boolean} isShow */ public showHidePatternLayer(isShow: boolean) { this.broadCaster.broadcast('EDIT_RULE_SHOW_HIDE_LAYER', {isShow: isShow}); this.isFocus = isShow; } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Protected Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * Before component is shown * @protected */ protected beforeShowComp() { // 선택된 컬럼이 타임스탬프일 경우 New type 에서 타임스탬프를 뺸다 if (-1 !== this._checkIfAtLeastOneColumnIsSelType(this.selectedFields, 'timestamp')) { const items = []; this.selectedFields.forEach((item) => { if (item.type.toLowerCase() === 'timestamp') { items.push(item); } }); if (items.length === this.selectedFields.length) { this.typeList.splice(this.typeList.length - 1, 1); } } } /** * After component is shown * @protected */ protected afterShowComp() { if (this.dsId && this.selectedType) { // 컨텍스트 메뉴 이용 this.defaultIndex = this.typeList.indexOf(this.selectedType.toLowerCase()); // Only get timestamp formats when it is timestamp type if (-1 !== this._checkIfAtLeastOneColumnIsSelType(this.selectedFields, 'timestamp') || this.selectedType.toLowerCase() === 'timestamp') { this.isTimestamp = true; this.getTimestampFormats(); } else { this.isTimestamp = false; } } } /** * parse rule string (When editing) * @param data ({ruleString : string, jsonRuleString : any}) */ protected parsingRuleString(data: { jsonRuleString: SetTypeRule }) { if (typeof data.jsonRuleString.col === 'string') { data.jsonRuleString.col = [data.jsonRuleString.col]; } // COLUMN const arrFields: string[] = data.jsonRuleString.col; this.selectedFields = arrFields.map(item => { if (item.length > 2 && item.startsWith('`') && item.endsWith('`')) { item = item.substring(1, item.length - 1); } return this.fields.find(orgItem => orgItem.name === item); }).filter(field => !!field); // TYPE this.selectedType = data.jsonRuleString.type.toLowerCase(); // TODO : this.defaultIndex = this.typeList.indexOf(this.selectedType); // FORMAT if ('timestamp' === this.selectedType || 'string' === this.selectedType) { if ('string' === this.selectedType) { // 선택된 모든 컬럼이 스트링일 떄는 타임스탬프 패턴 지정을 보여줄 필요 없다 if (-1 === this._checkIfAtLeastOneColumnIsSelType(this.selectedFields, 'timestamp')) { this.isTimestamp = false; return; } } this.isTimestamp = true; this.selectedTimestamp = data.jsonRuleString.format; this.hasEditTimestamp = true; // 편집 여부 } } /** * returns -1 if type does not exist in array * @param {Field[]} selectedFields * @param {string} type * @return {number} * @private */ private _checkIfAtLeastOneColumnIsSelType(selectedFields: Field[], type: string): number { return selectedFields.findIndex((item) => { return item.type === type.toUpperCase(); }); } /** * Get field name array * @return {string[]} * @private */ private _getFieldNameArray() { return this.fields.map((item) => { return item.name }); } /** * Get timestamp values in array * @private */ private _timestampValueArray() { return this.timestampFormats.map((item) => { return item.value; }); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ }
the_stack
import { action, computed, observable, reaction, autorun } from 'mobx'; import _ from 'lodash'; import { XYWH, XY, dummy as geom } from '~/domain/geometry'; import { StoreFrame } from '~/store/frame'; import ControlStore from '~/store/stores/controls'; import InteractionStore from '~/store/stores/interaction'; import ServiceStore from '~/store/stores/service'; import { ServiceCard } from '~/domain/service-map'; import { PlacementStrategy } from '~/domain/layout/abstract'; import { sizes } from '~/ui/vars'; export enum PlacementKind { FromWorld = 'FromWorld', ToWorld = 'ToWorld', AnotherNamespace = 'AnotherNamespace', InsideWithConnections = 'InsideWithConnections', InsideWithoutConnections = 'InsideWithoutConnections', OutsideManaged = 'OutsideManaged', } export interface PlacementMeta { kind: PlacementKind; card: ServiceCard; weight: number; } export interface PlacementEntry { kind: PlacementKind; card: ServiceCard; geometry: XYWH; } export interface EntriesGroup { entries: PlacementEntry[]; bbox: XYWH; } type PlacementFilter = (e: PlacementEntry) => boolean; export type Placement = Array<PlacementEntry>; export type CardsPlacement = Map<string, PlacementEntry>; export type CardsColumns = Map<string, PlacementMeta[][]>; // TODO: move it away from domain export class ServiceMapPlacementStrategy extends PlacementStrategy { @observable private controls: ControlStore; @observable private interactions: InteractionStore; @observable private services: ServiceStore; constructor(ctrl: ControlStore, intx: InteractionStore, svcs: ServiceStore) { super(); this.controls = ctrl; this.interactions = intx; this.services = svcs; reaction( () => this.cardsPlacement, () => this.releasePlacement(), ); } @computed public get bbox(): XYWH { let width = this.namespaceBBox ? this.namespaceBBox.w : 0; let height = this.namespaceBBox ? this.namespaceBBox.h : 0; let x = this.namespaceBBox ? this.namespaceBBox.x : 0; let y = this.namespaceBBox ? this.namespaceBBox.y : 0; this.cardsXYs.forEach((xy: XY, cardId: string) => { const wh = this.cardsWHs.get(cardId); if (wh == null) return; width = Math.max(width, xy.x + wh.w); height = Math.max(height, xy.y + wh.h); x = Math.min(x, xy.x); y = Math.min(y, xy.y); }); return new XYWH(x, y, width, height); } @computed public get namespaceBBox(): XYWH | null { return this.cardsBBox(e => { const one = e.kind === PlacementKind.InsideWithConnections; const two = e.kind === PlacementKind.InsideWithoutConnections; return one || two; }); } @action.bound public releasePlacement() { this.cardsPlacement.forEach((plcEntry: PlacementEntry, cardId: string) => { this.cardsXYs.set(cardId, plcEntry.geometry); }); } private cardsBBox(filterFn: PlacementFilter): XYWH | null { const bbox = geom.xywh(Infinity, Infinity); this.cardsPlacement.forEach((e: PlacementEntry) => { if (!filterFn(e)) return; const { x, y, w, h } = e.geometry; bbox.x = Math.min(bbox.x, x); bbox.y = Math.min(bbox.y, y); // Temporarily store here maxX, maxY for a while bbox.w = Math.max(bbox.w, x + w); bbox.h = Math.max(bbox.h, y + h); }); if (!bbox.isFinite) return null; bbox.w -= bbox.x; bbox.h -= bbox.y; return bbox; } @computed private get cardsPlacement(): CardsPlacement { const groups = this.placementGroups; const columns: Map<string, PlacementMeta[][]> = new Map(); const skipAnotherNs = !this.controls.showCrossNamespaceActivity; groups.forEach((placements: Set<PlacementMeta>, kind: PlacementKind) => { if (skipAnotherNs && kind === PlacementKind.AnotherNamespace) return; const kindColumns = this.buildPlacementColumns(placements); columns.set(kind, kindColumns); }); const placement = this.assignCoordinates(columns); return placement; } @computed private get placementGroups() { const index: Map<PlacementKind, Set<PlacementMeta>> = new Map(); const currentNs = this.controls.currentNamespace; this.services.cardsList.forEach((card: ServiceCard) => { const meta = this.getCardPlacementMeta(card, currentNs || undefined); const kindSet = index.get(meta.kind) ?? new Set(); const cards = kindSet.add(meta); index.set(meta.kind, cards); }); return index; } private getCardPlacementMeta(card: ServiceCard, ns?: string): PlacementMeta { const senders = this.connections.incomings.get(card.id); const receivers = this.connections.outgoings.get(card.id); const incomingsCount = senders?.size || 0; const outgoingsCount = receivers?.size || 0; // TODO: cache this ? const props = this.findSpecialInteractions(card); let kind = PlacementKind.InsideWithoutConnections; if (card.isHost || card.isRemoteNode) { kind = PlacementKind.FromWorld; } else if (card.isWorld) { kind = PlacementKind.FromWorld; kind = incomingsCount > 0 ? PlacementKind.ToWorld : kind; } else if (ns != null && card.namespace !== ns) { kind = PlacementKind.AnotherNamespace; } else if (incomingsCount > 0 || outgoingsCount > 0) { kind = PlacementKind.InsideWithConnections; } // Weight determines how many connections the card has. // If card has special interactions, it gains more weight. let weight = -incomingsCount + outgoingsCount; weight += props.hasWorldAsSender || props.hasHostAsSender ? 1000 : 0; weight += props.hasWorldAsReceiver ? 500 : 0; return { kind, card, weight, }; } private findSpecialInteractions(card: ServiceCard) { const senders = this.connections.incomings.get(card.id); const receivers = this.connections.outgoings.get(card.id); let hasWorldAsSender = false; let hasHostAsSender = false; let hasWorldAsReceiver = false; // prettier-ignore senders != null && senders.forEach((_, senderId) => { const sender = this.services.cardsMap.get(senderId); if (sender == null) return; hasWorldAsSender = hasWorldAsSender || sender.isWorld; hasHostAsSender = hasHostAsSender || sender.isHost; }); // prettier-ignore receivers != null && receivers.forEach((_, receiverId) => { const receiver = this.services.cardsMap.get(receiverId); if (receiver == null) return; hasWorldAsReceiver = hasWorldAsReceiver || receiver.isWorld; }); return { hasWorldAsReceiver, hasWorldAsSender, hasHostAsSender, }; } private buildPlacementColumns(plcs: Set<PlacementMeta>): PlacementMeta[][] { // Heaviest cards go first const sorted = Array.from(plcs).sort((a, b) => b.weight - a.weight); // Make columns to be more like square const maxCardsInColumn = Math.ceil(Math.sqrt(plcs.size)); const columns: PlacementMeta[][] = []; let curColumn: PlacementMeta[] = []; let curWeight: number | null = null; const flushColumn = () => { columns.push(curColumn); curColumn = []; }; sorted.forEach((plc: PlacementMeta, i: number) => { const maxCardsReached = curColumn.length >= maxCardsInColumn; const weightChanged = curWeight != null && plc.weight !== curWeight; if (maxCardsReached || weightChanged) flushColumn(); curWeight = plc.weight; curColumn.push(plc); if (i === sorted.length - 1) flushColumn(); }); return columns; } private assignCoordinates(columns: CardsColumns): CardsPlacement { const placement: CardsPlacement = new Map(); // prettier-ignore const top = this.alignColumns(columns, [ PlacementKind.ToWorld, ]); // prettier-ignore const middle = this.alignColumns(columns, [ PlacementKind.FromWorld, PlacementKind.InsideWithConnections, PlacementKind.InsideWithoutConnections, ]); // prettier-ignore const bottom = this.alignColumns(columns, [ PlacementKind.AnotherNamespace, ]); const toOutside = top.get(PlacementKind.ToWorld); const fromOutside = middle.get(PlacementKind.FromWorld); const insideWithConns = middle.get(PlacementKind.InsideWithConnections); const insideNoConns = middle.get(PlacementKind.InsideWithoutConnections); const anotherNs = bottom.get(PlacementKind.AnotherNamespace); const shiftEntries = (shift: XY, entries: PlacementEntry[]) => { entries.forEach((entry: PlacementEntry) => { entry.geometry.x += shift.x; entry.geometry.y += shift.y; }); }; const shiftToInsideCenter = (bbox: XYWH): XY => { const insideBBox = insideWithConns!.bbox; const relativeOffset = insideBBox.x - bbox.x; const bboxDiff = (insideBBox.w - bbox.w) / 2; const x = relativeOffset + bboxDiff; return { x, y: 0 }; }; // ToWorld cards aligned to middle of InsideWithConnections cards if (insideWithConns != null && toOutside != null) { shiftEntries(shiftToInsideCenter(toOutside.bbox), toOutside.entries); } if (toOutside != null) { // Shift all other cards below ToWorld cards const middleShift = { x: 0, y: toOutside.bbox.h + sizes.endpointVPadding, }; // prettier-ignore fromOutside && shiftEntries(middleShift, fromOutside.entries); insideWithConns && shiftEntries(middleShift, insideWithConns.entries); insideNoConns && shiftEntries(middleShift, insideNoConns.entries); } const buildShiftForBottom = (): XY => { const shift = { x: 0, y: 0 }; if (toOutside != null) { shift.y += toOutside.bbox.h + sizes.endpointVPadding; } let middleHeight = 0; if (fromOutside != null) { middleHeight = Math.max(middleHeight, fromOutside.bbox.h); } if (insideWithConns != null) { middleHeight = Math.max(middleHeight, insideWithConns.bbox.h); } if (insideNoConns != null) { middleHeight = Math.max(middleHeight, insideNoConns.bbox.h); } if (middleHeight > Number.EPSILON) { shift.y += middleHeight + sizes.endpointVPadding; } if (insideWithConns != null) { const insideShift = shiftToInsideCenter(anotherNs!.bbox); shift.x = insideShift.x; } return shift; }; if (anotherNs != null) { // Shift card from another namespace below others const shift = buildShiftForBottom(); shiftEntries(shift, anotherNs.entries); } const copyEntries = (entries: PlacementEntry[]) => { entries.forEach(entry => { placement.set(entry.card.id, entry); }); }; toOutside && copyEntries(toOutside.entries); fromOutside && copyEntries(fromOutside.entries); insideWithConns && copyEntries(insideWithConns.entries); insideNoConns && copyEntries(insideNoConns.entries); anotherNs && copyEntries(anotherNs.entries); return placement; } private alignColumns( cardsColumns: CardsColumns, kinds: PlacementKind[], ): Map<PlacementKind, EntriesGroup> { const alignment = new Map(); const columnHeights: Map<PlacementEntry[], number> = new Map(); const offset = { x: 0, y: 0 }; let entireHeight = 0; kinds.forEach(kind => { const columns = cardsColumns.get(kind); if (columns == null) return; const entries: PlacementEntry[] = []; const bbox = XYWH.fromArgs(offset.x, offset.y, 0, 0); columns.forEach((column: PlacementMeta[], ci: number) => { const columnEntries: PlacementEntry[] = []; let columnWidth = 0; let columnHeight = 0; offset.y = 0; column.forEach((meta: PlacementMeta, ri: number) => { let cardWH = this.cardsDimensions.get(meta.card.id); if (cardWH == null) { cardWH = this.defaultCardXYWH().wh; } const geomtry = XYWH.fromArgs(offset.x, offset.y, cardWH.w, cardWH.h); const entry = { card: meta.card, kind: meta.kind, geometry: geomtry, }; entries.push(entry); columnEntries.push(entry); columnWidth = Math.max(columnWidth, cardWH.w); columnHeight += cardWH.h + (ri === 0 ? 0 : sizes.endpointVPadding); offset.y += cardWH.h + sizes.endpointVPadding; }); columnHeights.set(columnEntries, columnHeight); offset.x += columnWidth + sizes.endpointHPadding; bbox.w += columnWidth + (ci === 0 ? 0 : sizes.endpointHPadding); bbox.h = Math.max(bbox.h, offset.y - sizes.endpointVPadding); entireHeight = Math.max(entireHeight, bbox.h); }); alignment.set(kind, { entries, bbox }); }); columnHeights.forEach((columnHeight: number, entries: PlacementEntry[]) => { if (entries.length === 0) return; const kind = entries[0].kind; const verticalOffset = (entireHeight - columnHeight) / 2; entries.forEach(entry => { entry.geometry.y += verticalOffset; }); }); return alignment; } @computed get connections() { return this.interactions.connections; } }
the_stack
import { PdfStreamWriter } from './../../input-output/pdf-stream-writer'; import { GetResourceEventHandler } from './../pdf-graphics'; import { PdfColorSpace } from './../enum'; import { PdfBrush } from './pdf-brush'; import { PointF, SizeF, RectangleF, Rectangle } from './../../drawing/pdf-drawing'; import { IPdfWrapper } from '../../../interfaces/i-pdf-wrapper'; import { PdfTransformationMatrix } from './../pdf-transformation-matrix'; import { DictionaryProperties } from './../../input-output/pdf-dictionary-properties'; import { PdfArray } from './../../primitives/pdf-array'; import { PdfName } from '../../../../src/implementation/primitives/pdf-name'; import { PdfNumber } from './../../primitives/pdf-number'; import { PdfGraphics } from './../pdf-graphics'; import { PdfResources} from './../pdf-resources'; import { PdfStream } from './../../primitives/pdf-stream'; import { PdfPage } from './../../pages/pdf-page'; import { IPdfPrimitive } from './../../../interfaces/i-pdf-primitives'; /** * `PdfTilingBrush` Implements a colored tiling brush. */ export class PdfTilingBrush extends PdfBrush implements IPdfWrapper { //Fields /** * Local variable to store rectanble box. * @private */ private mBox: Rectangle; /** * Local variable to store graphics. * @private */ private mGraphics: PdfGraphics; /** * Local variable to store brush Stream. * @private */ private brushStream: PdfStream; /** * Local variable to store brush Stream. * @private */ private tempBrushStream: PdfStream; /** * Local variable to store resources. * @private */ private mResources: PdfResources; /** * Local variable to store Stroking. * @private */ private mStroking: boolean = false; /** * Local variable to store the page. * @private */ private mPage: PdfPage; /** * Local variable to store the tile start location. * @private */ private mLocation: PointF = new PointF(0, 0); /** * Local variable to store the Matrix. * @private */ private mTransformationMatrix: PdfTransformationMatrix; /** * Local variable to store the dictionary properties. * @private */ private mDictionaryProperties : DictionaryProperties = new DictionaryProperties(); //Constructor /** * Initializes a new instance of the `PdfTilingBrush` class. * @public */ public constructor(rectangle: Rectangle) /** * Initializes a new instance of the `PdfTilingBrush` class. * @public */ public constructor(size: SizeF) /** * Initializes a new instance of the `PdfTilingBrush` class. * @public */ public constructor(size: SizeF, page: PdfPage) /** * Initializes a new instance of the `PdfTilingBrush` class. * @public */ public constructor(rectangle: Rectangle, page: PdfPage) /** * Initializes a new instance of the `PdfTilingBrush` class. * @public */ public constructor(arg1?: Rectangle|SizeF, arg2?: PdfPage) { super(); let rect : Rectangle = null; if (arg1 instanceof Rectangle) { rect = arg1; } else if (arg1 instanceof SizeF) { rect = new Rectangle(0, 0, arg1.width, arg1.height); } if (arg2 !== null && arg2 instanceof PdfPage) { this.mPage = arg2; } this.brushStream = new PdfStream(); this.mResources = new PdfResources(); this.brushStream.items.setValue(this.mDictionaryProperties.resources , this.mResources); this.setBox(rect); this.setObligatoryFields(); if (arg2 !== null && arg2 instanceof PdfPage) { this.mPage = arg2; this.graphics.colorSpace = arg2.document.colorSpace; } } /** * Initializes a new instance of the `PdfTilingBrush` class. * @private * @param rectangle The size of the smallest brush cell. * @param page The Current Page Object. * @param location The Tile start location. * @param matrix The matrix. */ private initialize(rectangle: Rectangle, page: PdfPage, location: PointF, matrix: PdfTransformationMatrix) : PdfTilingBrush { this.mPage = page; this.mLocation = location; this.mTransformationMatrix = matrix; this.tempBrushStream = this.brushStream; this.brushStream = new PdfStream(); let tempResource : PdfResources = new PdfResources(); this.brushStream.items.setValue(this.mDictionaryProperties.resources, tempResource); this.setBox(rectangle); this.setObligatoryFields(); return this; } //Properties /** * Location representing the start position of the tiles. * @public */ public get location(): PointF { return this.mLocation; } public set location(value: PointF) { this.mLocation = value; } /** * Sets the obligatory fields. * @private */ private setObligatoryFields() : void { this.brushStream.items.setValue(this.mDictionaryProperties.patternType, new PdfNumber(1)); // Tiling brush. this.brushStream.items.setValue(this.mDictionaryProperties.paintType, new PdfNumber(1)); // Coloured. this.brushStream.items.setValue(this.mDictionaryProperties.tilingType , new PdfNumber(1)); // Constant spacing. this.brushStream.items.setValue(this.mDictionaryProperties.xStep , new PdfNumber((this.mBox.right - this.mBox.left))); this.brushStream.items.setValue(this.mDictionaryProperties.yStep , new PdfNumber((this.mBox.bottom - this.mBox.top))); if ((this.mPage != null) && (this.mLocation != null)) { if ((this.mTransformationMatrix == null && typeof this.mTransformationMatrix === 'undefined')) { // Transform the tile origin to fit the location let tileTransform: number = (this.mPage.size.height % this.rectangle.size.height) - (this.mLocation.y); /* tslint:disable-next-line:max-line-length */ this.brushStream.items.setValue(this.mDictionaryProperties.matrix, new PdfArray([1, 0, 0, 1, this.mLocation.x, tileTransform])); } else { let tileTransform: number = 0; // Transform the tile origin to fit the location let elements: number[] = this.mTransformationMatrix.matrix.elements; if ((this.mPage.size.height > this.rectangle.size.height)) { tileTransform = (this.mTransformationMatrix.matrix.offsetY - (this.mPage.size.height % this.rectangle.size.height)); } else { tileTransform = ((this.mPage.size.height % this.rectangle.size.height) + this.mTransformationMatrix.matrix.offsetY); } this.brushStream.items.setValue(this.mDictionaryProperties.matrix, new PdfArray([ elements[0], elements[1], elements[2], elements[3], elements[4], tileTransform])); } } } /** * Sets the BBox coordinates. * @private */ private setBox(box: Rectangle) : void { this.mBox = box; let rect : RectangleF = new RectangleF(this.mBox.left, this.mBox.top, this.mBox.right, this.mBox.bottom); this.brushStream.items.setValue(this.mDictionaryProperties.bBox, PdfArray.fromRectangle(rect)); } //Properties /** * Gets the boundary box of the smallest brush cell. * @public */ public get rectangle(): Rectangle { return this.mBox; } /** * Gets the size of the smallest brush cell. * @public */ public get size(): SizeF { return this.mBox.size; } /** * Gets Graphics context of the brush. */ public get graphics(): PdfGraphics { if ((this.mGraphics == null && typeof this.mGraphics === 'undefined')) { let gr : GetResourceEventHandler = new GetResourceEventHandler(this); let g : PdfGraphics = new PdfGraphics(this.size, gr, this.brushStream); this.mGraphics = g; this.mResources = this.getResources(); this.mGraphics.initializeCoordinates(); } return this.mGraphics; } /** * Gets the resources and modifies the template dictionary. * @public */ public getResources() : PdfResources { return this.mResources; } /** * Gets or sets a value indicating whether this PdfTilingBrush * is used for stroking operations. */ public get stroking(): boolean { return this.mStroking; } public set stroking(value: boolean) { this.mStroking = value; } //PdfBrush methods /** * Creates a new copy of a brush. * @public */ public clone(): PdfBrush { let brush: PdfTilingBrush = this.initialize(this.rectangle, this.mPage, this.location, this.mTransformationMatrix); if ((this.mTransformationMatrix != null) && (this.mTransformationMatrix.matrix != null)) { /* tslint:disable-next-line:max-line-length */ brush.brushStream.items.setValue(this.mDictionaryProperties.matrix , new PdfArray(this.mTransformationMatrix.matrix.elements)); } brush.brushStream.data = this.tempBrushStream.data; brush.mResources = new PdfResources(this.mResources); brush.brushStream.items.setValue(this.mDictionaryProperties.resources, brush.mResources); return brush; } /** * Monitors the changes of the brush and modify PDF state respectfully. * @param brush The brush * @param streamWriter The stream writer * @param getResources The get resources delegate. * @param saveChanges if set to true the changes should be saved anyway. * @param currentColorSpace The current color space. */ /* tslint:disable-next-line:max-line-length */ public monitorChanges(brush: PdfBrush, streamWriter: PdfStreamWriter, getResources: GetResourceEventHandler, saveChanges: boolean, currentColorSpace: PdfColorSpace): boolean { let diff: boolean = false; if (brush !== this) { // Set the Pattern colour space. streamWriter.setColorSpace('Pattern', this.mStroking); // Set the pattern for non-stroking operations. let resources1 : PdfResources = getResources.getResources(); let name1 : PdfName = resources1.getName(this); streamWriter.setColourWithPattern(null, name1, this.mStroking); diff = true; } else if (brush instanceof PdfTilingBrush) { // Set the /Pattern colour space. streamWriter.setColorSpace('Pattern', this.mStroking); // Set the pattern for non-stroking operations. let resources : PdfResources = getResources.getResources(); let name: PdfName = resources.getName(this); streamWriter.setColourWithPattern(null, name, this.mStroking); diff = true; } return diff; } /** * Resets the changes, which were made by the brush. * In other words resets the state to the initial one. * @param streamWriter The stream writer. */ public resetChanges(streamWriter: PdfStreamWriter) : void { // We shouldn't do anything to reset changes. // All changes will be reset automatically by setting a new colour space. } /* tslint:enable */ // IPdfWrapper Members /** * Gets the `element`. * @public */ public get element() : IPdfPrimitive { return this.brushStream; } }
the_stack
import React, { useEffect, useRef } from 'react' import { act, render } from '@react-facet/dom-fiber-testing-library' import { useFacetMap } from './useFacetMap' import { NO_VALUE, Facet } from '../types' import { useFacetEffect } from './useFacetEffect' import { createFacet } from '../facet' import { useFacetState } from './useFacetState' it('triggers the map once for each multiple consumers', () => { const mapFn = jest.fn().mockReturnValue('map-value') const TestComponent = () => { const [valueFacet] = useFacetState('test-value') const mappedValueFacet = useFacetMap(mapFn, [], [valueFacet]) return ( <div> <fast-text text={mappedValueFacet} /> <fast-text text={mappedValueFacet} /> </div> ) } render(<TestComponent />) expect(mapFn).toHaveBeenCalledTimes(2) }) describe('multiple dependencies', () => { it('maps values from multiple facets', () => { const facetA = createFacet({ initialValue: 'A' }) const facetB = createFacet({ initialValue: 'B' }) const ComponentWithFacetEffect = () => { const adaptValue = useFacetMap((a, b) => `${a}-${b}`, [], [facetA, facetB]) return ( <span> <fast-text text={adaptValue} /> </span> ) } const dom = render(<ComponentWithFacetEffect />) expect(dom.container.textContent).toBe('A-B') // We verify that if a facet updates, it re-renders act(() => { facetA.set('Y') }) expect(dom.container.textContent).toBe('Y-B') }) it('supports optional default value', () => { const facetA = createFacet<string>({ initialValue: NO_VALUE }) const facetB = createFacet<string>({ initialValue: NO_VALUE }) const ComponentWithFacetEffect = () => { const adaptValue = useFacetMap((a, b) => `${a}-${b}`, [], [facetA, facetB]) return ( <span> <fast-text text={adaptValue} /> </span> ) } const dom = render(<ComponentWithFacetEffect />) expect(dom.container.textContent).toBe('') // We verify that if a facet updates, it re-renders act(() => { facetA.set('Y') }) expect(dom.container.textContent).toBe('') act(() => { facetB.set('X') }) expect(dom.container.textContent).toBe('Y-X') }) it('accepts an equality check and does not fire again if equal', () => { const facetA = createFacet({ initialValue: ['A'] }) const facetB = createFacet({ initialValue: 'B' }) const nameEqualityCheck = () => { let previousName: string return (current: { name: string }) => { if (current.name !== previousName) { previousName = current.name return false } return true } } const mock = jest.fn() const ComponentWithFacetEffect = () => { const adaptValue = useFacetMap(([a], b) => ({ name: `${a}-${b}` }), [], [facetA, facetB], nameEqualityCheck) useFacetEffect( (value) => { mock(value.name) }, [], [adaptValue], ) return null } render(<ComponentWithFacetEffect />) expect(mock).toHaveBeenCalledWith('A-B') mock.mockClear() // We verify that if a facet updates, it re-renders act(() => { facetA.set(['Y']) }) expect(mock).toHaveBeenCalledWith('Y-B') mock.mockClear() // We verify that if a facet updates, it re-renders act(() => { facetA.set(['Y']) }) expect(mock).not.toHaveBeenCalled() }) it('does not fire change notifications for string primitive', () => { const facetA = createFacet({ initialValue: ['A'] }) const facetB = createFacet({ initialValue: 'B' }) const mock = jest.fn() const ComponentWithFacetEffect = () => { const adaptValue = useFacetMap(([a], b) => `${a}-${b}`, [], [facetA, facetB]) useFacetEffect( (value) => { mock(value) }, [], [adaptValue], ) return null } render(<ComponentWithFacetEffect />) expect(mock).toHaveBeenCalledWith('A-B') mock.mockClear() // We verify that if a facet updates, it re-renders act(() => { facetA.set(['Y']) }) expect(mock).toHaveBeenCalledWith('Y-B') mock.mockClear() // We verify that if a facet updates, it re-renders act(() => { facetA.set(['Y']) }) expect(mock).not.toHaveBeenCalled() }) it('does not fire change notifications for number primitive', () => { const facetA = createFacet({ initialValue: [1] }) const facetB = createFacet({ initialValue: 2 }) const mock = jest.fn() const ComponentWithFacetEffect = () => { const adaptValue = useFacetMap(([a], b) => a + b, [], [facetA, facetB]) useFacetEffect( (value) => { mock(value) }, [], [adaptValue], ) return null } render(<ComponentWithFacetEffect />) expect(mock).toHaveBeenCalledWith(3) mock.mockClear() // We verify that if a facet updates, it re-renders act(() => { facetA.set([20]) }) expect(mock).toHaveBeenCalledWith(22) mock.mockClear() // We verify that if a facet updates, it re-renders act(() => { facetA.set([20]) }) expect(mock).not.toHaveBeenCalled() }) it('does not fire change notifications for boolean primitive', () => { const facetA = createFacet({ initialValue: [false] }) const facetB = createFacet({ initialValue: true }) const mock = jest.fn() const ComponentWithFacetEffect = () => { const adaptValue = useFacetMap(([a], b) => a && b, [], [facetA, facetB]) useFacetEffect( (value) => { mock(value) }, [], [adaptValue], ) return null } render(<ComponentWithFacetEffect />) expect(mock).toHaveBeenCalledWith(false) mock.mockClear() // We verify that if a facet updates, it re-renders act(() => { facetA.set([true]) }) expect(mock).toHaveBeenCalledWith(true) mock.mockClear() // We verify that if a facet updates, it re-renders act(() => { facetA.set([true]) }) expect(mock).not.toHaveBeenCalled() }) }) describe('single dependency', () => { it('triggers when there is a change in the facet', () => { const demoFacet = createFacet({ initialValue: 'initial value' }) const callback = jest.fn() const ComponentWithFacetEffect = () => { const adaptValue = useFacetMap((value) => value + value, [], [demoFacet]) useEffect(() => { adaptValue.observe((value) => { callback(value) }) }, [adaptValue]) return null } const scenario = <ComponentWithFacetEffect /> render(scenario) expect(callback).toHaveBeenCalledWith('initial valueinitial value') }) it('properly memoizes the returned facet', () => { const demoFacet = createFacet({ initialValue: 'initial value' }) const TestComponent = () => { const previousMappedFacetRef = useRef<Facet<string>>() const mappedFacet = useFacetMap((value) => value, [], [demoFacet]) // Check if it is a second render if (previousMappedFacetRef.current) { // check if previous and current mappedFacet are the same instance if (previousMappedFacetRef.current !== mappedFacet) { throw new Error('Facet instance has change') } } previousMappedFacetRef.current = mappedFacet return null } const { rerender } = render(<TestComponent />) // Render a second time to check (inside the component) // if the instance is the same rerender(<TestComponent />) }) it('properly memoizes the returned facet for multiple dependencies', () => { const demoFacet = createFacet({ initialValue: 'initial value' }) const secondFacet = createFacet({ initialValue: 'initial value' }) const TestComponent = () => { const previousMappedFacetRef = useRef<Facet<string>>() const mappedFacet = useFacetMap((value) => value, [], [demoFacet, secondFacet]) // Check if it is a second render if (previousMappedFacetRef.current) { // check if previous and current mappedFacet are the same instance if (previousMappedFacetRef.current !== mappedFacet) { throw new Error('Facet instance has change') } } previousMappedFacetRef.current = mappedFacet return null } const { rerender } = render(<TestComponent />) // Render a second time to check (inside the component) // if the instance is the same rerender(<TestComponent />) }) it('supports optional default value for single dependency', () => { const facetA = createFacet<string>({ initialValue: NO_VALUE }) const ComponentWithFacetEffect = () => { const adaptValue = useFacetMap((a) => a, [], [facetA]) return ( <span> <fast-text text={adaptValue} /> </span> ) } const dom = render(<ComponentWithFacetEffect />) expect(dom.container.textContent).toBe('') // We verify that if a facet updates, it re-renders act(() => { facetA.set('Y') }) expect(dom.container.textContent).toBe('Y') }) it('accepts an equality check and does not fire again if equal', () => { const facetA = createFacet({ initialValue: [{ name: 'A' }] }) const nameEqualityCheck = () => { let previousName: string return (current: { name: string }) => { if (current.name !== previousName) { previousName = current.name return false } return true } } const mock = jest.fn() const ComponentWithFacetEffect = () => { const adaptValue = useFacetMap(([a]) => a, [], [facetA], nameEqualityCheck) useFacetEffect( (value) => { mock(value.name) }, [], [adaptValue], ) return null } render(<ComponentWithFacetEffect />) expect(mock).toHaveBeenCalledWith('A') mock.mockClear() // We verify that if a facet updates, it re-renders act(() => { facetA.set([{ name: 'Y' }]) }) expect(mock).toHaveBeenCalledWith('Y') mock.mockClear() // We verify that if a facet updates with the same value, it should not re-render act(() => { facetA.set([{ name: 'Y' }]) }) expect(mock).not.toHaveBeenCalled() }) it('does not fire change notifications for string primitive', () => { const facetA = createFacet({ initialValue: [{ name: 'A' }] }) const mock = jest.fn() const ComponentWithFacetEffect = () => { const adaptValue = useFacetMap(([a]) => a.name, [], [facetA]) useFacetEffect( (value) => { mock(value) }, [], [adaptValue], ) return null } render(<ComponentWithFacetEffect />) expect(mock).toHaveBeenCalledWith('A') mock.mockClear() // We verify that if a facet updates, it re-renders act(() => { facetA.set([{ name: 'Y' }]) }) expect(mock).toHaveBeenCalledWith('Y') mock.mockClear() // We verify that if a facet updates, it re-renders act(() => { facetA.set([{ name: 'Y' }]) }) expect(mock).not.toHaveBeenCalled() }) it('does not fire change notifications for number primitive', () => { const facetA = createFacet({ initialValue: [{ name: 1 }] }) const mock = jest.fn() const ComponentWithFacetEffect = () => { const adaptValue = useFacetMap(([a]) => a.name, [], [facetA]) useFacetEffect( (value) => { mock(value) }, [], [adaptValue], ) return null } render(<ComponentWithFacetEffect />) expect(mock).toHaveBeenCalledWith(1) mock.mockClear() // We verify that if a facet updates, it re-renders act(() => { facetA.set([{ name: 2 }]) }) expect(mock).toHaveBeenCalledWith(2) mock.mockClear() // We verify that if a facet updates, it re-renders act(() => { facetA.set([{ name: 2 }]) }) expect(mock).not.toHaveBeenCalled() }) it('does not fire change notifications for boolean primitive', () => { const facetA = createFacet({ initialValue: [{ name: true }] }) const mock = jest.fn() const ComponentWithFacetEffect = () => { const adaptValue = useFacetMap(([a]) => a.name, [], [facetA]) useFacetEffect( (value) => { mock(value) }, [], [adaptValue], ) return null } render(<ComponentWithFacetEffect />) expect(mock).toHaveBeenCalledWith(true) mock.mockClear() // We verify that if a facet updates, it re-renders act(() => { facetA.set([{ name: false }]) }) expect(mock).toHaveBeenCalledWith(false) mock.mockClear() // We verify that if a facet updates, it re-renders act(() => { facetA.set([{ name: false }]) }) expect(mock).not.toHaveBeenCalled() }) })
the_stack
import { util } from "../helpers/util.ts"; import { ZodTypes } from "../ZodTypes.ts"; import { ParseParams, ZodParser } from "../parser.ts"; import { ZodCustomIssue, ZodError, ZodIssueCode, MakeErrorData, } from "../ZodError.ts"; import { ZodArray, ZodNullable, ZodNullableType, ZodOptional, ZodOptionalType, ZodTransformer, } from "../index.ts"; // import { outputSchema } from "../output-schema"; type CustomErrorParams = Partial<util.Omit<ZodCustomIssue, "code">>; type InternalCheck<T> = { type: "check"; check: (arg: T, ctx: RefinementCtx) => any; // refinementError: (arg: T) => MakeErrorData; }; type Mod<T> = { type: "mod"; mod: (arg: T) => any; // refinementError: (arg: T) => MakeErrorData; }; type Effect<T> = InternalCheck<T> | Mod<T>; // type Check<T> = { // check: (arg: T) => any; // path?: (string | number)[]; // // message?: string; // // params?: {[k:string]:any} // } & util.Omit<CustomError, 'code' | 'path'>; // type CustomErrorParams = Partial<util.Omit<ZodCustomIssue, "code">>; // type Check<T> = { // check: (arg: T) => any; // refinementError: (arg: T) => CustomErrorParams; // }; // export function declareZodType() {} export interface ZodTypeDef { t: ZodTypes; effects?: Effect<any>[]; // mods?: Mod<any>[]; accepts?: ZodType<any, any>; } export abstract class ZodType< Output, Def extends ZodTypeDef = ZodTypeDef, Input = Output > { readonly _type!: Output; readonly _output!: Output; readonly _input!: Input; readonly _def!: Def; // get inputSchema(): ZodTypeAny = this; // outputSchema: ZodTypeAny = this; // = ()=>{ // return this; // } // outputSchema = () => { // return this; // }; parse: (x: unknown, params?: ParseParams) => Output = ZodParser(this); safeParse: ( x: unknown, params?: ParseParams ) => { success: true; data: Output } | { success: false; error: ZodError } = ( data, params ) => { try { const parsed = this.parse(data, params); return { success: true, data: parsed }; } catch (err) { if (err instanceof ZodError) { return { success: false, error: err }; } throw err; } }; parseAsync: (x: unknown, params?: ParseParams) => Promise<Output> = async ( value, params ) => { return await this.parse(value, { ...params, async: true }); }; safeParseAsync: ( x: unknown, params?: ParseParams ) => Promise< { success: true; data: Output } | { success: false; error: ZodError } > = async (data, params) => { try { const parsed = await this.parseAsync(data, params); return { success: true, data: parsed }; } catch (err) { if (err instanceof ZodError) { return { success: false, error: err }; } throw err; } }; spa = this.safeParseAsync; // is(u: Input): u is Input { // try { // this.parse(u as any); // return true; // } catch (err) { // return false; // } // } // check(u: unknown): u is Input { // try { // this.parse(u as any); // return true; // } catch (err) { // return false; // } // } /** The .is method has been removed in Zod 3. For details see https://github.com/colinhacks/zod/tree/v3. */ is: never; /** The .check method has been removed in Zod 3. For details see https://github.com/colinhacks/zod/tree/v3. */ check: never; refine = <Func extends (arg: Output) => any>( check: Func, message: | string | CustomErrorParams | ((arg: Output) => CustomErrorParams) = "Invalid value." ) => { if (typeof message === "string") { return this._refinement((val, ctx) => { const result = check(val); const setError = () => ctx.addIssue({ code: ZodIssueCode.custom, message, }); if (result instanceof Promise) { return result.then((data) => { if (!data) setError(); }); } if (!result) { setError(); return result; } }); } if (typeof message === "function") { return this._refinement((val, ctx) => { const result = check(val); const setError = () => ctx.addIssue({ code: ZodIssueCode.custom, ...message(val), }); if (result instanceof Promise) { return result.then((data) => { if (!data) setError(); }); } if (!result) { setError(); return result; } }); } return this._refinement((val, ctx) => { const result = check(val); const setError = () => ctx.addIssue({ code: ZodIssueCode.custom, ...message, }); if (result instanceof Promise) { return result.then((data) => { if (!data) setError(); }); } if (!result) { setError(); return result; } }); }; refinement = ( check: (arg: Output) => any, refinementData: | MakeErrorData | ((arg: Output, ctx: RefinementCtx) => MakeErrorData) ) => { return this._refinement((val, ctx) => { if (!check(val)) { ctx.addIssue( typeof refinementData === "function" ? refinementData(val, ctx) : refinementData ); } }); }; _refinement: (refinement: InternalCheck<Output>["check"]) => this = ( refinement ) => { return new (this as any).constructor({ ...this._def, effects: [ ...(this._def.effects || []), { type: "check", check: refinement }, ], }) as this; }; constructor(def: Def) { this._def = def; // this.is = this.is.bind(this); // this.check = this.check.bind(this); this.transform = this.transform.bind(this); this.default = this.default.bind(this); } abstract toJSON: () => object; optional: () => ZodOptionalType<this> = () => ZodOptional.create(this); or = this.optional; nullable: () => ZodNullableType<this> = () => { return ZodNullable.create(this) as any; }; array: () => ZodArray<this> = () => ZodArray.create(this); // transform< // This extends this, // U extends ZodType<any>, // Tx extends (arg: This["_output"]) => U["_input"] | Promise<U["_input"]> // >(input: U, transformer: Tx): ZodTransformer<This, U>; // transform< // This extends this, // Tx extends ( // arg: This["_output"] // ) => This["_input"] | Promise<This["_input"]> // >(transformer: Tx): ZodTransformer<This, This>; // transform(input: any, transformer?: any) { // if (transformer) { // return ZodTransformer.create(this as any, input, transformer) as any; // } // return ZodTransformer.create(this as any, outputSchema(this), input) as any; // } // default< // T extends Input = Input, // Opt extends ReturnType<this["optional"]> = ReturnType<this["optional"]> // >(def: T): ZodTransformer<Opt, this>; // default< // T extends (arg: this) => Input, // Opt extends ReturnType<this["optional"]> = ReturnType<this["optional"]> // >(def: T): ZodTransformer<Opt, this>; // default(def: any) { // return ZodTransformer.create(this.optional(), this, (x: any) => { // return x === undefined // ? typeof def === "function" // ? def(this) // : def // : x; // }) as any; // } // transform<This extends this, Out, U extends ZodType<any>>( // input: U, // transformer: (arg: Output) => Out | Promise<Out> // ): This extends ZodTransformer<infer T, any> // ? ZodTransformer<T, Out> // : ZodTransformer<This, Out>; // transform<Out, This extends this>( // transformer: (arg: Output) => Out | Promise<Out> // ): This extends ZodTransformer<infer T, any> // ? ZodTransformer<T, Out> // : ZodTransformer<This, Out>; transform: <Out, This extends this>( transformer: (arg: Output) => Out | Promise<Out> ) => This extends ZodTransformer<infer T, any> ? ZodTransformer<T, Out> : ZodTransformer<This, Out> = (mod) => { // if(typeof first === "function") // const mod = typeof first === "function" ? first : second; // const newSchema = this.transform(txFunc); // if (!second) return newSchema; // if (typeof mod !== "function") // throw new Error("Must provide a function to the .transform() method"); let returnType; if (this instanceof ZodTransformer) { returnType = new (this as any).constructor({ ...this._def, effects: [...(this._def.effects || []), { type: "mod", mod }], }) as any; } else { returnType = new ZodTransformer({ // ...this._def, t: ZodTypes.transformer, schema: this, effects: [{ type: "mod", mod }], }) as any; } return returnType; }; // if (!second) { // return returnType; // } else { // return returnType.refine( // (val: any) => { // return first.parse(val); // }, // { message: "Parsing error!" } // ); // } // }; prependMod = <Out>( mod: (arg: Output) => Out | Promise<Out> ): ZodType<Out, Def, Input> => { return new (this as any).constructor({ ...this._def, effects: [{ type: "mod", mod }, ...(this._def.effects || [])], }) as any; }; clearEffects = <Out>(): ZodType<Out, Def, Input> => { return new (this as any).constructor({ ...this._def, effects: [], }) as any; }; setEffects = <Out>(effects: Effect<any>[]): ZodType<Out, Def, Input> => { return new (this as any).constructor({ ...this._def, effects, }) as any; }; default<T extends Input, This extends this = this>( def: T ): ZodTransformer<ZodOptional<This>, Input>; default<T extends (arg: this) => Input, This extends this = this>( def: T ): ZodTransformer<ZodOptional<This>, Input>; // default< // T extends (arg: this) => Input, // Opt extends ReturnType<this["optional"]> = ReturnType<this["optional"]> // >(def: T): ZodTransformer<Opt, this>; default(def: any) { return this.optional().transform((val: any) => { const defaultVal = typeof def === "function" ? def(this) : def; return typeof val !== "undefined" ? val : defaultVal; }) as any; } isOptional: () => boolean = () => this.safeParse(undefined).success; isNullable: () => boolean = () => this.safeParse(null).success; } export type RefinementCtx = { addIssue: (arg: MakeErrorData) => void; path: (string | number)[]; }; export type ZodRawShape = { [k: string]: ZodTypeAny }; export type TypeOf<T extends ZodType<any>> = T["_output"]; export type input<T extends ZodType<any>> = T["_input"]; export type output<T extends ZodType<any>> = T["_output"]; export type infer<T extends ZodType<any>> = T["_output"]; export type ZodTypeAny = ZodType<any, any, any>;
the_stack
import { Response, Request } from "express"; import ChunkInterface from "./utils/ChunkInterface"; import { UserInterface } from "../../models/user"; import NotAuthorizedError from "../../utils/NotAuthorizedError"; import NotFoundError from "../../utils/NotFoundError"; import crypto from "crypto"; import getBusboyData from "./utils/getBusboyData"; import videoChecker from "../../utils/videoChecker"; import fs from "fs"; import uuid from "uuid"; import awaitUploadStreamFS from "./utils/awaitUploadStreamFS"; import File, { FileInterface } from "../../models/file"; import getFileSize from "./utils/getFileSize"; import DbUtilFile from "../../db/utils/fileUtils/index"; import awaitStream from "./utils/awaitStream"; import createThumbnailAny from "./utils/createThumbailAny"; import imageChecker from "../../utils/imageChecker"; import Thumbnail, {ThumbnailInterface} from "../../models/thumbnail"; import streamToBuffer from "../../utils/streamToBuffer"; import User from "../../models/user"; import env from "../../enviroment/env"; import removeChunksFS from "./utils/removeChunksFS"; import getPrevIVFS from "./utils/getPrevIVFS"; import awaitStreamVideo from "./utils/awaitStreamVideo"; import fixStartChunkLength from "./utils/fixStartChunkLength"; import Folder, { FolderInterface } from "../../models/folder"; import addToStoageSize from "./utils/addToStorageSize"; import subtractFromStorageSize from "./utils/subtractFromStorageSize"; import ForbiddenError from "../../utils/ForbiddenError"; import { ObjectID } from "mongodb"; const dbUtilsFile = new DbUtilFile(); class FileSystemService implements ChunkInterface { constructor() { } uploadFile = async(user: UserInterface, busboy: any, req: Request) => { const password = user.getEncryptionKey(); if (!password) throw new ForbiddenError("Invalid Encryption Key") const initVect = crypto.randomBytes(16); const CIPHER_KEY = crypto.createHash('sha256').update(password).digest() const cipher = crypto.createCipheriv('aes256', CIPHER_KEY, initVect); const {file, filename, formData} = await getBusboyData(busboy); const parent = formData.get("parent") || "/" const parentList = formData.get("parentList") || "/"; const size = formData.get("size") || "" const personalFile = formData.get("personal-file") ? true : false; let hasThumbnail = false; let thumbnailID = "" const isVideo = videoChecker(filename) const systemFileName = uuid.v4(); const metadata = { owner: user._id, parent, parentList, hasThumbnail, thumbnailID, isVideo, size, IV: initVect, filePath: env.fsDirectory + systemFileName } const fileWriteStream = fs.createWriteStream(metadata.filePath); const totalStreamsToErrorCatch = [file, cipher, fileWriteStream]; await awaitUploadStreamFS(file.pipe(cipher), fileWriteStream, req, metadata.filePath, totalStreamsToErrorCatch); const date = new Date(); const encryptedFileSize = await getFileSize(metadata.filePath); const currentFile = new File({ filename, uploadDate: date.toISOString(), length: encryptedFileSize, metadata }); await currentFile.save(); await addToStoageSize(user, size, personalFile); const imageCheck = imageChecker(currentFile.filename); if (currentFile.length < 15728640 && imageCheck) { const updatedFile = await createThumbnailAny(currentFile, filename, user); return updatedFile; } else { return currentFile; } } getFileWriteStream = async(user: UserInterface, file: FileInterface, parentFolder: FolderInterface) => { const password = user.getEncryptionKey(); if (!password) throw new ForbiddenError("Invalid Encryption Key") const initVect = crypto.randomBytes(16); const CIPHER_KEY = crypto.createHash('sha256').update(password).digest() const cipher = crypto.createCipheriv('aes256', CIPHER_KEY, initVect); const filename = file.filename const parent = parentFolder._id const parentList = [...parentFolder.parentList, parentFolder._id] const size = file.metadata.size const personalFile = file.metadata.personalFile ? true : false let hasThumbnail = file.metadata.hasThumbnail; let thumbnailID = file.metadata.thumbnailID const isVideo = file.metadata.isVideo const systemFileName = uuid.v4(); const metadata = { owner: user._id, parent, parentList, hasThumbnail, thumbnailID, isVideo, size, IV: file.metadata.IV, filePath: env.fsDirectory + systemFileName } const fileWriteStream = fs.createWriteStream(metadata.filePath); return fileWriteStream; } downloadFile = async(user: UserInterface, fileID: string, res: Response) => { const currentFile: FileInterface = await dbUtilsFile.getFileInfo(fileID, user._id); if (!currentFile) throw new NotFoundError("Download File Not Found"); const password = user.getEncryptionKey(); if (!password) throw new ForbiddenError("Invalid Encryption Key") const filePath = currentFile.metadata.filePath!; const IV = currentFile.metadata.IV.buffer as Buffer; const readStream = fs.createReadStream(filePath); const CIPHER_KEY = crypto.createHash('sha256').update(password).digest() const decipher = crypto.createDecipheriv('aes256', CIPHER_KEY, IV); res.set('Content-Type', 'binary/octet-stream'); res.set('Content-Disposition', 'attachment; filename="' + currentFile.filename + '"'); res.set('Content-Length', currentFile.metadata.size.toString()); const allStreamsToErrorCatch = [readStream, decipher]; await awaitStream(readStream.pipe(decipher), res, allStreamsToErrorCatch); } getFileReadStream = async(user: UserInterface, fileID: string) => { const currentFile: FileInterface = await dbUtilsFile.getFileInfo(fileID, user._id); if (!currentFile) throw new NotFoundError("Download File Not Found"); const password = user.getEncryptionKey(); if (!password) throw new ForbiddenError("Invalid Encryption Key") const filePath = currentFile.metadata.filePath!; const IV = currentFile.metadata.IV.buffer as Buffer; const readStream = fs.createReadStream(filePath); const CIPHER_KEY = crypto.createHash('sha256').update(password).digest() const decipher = crypto.createDecipheriv('aes256', CIPHER_KEY, IV); return readStream } getThumbnail = async(user: UserInterface, id: string) => { const password = user.getEncryptionKey(); if (!password) throw new ForbiddenError("Invalid Encryption Key") const thumbnail = await Thumbnail.findById(new ObjectID(id)) as ThumbnailInterface; if (thumbnail.owner !== user._id.toString()) { throw new ForbiddenError('Thumbnail Unauthorized Error'); } const iv = thumbnail.IV!; const CIPHER_KEY = crypto.createHash('sha256').update(password).digest() const decipher = crypto.createDecipheriv("aes256", CIPHER_KEY, iv); const readStream = fs.createReadStream(thumbnail.path!); const allStreamsToErrorCatch = [readStream, decipher]; const bufferData = await streamToBuffer(readStream.pipe(decipher), allStreamsToErrorCatch); return bufferData; } getFullThumbnail = async(user: UserInterface, fileID: string, res: Response) => { const userID = user._id; const file: FileInterface = await dbUtilsFile.getFileInfo(fileID, userID); if (!file) throw new NotFoundError("File Thumbnail Not Found"); const password = user.getEncryptionKey(); const IV = file.metadata.IV.buffer as Buffer; if (!password) throw new ForbiddenError("Invalid Encryption Key") const readStream = fs.createReadStream(file.metadata.filePath!); const CIPHER_KEY = crypto.createHash('sha256').update(password).digest() const decipher = crypto.createDecipheriv('aes256', CIPHER_KEY, IV); res.set('Content-Type', 'binary/octet-stream'); res.set('Content-Disposition', 'attachment; filename="' + file.filename + '"'); res.set('Content-Length', file.metadata.size.toString()); const allStreamsToErrorCatch = [readStream, decipher]; await awaitStream(readStream.pipe(decipher), res, allStreamsToErrorCatch); } streamVideo = async(user: UserInterface, fileID: string, headers: any, res: Response, req: Request) => { // To get this all working correctly with encryption and across // All browsers took many days, tears, and some of my sanity. // Shoutout to Tyzoid for helping me with the decryption // And and helping me understand how the IVs work. // P.S I hate safari >:( // Why do yall have to be weird with video streaming // 90% of the issues with this are only in Safari // Is safari going to be the next internet explorer? const userID = user._id; const currentFile: FileInterface = await dbUtilsFile.getFileInfo(fileID, userID); if (!currentFile) throw new NotFoundError("Video File Not Found"); const password = user.getEncryptionKey(); if (!password) throw new ForbiddenError("Invalid Encryption Key") const fileSize = currentFile.metadata.size; const range = headers.range const parts = range.replace(/bytes=/, "").split("-") let start = parseInt(parts[0], 10) let end = parts[1] ? parseInt(parts[1], 10) : fileSize-1 const IV = currentFile.metadata.IV.buffer as Buffer; const chunksize = (end-start)+1 let head = { 'Content-Range': 'bytes ' + start + '-' + end + '/' + fileSize, 'Accept-Ranges': 'bytes', 'Content-Length': chunksize, 'Content-Type': 'video/mp4'} let currentIV = IV; let fixedStart = 0; let fixedEnd = currentFile.length; if (start === 0 && end === 1) { // This is for Safari/iOS, Safari will request the first // Byte before actually playing the video. Needs to be // 16 bytes. fixedStart = 0; fixedEnd = 15; } else { // If you're a normal browser, or this isn't Safari's first request // We need to make it so start is divisible by 16, since AES256 // Has a block size of 16 bytes. fixedStart = start % 16 === 0 ? start : fixStartChunkLength(start); } if (+start === 0) { // This math will not work if the start is 0 // So if it is we just change fixed start back // To 0. fixedStart = 0; } // We also need to calculate the difference between the start and the // Fixed start position. Since there will be an offset if the original // Request is not divisible by 16, it will not return the right part // Of the file, you will see how we do this in the awaitStreamVideo // code. const differenceStart = start - fixedStart; if (fixedStart !== 0 && start !== 0) { // If this isn't the first request, the way AES256 works is when you try to // Decrypt a certain part of the file that isn't the start, the IV will // Actually be the 16 bytes ahead of where you are trying to // Start the decryption. currentIV = await getPrevIVFS(fixedStart - 16, currentFile.metadata.filePath!) as Buffer; } const readStream = fs.createReadStream(currentFile.metadata.filePath!, { start: fixedStart, end: fixedEnd, }); const CIPHER_KEY = crypto.createHash('sha256').update(password).digest() const decipher = crypto.createDecipheriv('aes256', CIPHER_KEY, currentIV); decipher.setAutoPadding(false); res.writeHead(206, head); const allStreamsToErrorCatch = [readStream, decipher]; readStream.pipe(decipher); await awaitStreamVideo(start, end, differenceStart, decipher, res, req, allStreamsToErrorCatch, readStream); readStream.destroy(); } getPublicDownload = async(fileID: string, tempToken: any, res: Response) => { const file: FileInterface = await dbUtilsFile.getPublicFile(fileID); if (!file || !file.metadata.link || file.metadata.link !== tempToken) { throw new NotAuthorizedError("File Not Public"); } const user = await User.findById(file.metadata.owner) as UserInterface; const password = user.getEncryptionKey(); if (!password) throw new ForbiddenError("Invalid Encryption Key"); const IV = file.metadata.IV.buffer as Buffer; const readStream = fs.createReadStream(file.metadata.filePath!); const CIPHER_KEY = crypto.createHash('sha256').update(password).digest() const decipher = crypto.createDecipheriv('aes256', CIPHER_KEY, IV); res.set('Content-Type', 'binary/octet-stream'); res.set('Content-Disposition', 'attachment; filename="' + file.filename + '"'); res.set('Content-Length', file.metadata.size.toString()); const allStreamsToErrorCatch = [readStream, decipher]; await awaitStream(readStream.pipe(decipher), res, allStreamsToErrorCatch); if (file.metadata.linkType === "one") { await dbUtilsFile.removeOneTimePublicLink(fileID); } } deleteFile = async(userID: string, fileID: string) => { const file: FileInterface = await dbUtilsFile.getFileInfo(fileID, userID); if (!file) throw new NotFoundError("Delete File Not Found Error"); if (file.metadata.thumbnailID) { const thumbnail = await Thumbnail.findById(file.metadata.thumbnailID) as ThumbnailInterface; const thumbnailPath = thumbnail.path!; await removeChunksFS(thumbnailPath); await Thumbnail.deleteOne({_id: file.metadata.thumbnailID}); } await removeChunksFS(file.metadata.filePath!); await File.deleteOne({_id: file._id}); await subtractFromStorageSize(userID, file.length, file.metadata.personalFile!) } deleteFolder = async(userID: string, folderID: string, parentList: string[]) => { const parentListString = parentList.toString() await Folder.deleteMany({"owner": userID, "parentList": { $all: parentList}}) await Folder.deleteMany({"owner": userID, "_id": folderID}); const fileList = await dbUtilsFile.getFileListByParent(userID, parentListString); if (!fileList) throw new NotFoundError("Delete File List Not Found"); for (let i = 0; i < fileList.length; i++) { const currentFile = fileList[i]; try { if (currentFile.metadata.thumbnailID) { const thumbnail = await Thumbnail.findById(currentFile.metadata.thumbnailID) as ThumbnailInterface; const thumbnailPath = thumbnail.path!; await removeChunksFS(thumbnailPath); await Thumbnail.deleteOne({_id: currentFile.metadata.thumbnailID}); } await removeChunksFS(currentFile.metadata.filePath!); await File.deleteOne({_id: currentFile._id}); } catch (e) { console.log("Could not delete file", currentFile.filename, currentFile._id); } } } deleteAll = async(userID: string) => { await Folder.deleteMany({"owner": userID}); const fileList = await dbUtilsFile.getFileListByOwner(userID); if (!fileList) throw new NotFoundError("Delete All File List Not Found Error"); for (let i = 0; i < fileList.length; i++) { const currentFile = fileList[i]; try { if (currentFile.metadata.thumbnailID) { const thumbnail = await Thumbnail.findById(currentFile.metadata.thumbnailID) as ThumbnailInterface; const thumbnailPath = thumbnail.path!; await removeChunksFS(thumbnailPath); await Thumbnail.deleteOne({_id: currentFile.metadata.thumbnailID}); } await removeChunksFS(currentFile.metadata.filePath!); await File.deleteOne({_id: currentFile._id}); } catch (e) { console.log("Could Not Remove File", currentFile.filename, currentFile._id); } } } } export default FileSystemService;
the_stack
import { calcInputByPrice, calcOutByIn, calcPrice, revertPositive } from './MultiRouterMath'; import {PoolType, Pool, Route} from './MultiRouterTypes' const LegGasConsuming = 40_000; function calcPoolChainOutByIn(pools:Pool[], amountIn: number): number { return pools.reduce((input, p) => calcOutByIn(p, input), amountIn); } function calcPoolChainPrice(pools:Pool[], amountIn: number): number { let out = amountIn, derivative = 1; const last = pools.length - 1; for (let i = 0; i < last; ++i) { derivative *= calcPrice(pools[i], out); out = calcOutByIn(pools[i], out); } const res = derivative * calcPrice(pools[last], out); // TODO: to delete const res2 = (calcPoolChainOutByIn(pools, amountIn + 0.01) - calcPoolChainOutByIn(pools, amountIn))/0.01; if (Math.abs(res/res2-1) > 1e-5) console.error("163 " + res + " " + res2 + " " + Math.abs(res/res2-1)); return res; } function calcPoolChainInputByPrice(pools:Pool[], priceEffective: number, hint = 1): number { if (pools.length == 1) return calcInputByPrice(pools[0], priceEffective, hint); return revertPositive( (x:number) => 1/calcPoolChainPrice(pools, x), priceEffective, hint); } function calcInputByPriceParallel(pools: Pool[], priceEffective: number): number { let res = 0; // TODO: if pools are sorted by effectivity and one of them is less 0 => may avoid to check others pools.forEach(pool => { const input = calcInputByPrice(pool, priceEffective); if (input > 0) res += input; }) return res; } interface PoolsVariantData { poolNumber: number; amountOut: number; priceEffective: number; distribution: number[]; } function findBestDistributionIdealParams( amountIn: number, pools: Pool[], minPrice: number ): PoolsVariantData { // TODO: not binary search - but better? 1.01? let maxPrice; for (maxPrice = minPrice*2; calcInputByPriceParallel(pools, maxPrice) < amountIn; maxPrice *=2); minPrice = maxPrice/2; while((maxPrice/minPrice - 1) > 1e-12) { const price:number = (maxPrice+minPrice)/2; const input = calcInputByPriceParallel(pools, price); if (input >= amountIn) maxPrice = price; else minPrice = price; } const price:number = (maxPrice+minPrice)/2; let distribution = pools.map(pool => Math.max(calcInputByPrice(pool, price), 0)); const sum = distribution.reduce((a,b) => a+b, 0); if (Math.abs(sum/amountIn - 1) >= 0.1) console.assert(Math.abs(sum/amountIn - 1) < 0.1, '196 ' + sum + ' ' + amountIn); distribution = distribution.map(v => v/sum); return { poolNumber: pools.length, amountOut: distribution.map((v, i) => calcOutByIn(pools[i], v*amountIn)).reduce((a,b) => a+b, 0), priceEffective: price, distribution } } export function findBestDistributionIdeal( amountIn: number, pools: Pool[], tokenOutPriceBase: number, gasPriceGWeiBase: number ): Route | [number, number[][]]{ const legPriceInTokenOut = LegGasConsuming*gasPriceGWeiBase*1e-9/tokenOutPriceBase; let minPrice = calcPrice(pools[0], 0); for (let i = 1; i < pools.length; ++i) { const pr = calcPrice(pools[i], 0); minPrice = Math.min(pr, minPrice); } const params = findBestDistributionIdealParams(amountIn, pools, minPrice); const distrSorted = params.distribution.map((v, i) => [i, v]).sort((a,b) => b[1] - a[1]); params.distribution = distrSorted.map(a => a[1]); const poolsSorted = distrSorted.map(a => pools[a[0]]); // TODO: Use more fast search instead let bestOut = params.amountOut - pools.length*legPriceInTokenOut; let bestParams = params; for (let i = pools.length-1; i >= 1; --i) { const shortPoolList = poolsSorted.slice(0, i); const p = findBestDistributionIdealParams(amountIn, shortPoolList, minPrice); const out = p.amountOut - i*legPriceInTokenOut; if (out < bestOut){ //break; // TODO: uncomment? } else { bestOut = out; bestParams = p; } } const finalDistribution = bestParams.distribution.map((v, i) => [distrSorted[i][0], v]); const checkedOut = calcOut(amountIn, pools, finalDistribution, tokenOutPriceBase, gasPriceGWeiBase); return [checkedOut, finalDistribution]; } function findBestDistribution2 ( amountIn: number, pools: Pool[], tokenOutPriceBase: number, gasPriceGWeiBase: number ): Route | [number, number[][]]{ const legPriceInTokenOut = LegGasConsuming*gasPriceGWeiBase*1e-9/tokenOutPriceBase; const out = pools.map(p => calcOutByIn(p, amountIn)); const sum = out.reduce((a, b) => a+b, 0); const order = out.map((o, i) => [i, o/sum]).sort((a,b) => b[1] - a[1]); let bestGroup = order; let bestOut = -legPriceInTokenOut*pools.length*2; let flagDown = false; for (let i = pools.length; i >= 1; --i) { const group = order.slice(0, i); const sum = group.reduce((a, b) => a+b[1], 0); const out = group.map(p => calcOutByIn(pools[p[0]], p[1]/sum*amountIn)).reduce((a, b) => a+b, 0) - legPriceInTokenOut*i; if (out > bestOut) { console.assert(flagDown == false, "flagDown at " + amountIn); bestOut = out; bestGroup = group.map(([n, v]) => [n, v/sum]); } else { flagDown = true; // break; // TODO: unconmment? } } return [bestOut, bestGroup]; } function findBestDistribution3 ( amountIn: number, pools: Pool[], tokenOutPriceBase: number, gasPriceGWeiBase: number ): Route | [number, number[][]]{ const legPriceInTokenOut = LegGasConsuming*gasPriceGWeiBase*1e-9/tokenOutPriceBase; const out = pools.map(p => calcOutByIn(p, amountIn/pools.length)); const sum = out.reduce((a, b) => a+b, 0); const order = out.map((o, i) => [i, o/sum]).sort((a,b) => b[1] - a[1]); let bestGroup = order; let bestOut = -legPriceInTokenOut*pools.length*2; for (let i = pools.length; i >= 1; --i) { const group = order.slice(0, i); const sum = group.reduce((a, b) => a+b[1], 0); const out = group.map(p => calcOutByIn(pools[p[0]], p[1]/sum*amountIn)).reduce((a, b) => a+b, 0) - legPriceInTokenOut*i; if (out > bestOut) { bestOut = out; bestGroup = group.map(([n, v]) => [n, v/sum]); } else { // break; // TODO: unconmment? } } const checkedOut = calcOut(amountIn, pools, bestGroup, tokenOutPriceBase, gasPriceGWeiBase); return [checkedOut, bestGroup]; } function findBestDistributionWithoutTransactionCost( amountIn: number, pools: Pool[] // TODO: maybe use initial distribution? ): [number, number[]] { if (pools.length == 1) { return [calcOutByIn(pools[0], amountIn), [1]]; } let distr = pools.map(p => Math.max(calcOutByIn(p, amountIn/pools.length), 0)); for(let i = 0; i < 5; ++i) { const sum = distr.reduce((a, b) => a+b, 0); console.assert(sum > 0, "508 " + sum); const prices = distr.map((d, j) => 1/calcPrice(pools[j], amountIn*d/sum)) const pr = prices.reduce((a, b) => Math.max(a, b), 0); distr = pools.map((p, i) => calcInputByPrice(p, pr, distr[i])); } const sum = distr.reduce((a, b) => a + b, 0); distr = distr.map(d => d/sum); const out = distr.map((p, i) => calcOutByIn(pools[i], p*amountIn)).reduce((a, b) => a+b, 0); return [out, distr]; } export function findBestDistribution( amountIn: number, pools: Pool[], tokenOutPriceBase: number, gasPriceGWeiBase: number ): Route | [number, number[][]]{ const legPriceInTokenOut = LegGasConsuming*gasPriceGWeiBase*1e-9/tokenOutPriceBase; let [bestOut, distr] = findBestDistributionWithoutTransactionCost(amountIn, pools); bestOut -= legPriceInTokenOut*pools.length; let bestGroup = distr.map((d, i) => [i, d]).sort((a,b) => b[1] - a[1]); let flagDown = false; const poolsSorted = bestGroup.map(a => pools[a[0]]); for (let i = pools.length-1; i >= 1; --i) { const group = poolsSorted.slice(0, i); let [out, distr] = findBestDistributionWithoutTransactionCost(amountIn, group); out -= legPriceInTokenOut*i; if (out > bestOut) { console.assert(flagDown == false, "408 flagDown at " + amountIn); bestOut = out; bestGroup = distr.map((d, i) => [bestGroup[i][0], d]); } else { flagDown = true; // break; // TODO: uncomment for speed up ??? } } const checkedOut = calcOut(amountIn, pools, bestGroup, tokenOutPriceBase, gasPriceGWeiBase); return [checkedOut, bestGroup]; } function findBesChaintDistributionWithoutTransactionCost( amountIn: number, poolChains: Pool[][] // TODO: maybe use initial distribution? ): [number, number[]] { if (poolChains.length == 1) { return [calcPoolChainOutByIn(poolChains[0], amountIn), [1]]; } let distr = poolChains.map(p => Math.max(calcPoolChainOutByIn(p, amountIn/poolChains.length), 0)); for(let i = 0; i < 5; ++i) { const sum = distr.reduce((a, b) => a+b, 0); console.assert(sum > 0, "508 " + sum); const prices = distr.map((d, j) => 1/calcPoolChainPrice(poolChains[j], amountIn*d/sum)) const pr = prices.reduce((a, b) => Math.max(a, b), 0); distr = poolChains.map((p, i) => calcPoolChainInputByPrice(p, pr, distr[i])); } const sum = distr.reduce((a, b) => a + b, 0); distr = distr.map(d => d/sum); const out = distr.map((p, i) => calcPoolChainOutByIn(poolChains[i], p*amountIn)).reduce((a, b) => a+b, 0); return [out, distr]; } function findBestChainDistribution( amountIn: number, poolChains: Pool[][], tokenOutPriceBase: number, gasPriceGWeiBase: number ): Route | [number, number[][]]{ const legPriceInTokenOut = LegGasConsuming*gasPriceGWeiBase*1e-9/tokenOutPriceBase; let [bestOut, distr] = findBesChaintDistributionWithoutTransactionCost(amountIn, poolChains); let bestGroup = distr.map((d, i) => [i, d]).sort((a,b) => b[1] - a[1]); let totalJumps = 0; const poolNumber:number[] = []; for (let i = 0; i < poolChains.length; ++i) { totalJumps += poolChains[bestGroup[i][0]].length; poolNumber[i] = totalJumps; } bestOut -= legPriceInTokenOut*totalJumps; let flagDown = false; const poolsSorted = bestGroup.map(a => poolChains[a[0]]); for (let i = poolChains.length-1; i >= 1; --i) { const group = poolsSorted.slice(0, i); let [out, distr] = findBesChaintDistributionWithoutTransactionCost(amountIn, group); out -= legPriceInTokenOut*poolNumber[i-1]; if (out > bestOut) { console.assert(flagDown == false, "408 flagDown at " + amountIn); bestOut = out; bestGroup = distr.map((d, i) => [bestGroup[i][0], d]); } else { flagDown = true; // break; // TODO: uncomment for speed up ??? } } const checkedOut = calcPoolChainOut(amountIn, poolChains, bestGroup, tokenOutPriceBase, gasPriceGWeiBase); return [checkedOut, bestGroup]; } function calcOut( amountIn: number, pools: Pool[], distribution: number[][], tokenOutPriceBase: number, gasPriceGWeiBase: number ): number { const legPriceInTokenOut = LegGasConsuming*gasPriceGWeiBase*1e-9/tokenOutPriceBase; const sum = distribution.reduce((a, b) => a + b[1], 0); const out = distribution.map(p => calcOutByIn(pools[p[0]], p[1]/sum*amountIn)).reduce((a, b) => a+b, 0); /* console.log(amountIn, sum, out); console.log(distribution.map(d => { const inn = amountIn*d[1]/sum; inCheck += inn; const out = calcOutByIn(pools[d[0]], inn); outCheck += out; const pr = calcPrice(pools[d[0]], inn); d.push(out); d.push(pr); return d; }));*/ return out - legPriceInTokenOut*distribution.length; } function calcPoolChainOut( amountIn: number, poolChains: Pool[][], distribution: number[][], tokenOutPriceBase: number, gasPriceGWeiBase: number ): number { const legPriceInTokenOut = LegGasConsuming*gasPriceGWeiBase*1e-9/tokenOutPriceBase; const sum = distribution.reduce((a, b) => a + b[1], 0); const out = distribution.map(p => calcPoolChainOutByIn(poolChains[p[0]], p[1]/sum*amountIn)).reduce((a, b) => a+b, 0); let totalJumps = distribution.reduce((a, p) => a += poolChains[p[0]].length, 0); /* console.log(amountIn, sum, out); console.log(distribution.map(d => { const inn = amountIn*d[1]/sum; inCheck += inn; const out = calcOutByIn(pools[d[0]], inn); outCheck += out; const pr = calcPrice(pools[d[0]], inn); d.push(out); d.push(pr); return d; }));*/ return out - legPriceInTokenOut*totalJumps; }
the_stack
import {app} from './app.js'; app.controller( 'specTabCtrl', function ($scope, $location, $filter, $sce, Spec, storageService) { // Initial Config $scope.canEdit = false; $scope.editing = false; $scope.overlay = false; $scope.configuring = false; $scope.showingVideoWarning = false; $scope.canScrubVideo = false; $scope.showingCode = false; $scope.addingRow = null; $scope.selectedRow = null; $scope.resizingRow = null; $scope.getVideoSrc = function (src) { var URL_REGEX = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/; var ID_REGEX = /[-\w]{25,}/g; if (src && src.search(ID_REGEX) != -1) { var videoId = src.match(ID_REGEX); console.log('> Video is a Drive ID or Drive URL'); // Is a drive ID return $sce.trustAsResourceUrl( 'https://docs.google.com/uc?authuser=0&id=' + videoId + '&export=download' ); } else if (src && src.search(URL_REGEX) != -1) { console.log('> Video is a full URL'); // Is a full URL return $sce.trustAsResourceUrl(src); } else { // Something went wrong console.log('Something went wrong trying to load the video'); } }; $scope.$watch('spec.videoUrl', function () { if ($scope.spec) { $scope.spec.videoSrc = $scope.getVideoSrc($scope.spec.videoUrl); } }); var recalculate = function () { if ($scope.spec) { var msPerFrame = 1000 / $scope.spec.fps; $scope.spec.duration = $scope.spec.frames * msPerFrame; $scope.spec.divisions.minor = msPerFrame * $scope.spec.divisions.minorFrames; $scope.spec.divisions.major = msPerFrame * $scope.spec.divisions.majorFrames; if ($scope.spec.exactTiming) { $scope.decimalPlaces = 2; } else { $scope.decimalPlaces = 0; } $scope.createLabels(); } }; $scope.$watchGroup( [ 'spec.exactTiming', 'spec.fps', 'spec.frames', 'spec.divisions.minorFrames', 'spec.divisions.majorFrames', ], function () { recalculate(); } ); // Autosave storageService.autosave($scope); // Initial Data Setup if ($scope.specId) { Spec.get({id: $scope.specId}, function (data) { // TODO: Handle failure console.log(data); $scope.data = data; $scope.spec = $scope.data.spec; // check if can edit if ($scope.data.permissions.owner === $scope.user) { $scope.canEdit = true; } // Loop through all rows and set the easing option again for (var i = 0; i < $scope.spec.rows.length; i++) { var row = $scope.spec.rows[i]; // Set easing. var easing = matchOption($scope.easingOptions, row.easing, { label: 'Linear', value: 'linear', }); row.easing = easing; // Set tag. var tag = matchOption($scope.tagOptions, row.tag, { label: 'None', value: 'none', }); row.tag = tag; } }); // Check if should be editing. if ($location.search().create == 'true') { $scope.editing = true; $scope.configuring = true; $scope.overlay = true; } $location.search(''); } else { $scope.data = { group: null, groupHandle: null, title: null, permissions: { privacy: 'public', owner: $scope.user, editors: [], viewers: [], }, spec: { title: null, videoUrl: null, duration: 500, frames: 30, fps: 60, exactTiming: false, canvas: { width: 0, }, divisions: { minor: 15, // ms minorFrames: 1, major: 75, // ms majorFrames: 5, minorCount: null, majorCount: null, minorGap: null, majorGap: null, }, rows: [], }, }; $scope.spec = $scope.data.spec; // Start with editing mode on a new spec $scope.editing = true; } // Watch group name to make sure a handle is generated $scope.$watch('data.group', function () { if ($scope.data && $scope.data.group) { var handle = $scope.data.group.replace(/\s+/g, '-'); $scope.data.groupHandle = handle.toLowerCase(); console.log('> New Group Handle: ' + $scope.data.groupHandle); } }); // keep sidebar up to date $scope.$watchGroup(['data.group', 'data.title'], function () { $scope.refreshSidebar(); }); // Changing Config $scope.editSpec = function () { if ($scope.canEdit) { $scope.editing = true; } $scope.refreshCanvas(); }; $scope.previewSpec = function () { if ($scope.canEdit) { $scope.editing = false; } if ($scope.configuring) { $scope.toggleConfig(); } if ($scope.addingRow) { $scope.addingRow = null; } $scope.refreshCanvas(); $location.search(''); }; $scope.importJson = function () { // Import Json const input = document.createElement('input'); input.type = 'file'; input.accept = '.json'; input.onchange = function (e) { const target = e.target as HTMLInputElement; if (!target.files) return; const file = target.files[0]; const reader = new FileReader(); reader.onload = function (e) { const result = e.target?.result; if (!result) return; const json = JSON.parse(result as string); $scope.data = json; $scope.spec = $scope.data.spec; $scope.refreshCanvas(); }; reader.readAsText(file); }; input.click(); input.remove(); }; $scope.exportJson = function () { // Export Json const spec = $scope.spec; const json = JSON.stringify(spec, null, 2); const blob = new Blob([json], {type: 'application/json'}); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.download = 'spec.json'; a.href = url; a.click(); }; $scope.toggleConfig = function () { $scope.configuring = !$scope.configuring; $scope.overlay = $scope.configuring; }; $scope.toggleVideo = function () { if ($scope.editing) { // Add a video URL with Google Drive picker loadPicker($scope); } }; $scope.toggleVideoWarning = function (show) { if (typeof show === 'undefined') { $scope.showingVideoWarning = !$scope.showingVideoWarning; } else { $scope.showingVideoWarning = show; } }; $scope.setCanScrubVideo = function (canScrub) { $scope.canScrubVideo = canScrub; }; $scope.toggleCodePopup = function () { $scope.showingCode = !$scope.showingCode; $scope.overlay = $scope.showingCode; }; $scope.closeOverlay = function () { // Turn off settings popup if ($scope.configuring) { $scope.toggleConfig(); } // Turn off easing details if ($scope.showingCode) { $scope.toggleCodePopup(); } }; var matchOption = function (easingOrTagOptions, option, unmatchedOption) { if (option) { for (var i = 0; i < easingOrTagOptions.length; i++) { var opt = easingOrTagOptions[i]; if (opt.value === option.value) { return opt; } } } // Not set, therefore return none. return unmatchedOption; }; // Special case for first row adding $scope.firstRow = { adding: false, }; // Grid Labels $scope.labels = { frames: [], ms: [], }; $scope.createLabels = function () { $scope.labels.frames.length = 0; $scope.labels.ms.length = 0; // Calculate frame labels if ($scope.spec && $scope.spec.divisions.majorCount) { for (var i = 0; i <= $scope.spec.divisions.majorCount; i++) { var num = i * $scope.spec.divisions.majorFrames; let label = num.toString(); if (i === 0) { label = 'Frames'; } $scope.labels.frames.push(label); } } // Calculate ms labels if ($scope.spec && $scope.spec.divisions.majorCount) { for (var i = 0; i <= $scope.spec.divisions.majorCount; i++) { var num = i * $scope.spec.divisions.major; let label: string = num.toString(); if (i === 0) { label = 'Ms'; } else { label = $filter('number')(label, $scope.decimalPlaces); } $scope.labels.ms.push(label); } } }; // Watch for grid computations $scope.$watch('spec.divisions.majorCount', function () { $scope.createLabels(); }); // Toggle drawer $scope.toggleDrawer = function (row, isOpen) { if ($scope.addingRow) { // clear adding row $scope.addingRow = null; } if (row && ($scope.selectedRow != row || isOpen)) { // show drawer $scope.selectedRow = row; } else { // hide drawer $scope.selectedRow = null; } $scope.refreshCanvas(); }; // Toggle row adder $scope.toggleNewRow = function (row, isOpen) { if ($scope.selectedRow) { // clear selected row $scope.selectedRow = null; } if (row && ($scope.addingRow != row || isOpen)) { // show new row $scope.addingRow = row; } else { // hide new row $scope.addingRow = null; } $scope.refreshCanvas(); }; // Set resizing row $scope.setResizingRow = function (row) { $scope.resizingRow = row; }; // Refresh on duration / division change $scope.$watchGroup( ['spec.duration', 'spec.divisions'], function (newValues, oldValues, scope) { $scope.refreshCanvas(); } ); // Change Color $scope.changeColor = function (row, color) { row.color = color; }; // Delete A Row $scope.deleteRow = function (row) { var index = $scope.spec.rows.indexOf(row); if (index > -1) { $scope.spec.rows.splice(index, 1); $scope.refreshCanvas(); } }; } );
the_stack
/// <reference path="ezgui.ts" /> declare var Phaser; module EZGUI { export class Theme { static imageComponents = ['bg', 'corner', 'line', 'side', 'image', 'checkmark']; static imageStates = ['default', 'hover', 'down', 'checked']; static imageVariants = ['', 't', 'r', 'b', 'l', 'left', 'right', 'tl', 'tr', 'bl', 'br']; private _theme; private _default; private _listeners = []; public ready = false; public id: string; private url = ''; private path; constructor(public themeConfig) { var __this = this; if (typeof themeConfig == 'string') { //is this an url ? __this.url = themeConfig; utils.loadJSON(__this.url, function (themeConfig) { __this.themeConfig = themeConfig; __this.initThemeConfig(themeConfig); }); } else { this.initThemeConfig(themeConfig); } } public override(themeConfig) { var _theme = JSON.parse(JSON.stringify(themeConfig)); for (var t in _theme) { if (t == 'default') continue; var skin = _theme[t]; utils.extendJSON(skin, this._default); } this.parseComponents(_theme); for (var t in _theme) { if (t == 'default') continue; var skin = _theme[t]; this._theme[t] = skin; } } private fixLimits (target, source) { if (typeof source == 'object') { if (target.width != undefined && source.maxWidth) target.width = Math.min(target.width, source.maxWidth); if (target.height != undefined && source.maxHeight) target.height = Math.min(target.height, source.maxHeight); for (var i in source) { var src = source[i]; if (typeof target[i] == 'object') { this.fixLimits(target[i], source[i]); } } } } private initThemeConfig(themeConfig) { this._theme = JSON.parse(JSON.stringify(themeConfig)); this.id = this._theme.__config__ ? this._theme.__config__.name : undefined; this._default = this._theme['default']; for (var t in this._theme) { if (t == 'default') continue; var skin = this._theme[t]; /* for (var i in this._default) { if (!skin[i]) skin[i] = JSON.parse(JSON.stringify(this._default[i])); } */ utils.extendJSON(skin, this._default); } this.path = this.url.substring(0, this.url.lastIndexOf('/') + 1); this.parseComponents(this._theme); this.preload(); } private parseResources() { var themeResources = this._theme.__config__.resources; var resources = []; if (!themeResources || themeResources.length <= 0) return resources; var resToLoad = 0; for (var i = 0; i < themeResources.length; i++) { var res = themeResources[i]; if (res.indexOf('http://') == 0 || res.indexOf('https://') == 0 || res.indexOf('file://') == 0 || res.indexOf('/') == 0) continue; //TODO : use a path normalizer here if (res.indexOf('./') == 0) res = res.substring(2); if ((<any>PIXI).loader && (<any>PIXI).loader.resources[resources[i]]) { // } else { resources.push(this.path + res); } } return resources; } private parseComponents(theme) { for (var i in theme) { if (i == '__config__') continue; var item = theme[i]; for (var c = 0; c < Theme.imageComponents.length; c++) { var cc = Theme.imageComponents[c]; for (var v = 0; v < Theme.imageVariants.length; v++) { var vv = Theme.imageVariants[v]; if (vv != '') cc = cc + '-' + vv; if (item[cc] == undefined) { cc = Theme.imageComponents[c]; continue; } if (typeof item[cc] == 'string') { var str = item[cc]; item[cc] = this.normalizeResPath(str); } else { for (var s = 0; s < Theme.imageStates.length; s++) { var st = Theme.imageStates[s]; var str = item[cc][st]; if (str) { item[cc][st] = this.normalizeResPath(str); } } } cc = Theme.imageComponents[c]; } } } } private normalizeResPath(str) { if (str.indexOf('./') != 0) return str; str = str.substring(2); return this.path + str; } static load(themes: any[], cb:any=null) { var remaining = 0; for (var i = 0; i < themes.length; i++) { remaining++; var theme = new Theme(themes[i]); theme.onReady(function () { remaining--; if (remaining <= 0 && typeof cb == 'function') { cb(); } }); } } //experimental Theme transparent preload public onReady(cb) { if (typeof cb != 'function') return; if (this.ready) cb(); this._listeners.push(cb); } private preload() { var __this = this; var onAssetsLoaded = function () { __this.ready = true; EZGUI.themes[__this.id] = __this; var cb; while (cb = __this._listeners.pop()) cb(); } if (this._theme.__config__ && this._theme.__config__.resources) { var resources = this.parseResources(); if (resources.length == 0) { onAssetsLoaded(); } else { //console.log('Theme preloading ', resources); //utils.loadJSON(_this.url, function (themeConfig) { // _this.themeConfig = themeConfig; // _this.initThemeConfig(themeConfig); //}); __this.loadResources(resources, onAssetsLoaded); //if ((<any>PIXI).loader) { // (<any>PIXI).loader.add(resources); // (<any>PIXI).loader.load(onAssetsLoaded); //} //else { // var loader: any = new PIXI.AssetLoader(resources, false); // loader.onComplete = onAssetsLoaded; // loader.load(); //} } } else { onAssetsLoaded(); } } private loadResources(resources, cb) { var _this = this; var images = []; var atlases = []; var fonts = []; var atlasData = {}; var fontData = {}; var resToLoad = 0; var cacheAtlas = function () { for (var i in atlasData) { var atlasJson:any = atlasData[i]; var imgUrl = _this.path + atlasJson.meta.image; var baseTx = (<any>PIXI).utils ? (<any>PIXI).utils.TextureCache[imgUrl].baseTexture : (<any>PIXI).TextureCache[imgUrl].baseTexture; for (var f in atlasJson.frames) { var frame = atlasJson.frames[f].frame; var texture = new (<any>PIXI).Texture(baseTx, { x: frame.x, y: frame.y, width: frame.w, height: frame.h }); if ((<any>PIXI).utils) { (<any>PIXI).utils.TextureCache[f] = texture; } else { (<any>PIXI).TextureCache[f] = texture; } } } for (var i in fontData) { var font: any = fontData[i]; _this.parseFont(font, PIXI.Texture.fromFrame(font.textureId)); } cb(); } //var phaser24cache = function (loader) { // if (!loader._fileList) return; // //console.log(loader._fileList); // for (var i = 0; i < loader._fileList.length; i++) { // var tx = new (<any>PIXI).Texture(new (<any>PIXI).BaseTexture(loader._fileList[i].data)); // //tx._frame = { test: 1 }; // //console.log('Caching : ', loader._fileList[i].key); // PIXI.TextureCache[loader._fileList[i].key] = tx; // //console.log(tx); // } //} var loadImages = function () { var crossOrigin = (EZGUI.settings.crossOrigin == true); if (typeof Phaser != 'undefined') { //console.log('Phaser loader'); var loader: any = new Phaser.Loader(Phaser.GAMES[0]); loader.crossOrigin = crossOrigin; for (var i = 0; i < images.length; i++) { loader.image(images[i], images[i]); } loader.onLoadComplete.add(function () { //loader.onLoadComplete.add(EZGUI.Compatibility.fixCache, loader); EZGUI.Compatibility.fixCache.apply(loader); //phaser24cache(loader); cacheAtlas(); }); loader.start(); return; } if ((<any>PIXI).loader) { for (var i = 0; i < images.length; i++) { (<any>PIXI).loader.add({ url: images[i], crossOrigin: crossOrigin}); } //(<any>PIXI).loader.add(images); (<any>PIXI).loader.load(cacheAtlas); } else { var loader: any = new (<any>PIXI).AssetLoader(images, crossOrigin); loader.onComplete = cacheAtlas; loader.load(); } } for (var i = 0; i < resources.length; i++) { var res = resources[i]; if (res.indexOf('.json') > 0) { atlases.push(res); continue; } if (res.indexOf('.xml') > 0 || res.indexOf('.fnt') > 0) { fonts.push(res) continue; } images.push(res); } if (atlases.length > 0) { for (var i = 0; i < atlases.length; i++) { var font = atlases[i]; resToLoad++; (function (atlasUrl) { utils.loadJSON(atlasUrl, function (atlasjson) { images.push(_this.path + atlasjson.meta.image); resToLoad--; atlasData[atlasUrl] = atlasjson; if (resToLoad <= 0) { //console.log('Atlas loaded ', images); loadImages(); } }); })(font) } } if (fonts.length > 0) { for (var i = 0; i < fonts.length; i++) { var font = fonts[i]; resToLoad++; (function (atlasUrl) { utils.loadXML(atlasUrl, function (xmlfont) { var img = xmlfont.getElementsByTagName('page')[0].getAttribute('file'); var path = atlasUrl.substring(0, atlasUrl.lastIndexOf('\\') + atlasUrl.lastIndexOf('/') + 2); var src = path + img; //console.log('Fake font load = ', src); images.push(src); resToLoad--; fontData[atlasUrl] = { data: xmlfont, textureId: src } if (resToLoad <= 0) { //console.log('Fonts loaded ', images); loadImages(); } }); })(font) } } if (atlases.length <= 0 && fonts.length <= 0) { loadImages(); } } private parseFont(resource, texture) { var data: any = {}; var info = resource.data.getElementsByTagName('info')[0]; var common = resource.data.getElementsByTagName('common')[0]; data.font = info.getAttribute('face'); data.size = parseInt(info.getAttribute('size'), 10); data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10); data.chars = {}; var Rectangle: any; var BitmapText: any; if (PIXI.Rectangle) Rectangle = PIXI.Rectangle; else Rectangle = (<any>PIXI).math.Rectangle; if (Compatibility.PIXIVersion >= 3) { BitmapText = (<any>PIXI).extras.BitmapText; } else { BitmapText = (<any>PIXI).BitmapText; } //parse letters var letters = resource.data.getElementsByTagName('char'); for (var i = 0; i < letters.length; i++) { var charCode = parseInt(letters[i].getAttribute('id'), 10); var textureRect = new Rectangle( parseInt(letters[i].getAttribute('x'), 10) + texture.frame.x, parseInt(letters[i].getAttribute('y'), 10) + texture.frame.y, parseInt(letters[i].getAttribute('width'), 10), parseInt(letters[i].getAttribute('height'), 10) ); data.chars[charCode] = { xOffset: parseInt(letters[i].getAttribute('xoffset'), 10), yOffset: parseInt(letters[i].getAttribute('yoffset'), 10), xAdvance: parseInt(letters[i].getAttribute('xadvance'), 10), kerning: {}, texture: new PIXI.Texture(texture.baseTexture, textureRect) }; } //parse kernings var kernings = resource.data.getElementsByTagName('kerning'); for (i = 0; i < kernings.length; i++) { var first = parseInt(kernings[i].getAttribute('first'), 10); var second = parseInt(kernings[i].getAttribute('second'), 10); var amount = parseInt(kernings[i].getAttribute('amount'), 10); data.chars[second].kerning[first] = amount; } //resource.bitmapFont = data; // I'm leaving this as a temporary fix so we can test the bitmap fonts in v3 // but it's very likely to change BitmapText.fonts[data.font] = data; } public getSkin(skinId) { var skin = this._theme[skinId] || this._theme['default']; return skin; } public applySkin(settings) { var skinId = settings['skin'] || settings['component']; var skin = this._theme[skinId] || this._theme['default']; utils.extendJSON(settings, skin); this.fixLimits(settings, skin); return settings; } } }
the_stack
import { TextDocument, Location, Range } from 'vscode'; import { SystemVerilogSymbol } from './symbol'; export class SystemVerilogParser { private illegalMatches = /(?!return|begin|end|else|join|fork|for|if|virtual|static|automatic|generate|assign|initial|assert|disable)/; private comment = /(?:\/\/.*$)?/; private r_decl_block: RegExp = new RegExp( [ '(?<=^\\s*', /(?<type>module|program|interface|package|primitive|config|property)\s+/, // Mask automatic /(?:automatic\s+)?/, ')', /(?<name>\w+)/, /(?<params>\s*#\s*\([\w\W]*?\))?/, /(?<ports>\s*\([\W\w]*?\))?/, /\s*;/, /(?<body>[\W\w]*?)/, /(?<end>end\1)/ ] .map((x) => (typeof x === 'string' ? x : x.source)) .join(''), 'mg' ); private r_decl_class: RegExp = new RegExp( [ '(?<=^\\s*(virtual\\s+)?', /(?<type>class)\s+/, ')', /(?<name>\w+)/, /(\s+(extends|implements)\s+[\w\W]+?|\s*#\s*\([\w\W]+?\))*?/, /\s*;/, /(?<body>[\w\W]*?)/, /(?<end>endclass)/ ] .map((x) => (typeof x === 'string' ? x : x.source)) .join(''), 'mg' ); private r_decl_method: RegExp = new RegExp( [ '(?<=^\\s*(virtual|local|extern|pure\\s+virtual)?\\s*', /(?<type>(function|task))\s+/, /(?<return>[\w:[\]\s*]+\s*)?/, ')', /\b(?<name>[\w.]+)\b\s*/, /(?<ports>\([\W\w]*?\))?/, /\s*;/, /(?<body>[\w\W]*?)/, /(?<end>end(function|task))/ ] .map((x) => (typeof x === 'string' ? x : x.source)) .join(''), 'mg' ); private r_typedef: RegExp = new RegExp( [ /(?<=^\s*)/, /(?<type>typedef\b)\s*((?!;|\{)[\W\w])+/, // Recursive depth of 3 '{'s /(\{(?<body>\{(\{|[\W\w]+?)\}|[\W\w]+?)\}|[\w\W]+?\})?\s*/, /(?<name>\b\w+\b)/, // Variable dimension /(?:\s*\[[^;]*?\])*?/, /\s*(?<end>;)/ ] .map((x) => x.source) .join(''), 'mg' ); private r_instantiation: RegExp = new RegExp( [ '(?<=^\\s*', /(?:(?<modifier>virtual|static|automatic|rand|randc|pure virtual)\s+)?/, // Symbol type, ignore packed array this.illegalMatches, /\b(?<type>[:\w]+(?:\s*\[[^\]]*?\])*?)\s*/, this.comment, /(?<params>#\s*\([\w\W]*?\))?\s*/, // Allow multiple declaration /(\b\w+\s*,\s*)*?/, ')', this.illegalMatches, // Symbol name /\b(?<name>\w+)\s*/, // Unpacked array | Ports /(?:(\[[^\]]*?\]\s*)*?|(\([\w\W]*?\))?)\s*/, /\s*(?<end>;|,|=)/ ] .map((x) => (typeof x === 'string' ? x : x.source)) .join(''), 'mg' ); private r_assert: RegExp = new RegExp( [/(?<=^\s*(?<name>\w+)\s*:\s*)/, /(?<type>assert\b)/] .map((x) => (typeof x === 'string' ? x : x.source)) .join(''), 'mg' ); private r_define: RegExp = new RegExp( [ /(?<=^\s*)/, /`(?<type>define)\s+/, /(?<name>\w+)\b/, /((?<ports>\([^\n]*\))|\s*?)/, /(?<body>([^\n]*\\\n)*([^\n]*))/, /(?<!\\)(?=\n)/ ] .map((x) => x.source) .join(''), 'mg' ); private r_label: RegExp = new RegExp( [ /\b(?<type>begin)\b/, /\s*:\s*/, /(?<name>\w+)\s*(?:\/\/.*)?$/, // Matches up to 5 nested begin/ends // This is the only way to do it with RegExp without balancing groups /(?<body>(?:\bbegin\b(?:\bbegin\b(?:\bbegin\b(?:\bbegin\b(?:\bbegin\b[\w\W]+?\bend\b|[\w\W])+?\bend\b|[\w\W])+?\bend\b|[\w\W])+?\bend\b|[\w\W])+?\bend\b|[\w\W])+?)/, /\bend\b(\s*:\s*\1)?/ ] .map((x) => x.source) .join(''), 'mg' ); private r_ports: RegExp = new RegExp( [ /(?<!^(?:\/\/|`|\n).*?)/, '(?<=', /(?:\b(?:input|output|inout)\b)\s*/, /(?<type>(?:`?\w+)?\s*(\[.*?\])*?)?\s*/, // Allow multiple declaration /(\b\w+\s*,\s*)*?/, ')', /(?<name>\b\w+\b)/, // Has to be followed by , or ) /(?=\s*((\[.*?\]\s*)*?|\/\/[^\n]*\s*)(?:,|\)))/ ] .map((x) => (typeof x === 'string' ? x : x.source)) .join(''), 'mg' ); private r_block_fast = new RegExp( [ /(?<=^\s*(?:virtual\s+)?)/, /(?<type>module|class|interface|package|program)\s+/, /(?:automatic\s+)?/, /(?<name>\w+)/, /[\w\W.]*?/, /(end\1)/ ] .map((x) => x.source) .join(''), 'mg' ); public readonly full_parse = [ this.r_decl_block, this.r_decl_class, this.r_decl_method, this.r_typedef, this.r_define, this.r_label, this.r_instantiation, this.r_assert ]; public readonly declaration_parse = [ this.r_decl_block, this.r_decl_class, this.r_decl_method, this.r_typedef, this.r_define ]; public readonly fast_parse = [this.r_block_fast]; /** Matches the regex pattern with the document's text. If a match is found, it creates a `SystemVerilogSymbol` object. Add the objects to an empty list and return it. @param document The document in which the command was invoked. @param precision How much the parser will look for, must be "full", "declaration" or "fast" @param maxDepth How many deep it will traverse the hierarchy @return A list of `SystemVerilogSymbol` objects or a thenable that resolves to such. The lack of a result can be signaled by returning `undefined`, `null`, or an empty list. */ public get_all_recursive( document: TextDocument, precision: string = 'full', maxDepth: number = -1, text?: string, offset: number = 0, parent?: string, depth: number = 0 ): Array<SystemVerilogSymbol> { let symbols: Array<SystemVerilogSymbol> = []; const sub_blocks: Array<RegExpMatchArray> = []; if (!text) { text = document.getText(); } const regexes = this.translate_precision(precision); // Find blocks for (let i = 0; i < regexes.length; i++) { // eslint-disable-next-line no-constant-condition while (true) { const match: RegExpMatchArray = regexes[i].exec(text); if (match == null) { break; } else if (match.index === 0 && parent !== undefined) { continue; // eslint-disable-line no-continue } else if (sub_blocks.some((b) => match.index >= b.index && match.index < b.index + b[0].length)) { continue; // eslint-disable-line no-continue } const symbolInfo = new SystemVerilogSymbol( match.groups.name, match.groups.type, parent, new Location( document.uri, new Range( document.positionAt(match.index + offset), document.positionAt(match.index + match[0].length + offset) ) ) ); symbols.push(symbolInfo); if (match.groups.ports && precision === 'full') { this.get_ports( document, match.groups.ports, offset + match.index + match[0].indexOf(match.groups.ports), match.groups.name ).then((out) => symbols.push(...out)); // eslint-disable-line @typescript-eslint/no-loop-func } if (match.groups.body) { sub_blocks.push(match); } } } // Recursively expand the sub-blocks if (depth !== maxDepth) { // eslint-disable-next-line guard-for-in for (const i in sub_blocks) { const match = sub_blocks[i]; const sub = this.get_all_recursive( document, precision, maxDepth, match.groups.body, match.index + offset + match[0].indexOf(match.groups.body), match.groups.name, depth + 1 ); symbols = symbols.concat(sub); } } return symbols; } private get_ports(document: TextDocument, text: string, offset, parent): Thenable<Array<SystemVerilogSymbol>> { return new Promise((resolve) => { const symbols: Array<SystemVerilogSymbol> = []; // eslint-disable-next-line no-constant-condition while (true) { const match_ports: RegExpMatchArray = this.r_ports.exec(text); if (match_ports == null) { break; } const symbolInfo = new SystemVerilogSymbol( match_ports.groups.name, match_ports.groups.type, parent, new Location( document.uri, new Range( document.positionAt(match_ports.index + offset), document.positionAt(match_ports.index + match_ports[0].length + offset) ) ) ); symbols.push(symbolInfo); } resolve(symbols); }); } private translate_precision(precision: string): Array<RegExp> { switch (precision) { case 'full': return this.full_parse; case 'declaration': return this.declaration_parse; case 'fast': return this.fast_parse; default: throw new Error('Illegal precision'); } } }
the_stack
import { BigAmount } from '@emeraldpay/bigamount'; import { isLedger, SeedReference } from '@emeraldpay/emerald-vault-core'; import { amountDecoder, BlockchainCode, Blockchains, HDPath, isEthereum } from '@emeraldwallet/core'; import { accounts, hdpathPreview, hwkey, IState } from '@emeraldwallet/store'; import { HDPathIndexes, IAddressState } from '@emeraldwallet/store/lib/hdpath-preview/types'; import { Address } from '@emeraldwallet/ui'; import { createStyles, Grid, MenuItem, Select, Table, TableBody, TableCell, TableHead, TableRow, Tooltip, Typography, } from '@material-ui/core'; import { makeStyles } from '@material-ui/core/styles'; import BeenhereIcon from '@material-ui/icons/Beenhere'; import ClearIcon from '@material-ui/icons/Clear'; import { Skeleton } from '@material-ui/lab'; import * as React from 'react'; import { ChangeEvent, Dispatch } from 'react'; import { connect } from 'react-redux'; import HDPathCounter from './HDPathCounter'; const useStyles = makeStyles( createStyles({ addressSkeleton: { paddingLeft: 4, paddingTop: 4, }, balanceSkeleton: { float: 'right', }, inactiveCheck: { color: '#d0d0d0', }, hdPathCell: { width: 160, }, hdPathIndex: { fontSize: '1rem', }, }), ); type Actions = { onAccountUpdate( account: number, ready: boolean, addresses: Partial<Record<BlockchainCode, string>>, indexes: HDPathIndexes, ): void; onReady( account: number, ready: boolean, addresses: Partial<Record<BlockchainCode, string>>, indexes: HDPathIndexes, ): void; onStart(): void; }; type OwnProps = { blockchains: BlockchainCode[]; seed: SeedReference; onChange( account: number | undefined, addresses: Partial<Record<BlockchainCode, string>>, indexes: HDPathIndexes, ): void; }; type StateProps = { disabledAccounts: number[]; initAccountId: number; isHWKey: boolean; isPreloaded: boolean; table: IAddressState[]; }; const BASE_HD_PATH: HDPath = HDPath.parse("m/44'/0'/0'/0/0"); const Component: React.FC<Actions & OwnProps & StateProps> = ({ disabledAccounts, initAccountId, isHWKey, isPreloaded, table, onAccountUpdate, onReady, onStart, }) => { const styles = useStyles(); const [accountId, setAccountId] = React.useState(initAccountId); const [initialized, setInitialized] = React.useState(false); const [indexes, setIndexes] = React.useState<HDPathIndexes>( table.reduce((carry, item) => ( { ...carry, [item.blockchain]: HDPath.parse(item.hdpath).index } ), {}), ); const addresses: Partial<Record<BlockchainCode, string>> = {}; const ready = !isHWKey || isPreloaded; table.forEach((item) => { if (item.xpub || item.address) { addresses[item.blockchain] = item.xpub ?? item.address; } }); const isActive = React.useCallback((item: IAddressState) => { const amountReader = amountDecoder(item.blockchain); return item.balance != null && amountReader(item.balance).isPositive(); }, []); let prev: IAddressState | undefined = undefined; const isChanged = React.useCallback( (item: IAddressState) => prev == null || prev.blockchain != item.blockchain || prev.hdpath != item.hdpath || prev.address != item.address, [prev], ); const renderAddress = React.useCallback((value: string | undefined | null, blockchain: BlockchainCode) => { if (value != null && value.length > 0) { return <Address address={value} disableCopy={true} />; } if (isHWKey) { const appTitle = Blockchains[blockchain].getTitle(); return ( <Skeleton variant="text" width={380} height={20} className={styles.addressSkeleton}> Open {appTitle} App on Ledger </Skeleton> ); } return <Skeleton variant="text" width={380} height={12} />; }, []); const renderBalance = React.useCallback((item: IAddressState) => { if (item.balance == null || item.balance.length == 0) { return <Skeleton variant="text" width={80} height={12} className={styles.balanceSkeleton} />; } const amountReader = amountDecoder<BigAmount>(item.blockchain); const amount = amountReader(item.balance); return <Typography>{amount.toString()}</Typography>; }, []); const onAccountChange = React.useCallback( (path: HDPath) => { setAccountId(path.account); onAccountUpdate(path.account, ready, addresses, indexes); }, [addresses, indexes, ready], ); const onIndexChange = React.useCallback( (item: IAddressState) => ({ target: { value } }: ChangeEvent<{ value: unknown }>) => { const newIndexes = { ...indexes }; newIndexes[item.blockchain] = parseInt(value as string, 10); onAccountUpdate(accountId, ready, addresses, newIndexes); }, [accountId, addresses, indexes, ready], ); React.useEffect(() => { if (!initialized) { onStart(); onAccountUpdate(accountId, ready, addresses, indexes); setInitialized(true); } }, []); React.useEffect(() => { onReady(accountId, ready, addresses, indexes); }, [isHWKey, isPreloaded]); React.useEffect(() => { setIndexes(table.reduce((carry, item) => ( { ...carry, [item.blockchain]: HDPath.parse(item.hdpath).index } ), {})); }, [table]); return ( <Grid container={true}> <Grid item={true} xs={12}> <HDPathCounter base={BASE_HD_PATH.toString()} start={accountId} disabled={disabledAccounts} onChange={onAccountChange} /> </Grid> <Grid item={true} xs={12}> <Table size="small"> <TableHead> <TableRow> <TableCell>Blockchain</TableCell> <TableCell>HD Path</TableCell> <TableCell>Address</TableCell> <TableCell align="right">Balance</TableCell> <TableCell>Coin</TableCell> <TableCell>In use</TableCell> </TableRow> </TableHead> <TableBody> {table.map((item, index) => { const hdpath = HDPath.parse(item.hdpath); const element = ( <TableRow key={item.blockchain + '-' + item.address + '-' + item.asset}> <TableCell>{isChanged(item) ? Blockchains[item.blockchain].getTitle() : ''}</TableCell> <TableCell className={styles.hdPathCell}> {isChanged(item) ? ( isEthereum(item.blockchain) ? ( <> {`m/${hdpath.purpose}'/${hdpath.coin}'/${hdpath.account}'/${hdpath.change}/`} <Select className={styles.hdPathIndex} value={hdpath.index} onChange={onIndexChange(item)}> {Array(11) .fill(null) .map((value, hdPathIndex) => ( <MenuItem key={`hdpath[${index}][${hdPathIndex}]`} value={hdPathIndex}> {hdPathIndex} </MenuItem> ))} </Select> </> ) : ( item.hdpath ) ) : ( '' )} </TableCell> <TableCell>{isChanged(item) ? renderAddress(item.address, item.blockchain) : ''}</TableCell> <TableCell align="right">{renderBalance(item)}</TableCell> <TableCell>{item.asset}</TableCell> <TableCell> <Tooltip title={isActive(item) ? 'You had used this address before' : 'New inactive address'}> {isActive(item) ? <BeenhereIcon /> : <ClearIcon className={styles.inactiveCheck} />} </Tooltip> </TableCell> </TableRow> ); prev = item; return element; })} </TableBody> </Table> </Grid> </Grid> ); }; export default connect( (state: IState, ownProps: OwnProps): StateProps => { let { seed } = ownProps; const isHWSeed = accounts.selectors.isHardwareSeed(state, seed); // if ledger seed, check if it's already used and get id if (isHWSeed && isLedger(seed)) { const ledgerSeed = accounts.selectors.findLedgerSeed(state); if (ledgerSeed?.id) { seed = { type: 'id', value: ledgerSeed.id, }; } } const disabledAccounts = seed.type == 'id' ? accounts.selectors .allWallets(state) .map(({ reserved }) => reserved?.map(({ accountId }) => accountId) ?? []) .reduce((result, accountId) => result.concat(accountId), []) : []; let accountId = 0; while (disabledAccounts.indexOf(accountId) >= 0) { accountId++; } return { disabledAccounts, initAccountId: accountId, isHWKey: isHWSeed, isPreloaded: hdpathPreview.selectors.isPreloaded(state), table: hdpathPreview.selectors.getCurrentDisplay(state, seed), }; }, // eslint-disable-next-line @typescript-eslint/no-explicit-any (dispatch: Dispatch<any>, ownProps: OwnProps): Actions => { return { onAccountUpdate(account, ready, addresses, indexes) { dispatch(hdpathPreview.actions.displayAccount(account, indexes)); ownProps.onChange(ready ? account : undefined, addresses, indexes); }, onReady(account, ready, addresses, indexes) { ownProps.onChange(ready ? account : undefined, addresses, indexes); }, onStart() { dispatch(hdpathPreview.actions.init(ownProps.blockchains, ownProps.seed)); dispatch(hdpathPreview.actions.displayAccount(0)); dispatch(hwkey.actions.setWatch(true)); }, }; }, )(Component);
the_stack
import { Credentials } from '@aws-amplify/core'; import { LocationClient, SearchPlaceIndexForPositionCommand, SearchPlaceIndexForTextCommand, } from '@aws-sdk/client-location'; import { GeoClass } from '../src/Geo'; import { AmazonLocationServiceProvider } from '../src/Providers/AmazonLocationServiceProvider'; import { Coordinates, SearchByCoordinatesOptions, SearchByTextOptions, } from '../src/types'; import { credentials, awsConfig, TestPlacePascalCase, testPlaceCamelCase, validGeometry, validGeofences, validGeofence1, singleGeofenceCamelcaseResults, batchGeofencesCamelcaseResults, } from './testData'; import { mockBatchPutGeofenceCommand, mockGetGeofenceCommand, mockListGeofencesCommand, } from './testUtils'; LocationClient.prototype.send = jest.fn(async command => { if ( command instanceof SearchPlaceIndexForTextCommand || command instanceof SearchPlaceIndexForPositionCommand ) { return { Results: [ { Place: TestPlacePascalCase, }, ], }; } }); describe('Geo', () => { afterEach(() => { jest.restoreAllMocks(); jest.clearAllMocks(); }); describe('constructor', () => { test('happy case', () => { const geo = new GeoClass(); }); }); describe('getModuleName', () => { const geo = new GeoClass(); const moduleName = geo.getModuleName(); expect(moduleName).toBe('Geo'); }); describe('pluggables', () => { test('getPluggable', () => { const geo = new GeoClass(); const provider = new AmazonLocationServiceProvider(); geo.addPluggable(provider); expect(geo.getPluggable(provider.getProviderName())).toBeInstanceOf( AmazonLocationServiceProvider ); }); test('removePluggable', () => { const geo = new GeoClass(); const provider = new AmazonLocationServiceProvider(); geo.addPluggable(provider); geo.removePluggable(provider.getProviderName()); expect(() => geo.getPluggable(provider.getProviderName())).toThrow( 'No plugin found in Geo for the provider' ); }); }); describe('AmazonLocationService is used as default provider', () => { test('creates the proper default provider', () => { const geo = new GeoClass(); geo.configure(awsConfig); expect(geo.getPluggable('AmazonLocationService')).toBeInstanceOf( AmazonLocationServiceProvider ); }); }); describe('configure', () => { test('configure with aws-exports file', () => { const geo = new GeoClass(); const config = geo.configure(awsConfig); const expected = { ...awsConfig, AmazonLocationService: awsConfig.geo.amazon_location_service, }; expect(config).toEqual(expected); }); }); describe('get map resources', () => { test('should fail if there is no provider', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.resolve(credentials); }); const geo = new GeoClass(); geo.configure(awsConfig); geo.removePluggable('AmazonLocationService'); expect(() => geo.getAvailableMaps()).toThrow( 'No plugin found in Geo for the provider' ); expect(() => geo.getDefaultMap()).toThrow( 'No plugin found in Geo for the provider' ); }); test('should tell you if there are no available map resources', () => { const geo = new GeoClass(); geo.configure({}); expect(() => geo.getAvailableMaps()).toThrow( "No map resources found in amplify config, run 'amplify add geo' to create one and run `amplify push` after" ); }); test('should get all available map resources', () => { const geo = new GeoClass(); geo.configure(awsConfig); const maps = []; const availableMaps = awsConfig.geo.amazon_location_service.maps.items; const region = awsConfig.geo.amazon_location_service.region; for (const mapName in availableMaps) { const style = availableMaps[mapName].style; maps.push({ mapName, style, region }); } expect(geo.getAvailableMaps()).toEqual(maps); }); test('should tell you if there is no map resources when running getDefaultMap', () => { const geo = new GeoClass(); geo.configure({}); expect(() => geo.getDefaultMap()).toThrow( "No map resources found in amplify config, run 'amplify add geo' to create one and run `amplify push` after" ); }); test('should tell you if there is no default map resources (but there are maps) when running getDefaultMap', () => { const geo = new GeoClass(); geo.configure({ geo: { amazon_location_service: { maps: { items: { testMap: { style: 'teststyle' } } }, }, }, }); expect(() => geo.getDefaultMap()).toThrow( "No default map resource found in amplify config, run 'amplify add geo' to create one and run `amplify push` after" ); }); test('should get the default map resource', () => { const geo = new GeoClass(); geo.configure(awsConfig); const mapName = awsConfig.geo.amazon_location_service.maps.default; const style = awsConfig.geo.amazon_location_service.maps.items[mapName].style; const region = awsConfig.geo.amazon_location_service.region; const testMap = { mapName, style, region }; const defaultMapsResource = geo.getDefaultMap(); expect(defaultMapsResource).toEqual(testMap); }); }); describe('searchByText', () => { const testString = 'starbucks'; test('should search with just text input', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.resolve(credentials); }); const geo = new GeoClass(); geo.configure(awsConfig); const results = await geo.searchByText(testString); expect(results).toEqual([testPlaceCamelCase]); const spyon = jest.spyOn(LocationClient.prototype, 'send'); const input = spyon.mock.calls[0][0].input; expect(input).toEqual({ Text: testString, IndexName: awsConfig.geo.amazon_location_service.search_indices.default, }); }); test('should search using given options with biasPosition', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.resolve(credentials); }); const geo = new GeoClass(); geo.configure(awsConfig); const searchOptions: SearchByTextOptions = { biasPosition: [12345, 67890], countries: ['USA'], maxResults: 40, searchIndexName: 'geoJSSearchCustomExample', }; const results = await geo.searchByText(testString, searchOptions); expect(results).toEqual([testPlaceCamelCase]); const spyon = jest.spyOn(LocationClient.prototype, 'send'); const input = spyon.mock.calls[0][0].input; expect(input).toEqual({ Text: testString, IndexName: searchOptions.searchIndexName, BiasPosition: searchOptions.biasPosition, FilterCountries: searchOptions.countries, MaxResults: searchOptions.maxResults, }); }); test('should search using given options with searchAreaConstraints', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.resolve(credentials); }); const geo = new GeoClass(); geo.configure(awsConfig); const searchOptions: SearchByTextOptions = { searchAreaConstraints: [123, 456, 789, 321], countries: ['USA'], maxResults: 40, searchIndexName: 'geoJSSearchCustomExample', }; const results = await geo.searchByText(testString, searchOptions); expect(results).toEqual([testPlaceCamelCase]); const spyon = jest.spyOn(LocationClient.prototype, 'send'); const input = spyon.mock.calls[0][0].input; expect(input).toEqual({ Text: testString, IndexName: searchOptions.searchIndexName, FilterBBox: searchOptions.searchAreaConstraints, FilterCountries: searchOptions.countries, MaxResults: searchOptions.maxResults, }); }); test('should throw an error if both BiasPosition and SearchAreaConstraints are given in the options', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.resolve(credentials); }); const geo = new GeoClass(); geo.configure(awsConfig); const searchOptions: SearchByTextOptions = { countries: ['USA'], maxResults: 40, searchIndexName: 'geoJSSearchCustomExample', biasPosition: [12345, 67890], searchAreaConstraints: [123, 456, 789, 321], }; await expect(geo.searchByText(testString, searchOptions)).rejects.toThrow( 'BiasPosition and SearchAreaConstraints are mutually exclusive, please remove one or the other from the options object' ); }); test('should fail if there is no provider', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.resolve(credentials); }); const geo = new GeoClass(); geo.configure(awsConfig); geo.removePluggable('AmazonLocationService'); const testString = 'starbucks'; await expect(geo.searchByText(testString)).rejects.toThrow( 'No plugin found in Geo for the provider' ); }); }); describe('searchByCoordinates', () => { const testCoordinates: Coordinates = [45, 90]; test('should search with just coordinate input', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.resolve(credentials); }); const geo = new GeoClass(); geo.configure(awsConfig); const results = await geo.searchByCoordinates(testCoordinates); expect(results).toEqual(testPlaceCamelCase); const spyon = jest.spyOn(LocationClient.prototype, 'send'); const input = spyon.mock.calls[0][0].input; expect(input).toEqual({ Position: testCoordinates, IndexName: awsConfig.geo.amazon_location_service.search_indices.default, }); }); test('should search using options when given', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.resolve(credentials); }); const geo = new GeoClass(); geo.configure(awsConfig); const searchOptions: SearchByCoordinatesOptions = { maxResults: 40, searchIndexName: 'geoJSSearchCustomExample', }; const results = await geo.searchByCoordinates( testCoordinates, searchOptions ); expect(results).toEqual(testPlaceCamelCase); const spyon = jest.spyOn(LocationClient.prototype, 'send'); const input = spyon.mock.calls[0][0].input; expect(input).toEqual({ Position: testCoordinates, IndexName: searchOptions.searchIndexName, MaxResults: searchOptions.maxResults, }); }); test('should fail if there is no provider', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.resolve(credentials); }); const geo = new GeoClass(); geo.configure(awsConfig); geo.removePluggable('AmazonLocationService'); await expect(geo.searchByCoordinates(testCoordinates)).rejects.toThrow( 'No plugin found in Geo for the provider' ); }); }); describe('saveGeofences', () => { test('saveGeofences with a single geofence', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.resolve(credentials); }); LocationClient.prototype.send = jest .fn() .mockImplementationOnce(mockBatchPutGeofenceCommand); const geo = new GeoClass(); geo.configure(awsConfig); // Check that results are what's expected const results = await geo.saveGeofences(validGeofence1); expect(results).toEqual(singleGeofenceCamelcaseResults); // Expect that the API was called with the proper input const spyon = jest.spyOn(LocationClient.prototype, 'send'); const input = spyon.mock.calls[0][0].input; const output = { Entries: [ { GeofenceId: validGeofence1.geofenceId, Geometry: { Polygon: validGeofence1.geometry.polygon, }, }, ], CollectionName: 'geofenceCollectionExample', }; expect(input).toEqual(output); }); test('saveGeofences with multiple geofences', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.resolve(credentials); }); LocationClient.prototype.send = jest .fn() .mockImplementation(mockBatchPutGeofenceCommand); const geo = new GeoClass(); geo.configure(awsConfig); // Check that results are what's expected const results = await geo.saveGeofences(validGeofences); expect(results).toEqual(batchGeofencesCamelcaseResults); // Expect that the API was called the right amount of times const expectedNumberOfCalls = Math.floor(validGeofences.length / 10) + 1; expect(LocationClient.prototype.send).toHaveBeenCalledTimes( expectedNumberOfCalls ); }); test('should fail if there is no provider', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.resolve(credentials); }); const geo = new GeoClass(); geo.configure(awsConfig); geo.removePluggable('AmazonLocationService'); await expect(geo.saveGeofences(validGeofence1)).rejects.toThrow( 'No plugin found in Geo for the provider' ); }); }); describe('getGeofence', () => { test('getGeofence returns the right geofence', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.resolve(credentials); }); LocationClient.prototype.send = jest .fn() .mockImplementationOnce(mockGetGeofenceCommand); const geo = new GeoClass(); geo.configure(awsConfig); // Check that results are what's expected const results = await geo.getGeofence('testGeofenceId'); const expected = { geofenceId: 'testGeofenceId', geometry: validGeometry, createTime: '2020-04-01T21:00:00.000Z', updateTime: '2020-04-01T21:00:00.000Z', status: 'ACTIVE', }; expect(results).toEqual(expected); // Expect that the API was called with the proper input const spyon = jest.spyOn(LocationClient.prototype, 'send'); const input = spyon.mock.calls[0][0].input; const output = { GeofenceId: 'testGeofenceId', CollectionName: 'geofenceCollectionExample', }; expect(input).toEqual(output); }); }); describe('listGeofences', () => { test('listGeofences gets the first 100 geofences when no arguments are given', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.resolve(credentials); }); LocationClient.prototype.send = jest .fn() .mockImplementationOnce(mockListGeofencesCommand); const geo = new GeoClass(); geo.configure(awsConfig); // Check that results are what's expected const results = await geo.listGeofences(); expect(results.entries.length).toEqual(100); }); test('listGeofences gets the second 100 geofences when nextToken is passed', async () => { jest.spyOn(Credentials, 'get').mockImplementation(() => { return Promise.resolve(credentials); }); LocationClient.prototype.send = jest .fn() .mockImplementation(mockListGeofencesCommand); const geo = new GeoClass(); geo.configure(awsConfig); // Check that results are what's expected const first100Geofences = await geo.listGeofences(); const second100Geofences = await geo.listGeofences({ nextToken: first100Geofences.nextToken, }); expect(second100Geofences.entries.length).toEqual(100); expect(second100Geofences.entries[0].geofenceId).toEqual( 'validGeofenceId100' ); expect(second100Geofences.entries[99].geofenceId).toEqual( 'validGeofenceId199' ); }); }); });
the_stack
import { Injectable } from '@angular/core'; import { Angulartics2 } from '../../angulartics2-core'; declare var _paq: any; export type EventTrackAction = | 'setEcommerceView' | 'addEcommerceItem' | 'trackEcommerceCartUpdate' | 'trackEcommerceOrder' | 'trackLink' | 'trackGoal' | 'trackSiteSearch' | string; export type ScopeMatomo = 'visit' | 'page'; export interface DimensionsMatomoProperties { dimension0?: string; dimension1?: string; dimension2?: string; dimension3?: string; dimension4?: string; dimension5?: string; dimension6?: string; dimension7?: string; dimension8?: string; dimension9?: string; } export interface SetEcommerceViewMatomoProperties { /** @class SetEcommerceViewMatomoProperties */ productSKU: string; /** @class SetEcommerceViewMatomoProperties */ productName: string; /** @class SetEcommerceViewMatomoProperties */ categoryName: string; /** @class SetEcommerceViewMatomoProperties */ price: string; } export interface AddEcommerceItemProperties { /** @class AddEcommerceItemProperties */ productSKU: string; /** @class AddEcommerceItemProperties */ productName: string; /** @class AddEcommerceItemProperties */ productCategory: string; /** @class AddEcommerceItemProperties */ price: string; /** @class AddEcommerceItemProperties */ quantity: string; } export interface TrackEcommerceCartUpdateMatomoProperties { /** @class TrackEcommerceCartUpdateMatomoProperties */ grandTotal: string; } export interface TrackEcommerceOrderMatomoProperties { /** @class TrackEcommerceOrderMatomoProperties */ orderId: string; /** @class TrackEcommerceOrderMatomoProperties */ grandTotal: string; /** @class TrackEcommerceOrderMatomoProperties */ subTotal: string; /** @class TrackEcommerceOrderMatomoProperties */ tax: string; /** @class TrackEcommerceOrderMatomoProperties */ shipping: string; /** @class TrackEcommerceOrderMatomoProperties */ discount: string; } export interface TrackLinkMatomoProperties { /** @class TrackLinkMatomoProperties */ url: string; /** @class TrackLinkMatomoProperties */ linkType: string; } export interface TrackGoalMatomoProperties { /** @class TrackGoalMatomoProperties */ goalId: string; /** @class TrackGoalMatomoProperties */ value: string; } export interface TrackSiteSearchMatomoProperties { /** @class TrackSiteSearchMatomoProperties */ keyword: string; /** @class TrackSiteSearchMatomoProperties */ category: string; /** @class TrackSiteSearchMatomoProperties */ searchCount: string; } export interface TrackEventMatomoProperties { /** @class TrackEventMatomoProperties */ category: string; /** @class TrackEventMatomoProperties */ name?: string; /** @class TrackEventMatomoProperties */ label?: string; /** @class TrackEventMatomoProperties */ value: number | string; } export interface SetCustomVariableMatomoProperties extends DimensionsMatomoProperties { /** @class SetCustomVariableMatomoProperties */ index: number; /** @class SetCustomVariableMatomoProperties */ name: string; /** @class SetCustomVariableMatomoProperties */ value: string; /** @class SetCustomVariableMatomoProperties */ scope: ScopeMatomo; } export interface DeleteCustomVariableMatomoProperties { /** @class DeleteCustomVariableMatomoProperties */ index: number; /** @class DeleteCustomVariableMatomoProperties */ scope: ScopeMatomo; } export type EventTrackactionProperties = | SetEcommerceViewMatomoProperties | AddEcommerceItemProperties | TrackEcommerceCartUpdateMatomoProperties | TrackEcommerceOrderMatomoProperties | TrackLinkMatomoProperties | TrackGoalMatomoProperties | TrackSiteSearchMatomoProperties | TrackEventMatomoProperties; @Injectable({ providedIn: 'root' }) export class Angulartics2Matomo { constructor(private angulartics2: Angulartics2) { if (typeof _paq === 'undefined') { console.warn('Matomo not found'); } this.angulartics2.setUsername.subscribe((x: string) => this.setUsername(x)); this.angulartics2.setUserProperties.subscribe((x: SetCustomVariableMatomoProperties) => this.setUserProperties(x), ); } startTracking(): void { this.angulartics2.pageTrack .pipe(this.angulartics2.filterDeveloperMode()) .subscribe(x => this.pageTrack(x.path)); this.angulartics2.eventTrack .pipe(this.angulartics2.filterDeveloperMode()) .subscribe(x => this.eventTrack(x.action, x.properties)); } pageTrack(path: string, title?: string) { try { if (!window.location.origin) { (window.location as any).origin = window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : ''); } _paq.push(['setDocumentTitle', title || window.document.title]); _paq.push(['setCustomUrl', window.location.origin + path]); _paq.push(['trackPageView']); } catch (e) { if (!(e instanceof ReferenceError)) { throw e; } } } resetUser() { try { _paq.push(['appendToTrackingUrl', 'new_visit=1']); // (1) forces a new visit _paq.push(['deleteCookies']); // (2) deletes existing tracking cookies to start the new visit } catch (e) { if (!(e instanceof ReferenceError)) { throw e; } } } eventTrack(action: 'setEcommerceView', properties: SetEcommerceViewMatomoProperties): void; eventTrack(action: 'addEcommerceItem', properties: AddEcommerceItemProperties): void; eventTrack( action: 'trackEcommerceCartUpdate', properties: TrackEcommerceCartUpdateMatomoProperties, ): void; eventTrack(action: 'trackEcommerceOrder', properties: TrackEcommerceOrderMatomoProperties): void; eventTrack(action: 'trackLink', properties: TrackLinkMatomoProperties): void; eventTrack(action: 'trackGoal', properties: TrackGoalMatomoProperties): void; eventTrack(action: 'trackSiteSearch', properties: TrackSiteSearchMatomoProperties): void; eventTrack(action: string, properties: TrackEventMatomoProperties): void; /** * Track a basic event in Matomo, or send an ecommerce event. * * @param action A string corresponding to the type of event that needs to be tracked. * @param properties The properties that need to be logged with the event. */ eventTrack(action: EventTrackAction, properties?: EventTrackactionProperties) { let params = []; switch (action) { /** * @description Sets the current page view as a product or category page view. When you call * setEcommerceView it must be followed by a call to trackPageView to record the product or * category page view. * * @link https://matomo.org/docs/ecommerce-analytics/#tracking-product-page-views-category-page-views-optional * @link https://developer.matomo.org/api-reference/tracking-javascript#ecommerce * * @property productSKU (required) SKU: Product unique identifier * @property productName (optional) Product name * @property categoryName (optional) Product category, or array of up to 5 categories * @property price (optional) Product Price as displayed on the page */ case 'setEcommerceView': params = [ 'setEcommerceView', (properties as SetEcommerceViewMatomoProperties).productSKU, (properties as SetEcommerceViewMatomoProperties).productName, (properties as SetEcommerceViewMatomoProperties).categoryName, (properties as SetEcommerceViewMatomoProperties).price, ]; break; /** * @description Adds a product into the ecommerce order. Must be called for each product in * the order. * * @link https://matomo.org/docs/ecommerce-analytics/#tracking-ecommerce-orders-items-purchased-required * @link https://developer.matomo.org/api-reference/tracking-javascript#ecommerce * * @property productSKU (required) SKU: Product unique identifier * @property productName (optional) Product name * @property categoryName (optional) Product category, or array of up to 5 categories * @property price (recommended) Product price * @property quantity (optional, default to 1) Product quantity */ case 'addEcommerceItem': params = [ 'addEcommerceItem', (properties as AddEcommerceItemProperties).productSKU, (properties as AddEcommerceItemProperties).productName, (properties as AddEcommerceItemProperties).productCategory, (properties as AddEcommerceItemProperties).price, (properties as AddEcommerceItemProperties).quantity, ]; break; /** * @description Tracks a shopping cart. Call this javascript function every time a user is * adding, updating or deleting a product from the cart. * * @link https://matomo.org/docs/ecommerce-analytics/#tracking-add-to-cart-items-added-to-the-cart-optional * @link https://developer.matomo.org/api-reference/tracking-javascript#ecommerce * * @property grandTotal (required) Cart amount */ case 'trackEcommerceCartUpdate': params = [ 'trackEcommerceCartUpdate', (properties as TrackEcommerceCartUpdateMatomoProperties).grandTotal, ]; break; /** * @description Tracks an Ecommerce order, including any ecommerce item previously added to * the order. orderId and grandTotal (ie. revenue) are required parameters. * * @link https://matomo.org/docs/ecommerce-analytics/#tracking-ecommerce-orders-items-purchased-required * @link https://developer.matomo.org/api-reference/tracking-javascript#ecommerce * * @property orderId (required) Unique Order ID * @property grandTotal (required) Order Revenue grand total (includes tax, shipping, and subtracted discount) * @property subTotal (optional) Order sub total (excludes shipping) * @property tax (optional) Tax amount * @property shipping (optional) Shipping amount * @property discount (optional) Discount offered (set to false for unspecified parameter) */ case 'trackEcommerceOrder': params = [ 'trackEcommerceOrder', (properties as TrackEcommerceOrderMatomoProperties).orderId, (properties as TrackEcommerceOrderMatomoProperties).grandTotal, (properties as TrackEcommerceOrderMatomoProperties).subTotal, (properties as TrackEcommerceOrderMatomoProperties).tax, (properties as TrackEcommerceOrderMatomoProperties).shipping, (properties as TrackEcommerceOrderMatomoProperties).discount, ]; break; /** * @description To manually trigger an outlink * * @link https://matomo.org/docs/tracking-goals-web-analytics/ * @link https://developer.matomo.org/guides/tracking-javascript-guide#tracking-a-click-as-an-outlink-via-css-or-javascript * * @property url (required) link url * @property linkType (optional) type of link */ case 'trackLink': params = [ 'trackLink', (properties as TrackLinkMatomoProperties).url, (properties as TrackLinkMatomoProperties).linkType, ]; break; /** * @description Tracks an Ecommerce goal * * @link https://matomo.org/docs/tracking-goals-web-analytics/ * @link https://developer.matomo.org/guides/tracking-javascript-guide#manually-trigger-goal-conversions * * @property goalId (required) Unique Goal ID * @property value (optional) passed to goal tracking */ case 'trackGoal': params = [ 'trackGoal', (properties as TrackGoalMatomoProperties).goalId, (properties as TrackGoalMatomoProperties).value, ]; break; /** * @description Tracks a site search * * @link https://matomo.org/docs/site-search/ * @link https://developer.matomo.org/guides/tracking-javascript-guide#internal-search-tracking * * @property keyword (required) Keyword searched for * @property category (optional) Search category * @property searchCount (optional) Number of results */ case 'trackSiteSearch': params = [ 'trackSiteSearch', (properties as TrackSiteSearchMatomoProperties).keyword, (properties as TrackSiteSearchMatomoProperties).category, (properties as TrackSiteSearchMatomoProperties).searchCount, ]; break; /** * @description Logs an event with an event category (Videos, Music, Games...), an event * action (Play, Pause, Duration, Add Playlist, Downloaded, Clicked...), and an optional * event name and optional numeric value. * * @link https://matomo.org/docs/event-tracking/ * @link https://developer.matomo.org/api-reference/tracking-javascript#using-the-tracker-object * * @property category * @property action * @property name (optional, recommended) * @property value (optional) */ default: // PAQ requires that eventValue be an integer, see: http://matomo.org/docs/event-tracking if ((properties as TrackEventMatomoProperties).value) { const parsed = parseInt((properties as TrackEventMatomoProperties).value as any, 10); (properties as TrackEventMatomoProperties).value = isNaN(parsed) ? 0 : parsed; } params = [ 'trackEvent', (properties as TrackEventMatomoProperties).category, action, (properties as TrackEventMatomoProperties).name || (properties as TrackEventMatomoProperties).label, // Changed in favour of Matomo documentation. Added fallback so it's backwards compatible. (properties as TrackEventMatomoProperties).value, ]; } try { _paq.push(params); } catch (e) { if (!(e instanceof ReferenceError)) { throw e; } } } setUsername(userId: string | boolean) { try { _paq.push(['setUserId', userId]); } catch (e) { if (!(e instanceof ReferenceError)) { throw e; } } } /** * Sets custom dimensions if at least one property has the key "dimension<n>", * e.g. dimension10. If there are custom dimensions, any other property is ignored. * * If there are no custom dimensions in the given properties object, the properties * object is saved as a custom variable. * * If in doubt, prefer custom dimensions. * @link https://matomo.org/docs/custom-variables/ */ setUserProperties(properties: SetCustomVariableMatomoProperties) { const dimensions = this.setCustomDimensions(properties); try { if (dimensions.length === 0) { _paq.push([ 'setCustomVariable', properties.index, properties.name, properties.value, properties.scope, ]); } } catch (e) { if (!(e instanceof ReferenceError)) { throw e; } } } /** * If you created a custom variable and then decide to remove this variable from * a visit or page view, you can use deleteCustomVariable. * * @link https://developer.matomo.org/guides/tracking-javascript-guide#deleting-a-custom-variable */ deletedUserProperties(properties: DeleteCustomVariableMatomoProperties) { try { _paq.push(['deleteCustomVariable', properties.index, properties.scope]); } catch (e) { if (!(e instanceof ReferenceError)) { throw e; } } } private setCustomDimensions(properties: SetCustomVariableMatomoProperties): string[] { const dimensionRegex: RegExp = /dimension[1-9]\d*/; const dimensions = Object.keys(properties).filter(key => dimensionRegex.exec(key)); dimensions.forEach(dimension => { const number = Number(dimension.substr(9)); _paq.push(['setCustomDimension', number, properties[dimension]]); }); return dimensions; } }
the_stack
import Dimensions = Utils.Measurements.Dimensions; import DisplayObject = etch.drawing.DisplayObject; import IDisplayContext = etch.drawing.IDisplayContext; import Point = etch.primitives.Point; import Size = minerva.Size; import {Device} from '../Device'; import {IApp} from '../IApp'; import {MainScene} from './../MainScene'; import {MenuCategory} from './MenuCategory'; import {MenuItem} from './MenuItem'; declare var App: IApp; export class Header extends DisplayObject { private _LeftOver: boolean; private _MenuCols: number[]; private _RightOver: boolean; private _SelectedCategory: number; private _SettingsOver: boolean; private _ShareOver: boolean; private _Units: number; public CreateNewMargin: number; public DropDown: number; public DropDownHeight: number; public Height: number; public Hover: number[]; public ItemsPerPage: number; public Margin: number; public MenuItems: MenuCategory[] = []; public MenuJson; public MenuOver: boolean; public Rows: number; public Tweens: any[]; Init(drawTo: IDisplayContext): void { super.Init(drawTo); this._Units = 1.7; this.Height = App.Metrics.HeaderHeight; this.Rows = 1; this.MenuItems = []; this.ItemsPerPage = App.Metrics.ItemsPerPage; this.DropDownHeight = (App.Width / (this.ItemsPerPage + 1)) / App.Unit; this.DropDown = 0; this._SelectedCategory = 0; this._MenuCols = App.ThemeManager.MenuOrder; this.Margin = 0; this.CreateNewMargin = 0; this._LeftOver = false; this._RightOver = false; this.MenuOver = false; this.Tweens = []; this.MenuJson = App.BlockCreator.MenuJson; this.Populate(this.MenuJson); } //------------------------------------------------------------------------------------------- // POPULATE //------------------------------------------------------------------------------------------- Populate(json) { var units = App.Unit; var dataType = units*10; var gutter = 60; var menuCats = []; this.Rows = 1; if (App.Metrics.Device === Device.tablet) { gutter = 40; this.Rows = 2; } if (App.Metrics.Device === Device.mobile) { this.Rows = 2; } this.ItemsPerPage = App.Metrics.ItemsPerPage; this.DropDownHeight = (this.DrawTo.Width / (this.ItemsPerPage + 1)) / units; // GET NUMBER OF CATEGORIES // var n = json.categories.length; // GET MENU & CATEGORY WIDTHS // this.Ctx.font = "400 " + dataType + "px Dosis"; this.Ctx.textAlign = "left"; var catWidth = []; var menuWidth = 0; // total text width // for (var i=0; i<n; i++) { catWidth[i] = this.Ctx.measureText(json.categories[i].name.toUpperCase()).width + (gutter*units); menuWidth += catWidth[i]; } // start x for positioning // var catX = ((this.DrawTo.Width*0.5) - (menuWidth*0.5)); var rowOffset = ((this.Rows-1)*this.Height)*units; // POPULATE MENU // for (var i=0; i<n; i++) { var name = json.categories[i].name.toUpperCase(); var point = new Point(catX + (catWidth[i]*0.5),rowOffset); var size = new Size(catWidth[i],16); menuCats[i] = new MenuCategory(point,size,name,this.DropDownHeight); catX += catWidth[i]; // POPULATE CATEGORIES // var itemN = json.categories[i].items.length; menuCats[i].Pages = Math.floor((itemN-1)/this.ItemsPerPage); for (var j=0; j<itemN; j++) { var name = json.categories[i].items[j].name.toUpperCase(); var id = json.categories[i].items[j].id; var description = ""; if (json.categories[i].items[j].description) { description = json.categories[i].items[j].description; } var point = new Point(0,((this.Height + (this.DropDownHeight*0.5))*units) + rowOffset); var size = new Size(this.DropDownHeight*units,this.DropDownHeight*units); menuCats[i].Items.push(new MenuItem(point,size,name,id,description, <MainScene>this.DrawTo)); } } this.MenuItems = menuCats; this.DelayTo(this, 0, 300, 0, "DropDown"); } //------------------------------------------------------------------------------------------- // DRAW //------------------------------------------------------------------------------------------- Draw() { super.Draw(); var units = App.Unit; var dataType = units*10; var headerType = Math.round(units*28); var thisHeight = Math.round(this.Height*units); var dropDown = Math.round(this.DropDown*units); var rowOffset = ((this.Rows-1)*this.Height)*units; // BG // App.FillColor(this.Ctx,App.Palette[2]); this.Ctx.globalAlpha = 0.16; this.Ctx.fillRect(0,0,this.DrawTo.Width,thisHeight + (5*units) + dropDown + rowOffset); // shadow this.Ctx.globalAlpha = 0.9; //0.9 this.Ctx.fillRect(0,0,this.DrawTo.Width,thisHeight + dropDown + rowOffset); // solid // TT // this.Ctx.globalAlpha = 1; App.FillColor(this.Ctx,App.Palette[App.ThemeManager.Txt]); this.Ctx.font = "200 " + headerType + "px Dosis"; if (this.Rows>1) { this.Ctx.textAlign = "center"; this.Ctx.fillText("BLOKDUST", App.Width*0.5, (thisHeight * 0.5) + (headerType * 0.38)); } else { this.Ctx.textAlign = "left"; this.Ctx.fillText("BLOKDUST", (20 + this.CreateNewMargin) * units, (thisHeight * 0.5) + (headerType * 0.38)); } // DIVIDERS // App.StrokeColor(this.Ctx,App.Palette[1]); this.Ctx.globalAlpha = 1; this.Ctx.lineWidth = 1; // Horizontal // if (dropDown>0) { this.Ctx.beginPath(); this.Ctx.moveTo(20*units,thisHeight + rowOffset); this.Ctx.lineTo(this.DrawTo.Width-(20*units),thisHeight + rowOffset); this.Ctx.stroke(); } if (this.Rows>1) { this.Ctx.beginPath(); this.Ctx.moveTo(20*units,thisHeight); this.Ctx.lineTo(this.DrawTo.Width-(20*units),thisHeight); this.Ctx.stroke(); } // Vertical // var margin = this.DropDownHeight*0.5; this.Ctx.beginPath(); for (var i=0;i<this.MenuItems.length;i++) { var cat = this.MenuItems[i]; var menuX = cat.Position.x; if (i > 0) { this.Ctx.moveTo(Math.round(menuX - (cat.Size.width*0.5)), rowOffset + (thisHeight * 0.5) - (16 * units)); this.Ctx.lineTo(Math.round(menuX - (cat.Size.width*0.5)), rowOffset + (thisHeight * 0.5) + (16 * units)); } } // between share & settings // this.Ctx.moveTo(Math.round(this.DrawTo.Width - (margin * units)), (thisHeight * 0.5) - (16 * units)); this.Ctx.lineTo(Math.round(this.DrawTo.Width - (margin * units)), (thisHeight * 0.5) + (16 * units)); this.Ctx.stroke(); // CATEGORIES // this.Ctx.textAlign = "center"; this.Ctx.font = "400 " + dataType + "px Dosis"; for (var i=0;i<this.MenuItems.length;i++) { this.Ctx.globalAlpha = 1; cat = this.MenuItems[i]; // SELECTION COLOUR // var col = this._MenuCols[i - (Math.floor(i/this._MenuCols.length)*(this._MenuCols.length))]; App.FillColor(this.Ctx,App.Palette[col]); // DRAW CAT HEADER // cat.Draw(this.Ctx, units, this,rowOffset); // ITEMS // if (this.DropDown > 0 && cat.YOffset<this.DropDownHeight) { var itemN = cat.Items.length; margin = 20 + (this.Margin*0.666); this.Ctx.lineWidth = 1; // CLIPPING RECTANGLE // var clipHeight = this.DropDown - cat.YOffset; if (clipHeight<0) { clipHeight = 0; } this.Ctx.save(); this.Ctx.beginPath(); this.Ctx.moveTo(Math.floor(margin*units),(this.Height*units) + rowOffset); this.Ctx.lineTo(Math.ceil(this.DrawTo.Width - (margin*units)),(this.Height*units) + rowOffset); this.Ctx.lineTo(Math.ceil(this.DrawTo.Width - (margin*units)),((this.Height + clipHeight)*units) + rowOffset); this.Ctx.lineTo(Math.floor(margin*units),((this.Height + clipHeight)*units) + rowOffset); this.Ctx.closePath(); this.Ctx.clip(); // DRAW ITEMS // for (var j=0; j<itemN; j++) { var xPos = (margin + (this.DropDownHeight*0.5) + (this.DropDownHeight*j) + cat.XOffset)*units; var yPos = cat.YOffset; cat.Items[j].Position.x = xPos; // TODO: shouldn't really be setting position in Draw, but worth setting up update? if (xPos > 0 && xPos < this.DrawTo.Width) { cat.Items[j].Draw(this, units, xPos, yPos); } } // END CLIP // this.Ctx.restore(); // DRAW GHOST ITEM // for (var j=0; j<itemN; j++) { if (cat.Items[j].MouseIsDown && cat.Items[j].InfoOffset==0) { this.Ctx.globalAlpha = 0.5; App.BlockSprites.DrawSprite(this, cat.Items[j].MousePoint, false, cat.Items[j].Name.toLowerCase()); } } } } // SCROLL ARROWS // if (this.DropDown > 0) { var cat = this.MenuItems[this._SelectedCategory]; margin = this.Margin; // PAGINATION // App.StrokeColor(this.Ctx,App.Palette[1]); this.Ctx.lineWidth = 2; // CLIPPING RECTANGLE // this.Ctx.save(); this.Ctx.beginPath(); this.Ctx.moveTo(0, (this.Height * units) + rowOffset); this.Ctx.lineTo(this.DrawTo.Width, (this.Height * units) + rowOffset); this.Ctx.lineTo(this.DrawTo.Width, ((this.Height + this.DropDown) * units) + rowOffset); this.Ctx.lineTo(0, ((this.Height + this.DropDown) * units) + rowOffset); this.Ctx.closePath(); this.Ctx.clip(); App.StrokeColor(this.Ctx,App.Palette[App.ThemeManager.Txt]); if (cat.CurrentPage == 0) { App.StrokeColor(this.Ctx,App.Palette[1]); } // LEFT ARROW // this.Ctx.beginPath(); this.Ctx.moveTo((margin * units) - (20 * units), ((this.Height + (this.DropDown * 0.5) - 20) * units) + rowOffset); this.Ctx.lineTo((margin * units) - (40 * units), ((this.Height + (this.DropDown * 0.5)) * units) + rowOffset); this.Ctx.lineTo((margin * units) - (20 * units), ((this.Height + (this.DropDown * 0.5) + 20) * units) + rowOffset); this.Ctx.stroke(); App.StrokeColor(this.Ctx,App.Palette[App.ThemeManager.Txt]); if (cat.CurrentPage == cat.Pages) { App.StrokeColor(this.Ctx,App.Palette[1]); } // RIGHT ARROW // this.Ctx.beginPath(); this.Ctx.moveTo(this.DrawTo.Width - (margin * units) + (20 * units), ((this.Height + (this.DropDown * 0.5) - 20) * units) + rowOffset); this.Ctx.lineTo(this.DrawTo.Width - (margin * units) + (40 * units), ((this.Height + (this.DropDown * 0.5)) * units) + rowOffset); this.Ctx.lineTo(this.DrawTo.Width - (margin * units) + (20 * units), ((this.Height + (this.DropDown * 0.5) + 20) * units) + rowOffset); this.Ctx.stroke(); this.Ctx.restore(); } // SETTINGS & SHARE HOVER // var btnWidth = this.Ctx.measureText("SHARE").width + (40*units); App.FillColor(this.Ctx,App.Palette[2]); this.Ctx.globalAlpha = 0.9; if (this._ShareOver) { var shx = this.DrawTo.Width - (margin * units) - (btnWidth*0.5); this.Ctx.beginPath(); this.Ctx.moveTo(shx - (10*units),this.Height*units); this.Ctx.lineTo(shx,(this.Height + 10)*units); this.Ctx.lineTo(shx + (10*units),this.Height*units); this.Ctx.closePath(); this.Ctx.fill(); } if (this._SettingsOver) { var shx = this.DrawTo.Width - (margin * units) + (30*units); this.Ctx.beginPath(); this.Ctx.moveTo(shx - (10*units),this.Height*units); this.Ctx.lineTo(shx,(this.Height + 10)*units); this.Ctx.lineTo(shx + (10*units),this.Height*units); this.Ctx.closePath(); this.Ctx.fill(); } // SETTINGS BTN // this.Ctx.globalAlpha = 1; margin = this.DropDownHeight*0.5; App.FillColor(this.Ctx,App.Palette[App.ThemeManager.Txt]); App.StrokeColor(this.Ctx,App.Palette[App.ThemeManager.Txt]); this.Ctx.lineWidth = 2; this.Ctx.beginPath(); this.Ctx.moveTo(this.DrawTo.Width - (margin * units) + (20 * units), ((this.Height*0.5) - 1) * units); this.Ctx.lineTo(this.DrawTo.Width - (margin * units) + (26.6 * units), ((this.Height*0.5) - 7) * units); this.Ctx.lineTo(this.DrawTo.Width - (margin * units) + (33.2 * units), ((this.Height*0.5) - 1) * units); this.Ctx.lineTo(this.DrawTo.Width - (margin * units) + (40 * units), ((this.Height*0.5) - 7) * units); this.Ctx.moveTo(this.DrawTo.Width - (margin * units) + (20 * units), ((this.Height*0.5) + 7) * units); this.Ctx.lineTo(this.DrawTo.Width - (margin * units) + (26.6 * units), ((this.Height*0.5) + 1) * units); this.Ctx.lineTo(this.DrawTo.Width - (margin * units) + (33.2 * units), ((this.Height*0.5) + 7) * units); this.Ctx.lineTo(this.DrawTo.Width - (margin * units) + (40 * units), ((this.Height*0.5) + 1) * units); // SHARE BTN // this.Ctx.moveTo(this.DrawTo.Width - (margin * units) - (btnWidth*0.5) - (5 * units), ((this.Height*0.75) - 6) * units); this.Ctx.lineTo(this.DrawTo.Width - (margin * units) - (btnWidth*0.5), ((this.Height*0.75) - 1) * units); this.Ctx.lineTo(this.DrawTo.Width - (margin * units) - (btnWidth*0.5) + (5 * units), ((this.Height*0.75) - 6) * units); this.Ctx.stroke(); this.Ctx.textAlign = "right"; this.Ctx.fillText("SHARE", this.DrawTo.Width - (margin * units) - (20 * units) ,((this.Height * 0.5)*units) + (dataType * 0.38)); this.Ctx.textAlign = "center"; } IsPaginated(cat,units) { var itemN = cat.Items.length; return (itemN > this.ItemsPerPage); } //------------------------------------------------------------------------------------------- // TWEEN //------------------------------------------------------------------------------------------- DelayTo(panel,destination,t,delay,v){ var offsetTween = new window.TWEEN.Tween({x: panel[""+v]}); offsetTween.to({x: destination}, t); offsetTween.onUpdate(function () { panel[""+v] = this.x; }); offsetTween.easing(window.TWEEN.Easing.Exponential.InOut); offsetTween.delay(delay); offsetTween.start(this.LastVisualTick); this.Tweens.push(offsetTween); } StopAllTweens() { if (this.Tweens.length) { for (var j=0; j<this.Tweens.length; j++) { this.Tweens[j].stop(); } this.Tweens = []; } } //------------------------------------------------------------------------------------------- // INTERACTION //------------------------------------------------------------------------------------------- MouseDown(point) { this.HitTests(point); var units = App.Unit; // SELECT CATEGORY // for (var i=0; i<this.MenuItems.length; i++) { if (this.MenuItems[i].Hover && !(this._SelectedCategory==i && this.DropDown>0)) { this.StopAllTweens(); this.CloseOptions(); var cat = this.MenuItems[i]; //cat.CurrentPage = 0; // RESET ITEM PAGES //cat.XOffset = 0; for (var j=0; j<cat.Items.length; j++) { cat.Items[j].InfoOffset = 0; } this.DelayTo(this,this.DropDownHeight,500,0,"DropDown"); this.DelayTo(cat,1,400,0,"Selected"); this.DelayTo(cat,0,600,250,"YOffset"); if (this.IsPaginated(cat,units)) { this.DelayTo(this,this.DropDownHeight*0.5,600,50,"Margin"); } else { this.DelayTo(this,0,600,50,"Margin"); } this._SelectedCategory = i; // I'M THE SELECTED CATEGORY // RESET NON-SELECTED CATEGORIES // for (var j=0; j<this.MenuItems.length; j++) { if (j!==i) { var cat = this.MenuItems[j]; this.DelayTo(cat,0,250,0,"Selected"); this.DelayTo(cat,this.DropDownHeight,250,0,"YOffset"); } } } } // ITEMS // if (this.DropDown>0 && !this._LeftOver && !this._RightOver) { var cat = this.MenuItems[this._SelectedCategory]; for (var i = 0; i<cat.Items.length; i++) { var item = cat.Items[i]; if (item.InfoOffset==0) { // PANEL 1 if (item.InfoHover) { this.DelayTo(item,this.DropDownHeight,350,0,"InfoOffset"); // RESET OTHERS INFO PANEL for (var j = 0; j<cat.Items.length; j++) { if (i!==j) { this.DelayTo(cat.Items[j],0,350,0,"InfoOffset"); } } } else if (cat.Items[i].Hover) { item.MouseDown(point); } } else { // PANEL 2 if (cat.Items[i].BackHover) { this.DelayTo(item,0,350,0,"InfoOffset"); } } } } // SCROLL // if (this._LeftOver) { var cat = this.MenuItems[this._SelectedCategory]; if (cat.CurrentPage > 0) { cat.CurrentPage -= 1; this.DelayTo(cat,-( ((this.ItemsPerPage)*cat.CurrentPage) * this.DropDownHeight),500,0,"XOffset"); } } if (this._RightOver) { var cat = this.MenuItems[this._SelectedCategory]; if (cat.CurrentPage < cat.Pages) { cat.CurrentPage += 1; this.DelayTo(cat,-( ((this.ItemsPerPage)*cat.CurrentPage) * this.DropDownHeight),500,0,"XOffset"); } } // SHARE // if (this._ShareOver) { this.CloseOptions(); App.MainScene.SharePanel.OpenPanel(); } // SETTINGS // if (this._SettingsOver) { this.CloseOptions(); App.MainScene.SettingsPanel.OpenPanel(); } // CLOSE DROPDOWN // if (!this.MenuOver && (this.DropDown > 0)) { this.ClosePanel(); } } ClosePanel() { this.StopAllTweens(); this.DelayTo(this,0,300,0,"DropDown"); this.DelayTo(this,0,600,50,"Margin"); for (var i=0; i<this.MenuItems.length; i++) { this.DelayTo(this.MenuItems[i],0,250,0,"Selected"); this.DelayTo(this.MenuItems[i],this.DropDownHeight,250,0,"YOffset"); } } CloseOptions() { if (App.MainScene.OptionsPanel.Scale>0) { App.MainScene.OptionsPanel.Close(); } } MouseMove(point) { this.HitTests(point); } HitTests(point) { var units = App.Unit; var grd = App.GridSize; var rowOffset = ((this.Rows-1)*this.Height)*units; // CATEGORY HIT TEST // for (var i=0; i<this.MenuItems.length; i++) { var cat = this.MenuItems[i]; cat.Hover = Dimensions.hitRect(cat.Position.x - (cat.Size.width*0.5) + (2*units), rowOffset + (5*units), cat.Size.width - (4*units), (this.Height*units) - (10*units), point.x, point.y ); //ITEMS HIT TEST // if (this._SelectedCategory==i) { for (var j=0; j<cat.Items.length; j++) { var item = cat.Items[j]; item.Hover = Dimensions.hitRect(item.Position.x - (2*grd), item.Position.y - (2*grd), 4*grd, 4*grd, point.x, point.y); item.InfoHover = Dimensions.hitRect(item.Position.x - (52*units), item.Position.y - (42*units), 24*units, 24*units, point.x, point.y); item.BackHover = Dimensions.hitRect(item.Position.x - ((this.DropDownHeight*0.5)*units), item.Position.y - ((this.DropDownHeight*0.5)*units), this.DropDownHeight*units, this.DropDownHeight*units, point.x, point.y); item.MouseMove(point, this, (this.Height + this.DropDown - 20)*units ); // could narrow to just dragged? } } } // SCROLL HIT TEST // this._LeftOver = Dimensions.hitRect(0, ((this.Height + 20)*units) + rowOffset, this.Margin*units, (this.DropDown - 40)*units, point.x, point.y); this._RightOver = Dimensions.hitRect(this.DrawTo.Width - (this.Margin*units), ((this.Height + 20)*units) + rowOffset, this.Margin*units, (this.DropDown - 40)*units, point.x, point.y); // SHARE & SETTINGS HIT TESTS // this.Ctx.font = "400 " + (units*10) + "px Dosis"; var btnWidth = this.Ctx.measureText("SHARE").width + (40*units); this._ShareOver = Dimensions.hitRect(this.DrawTo.Width - ((this.DropDownHeight*0.5)*units) - btnWidth, 5*units, btnWidth, (this.Height*units) - (10*units), point.x, point.y); this._SettingsOver = Dimensions.hitRect(this.DrawTo.Width - ((this.DropDownHeight*0.5)*units), 5*units, ((this.DropDownHeight*0.5)*units), (this.Height*units) - (10*units), point.x, point.y); // WHOLE MENU // this.MenuOver = (point.y < (((this.Height + this.DropDown)*units) + rowOffset)); } MouseUp() { // ITEMS // var cat = this.MenuItems[this._SelectedCategory]; for (var i = 0; i<cat.Items.length; i++) { cat.Items[i].MouseUp(); } } }
the_stack
import { Box, Button, Checkbox, ColumnLayout, Container, Form, FormField, Header, Input, Multiselect, SpaceBetween } from "@awsui/components-react"; import { OptionDefinition } from "@awsui/components-react/internal/components/option/interfaces"; import { MemoryHistory } from "history"; import path from "path"; import React, { useCallback, useState } from "react"; import { useDispatch } from "react-redux"; import { useLocation } from "react-router"; import { useHistory } from "react-router-dom"; import { v4 as uuid } from "uuid"; import { EnterEmailModal, isEmailSet } from "../../components/AssessShared/EnterEmailModal"; import { RuleContribSource } from "../../containers/RuleContribution"; import { HistoryState } from "../../models/locationState"; import { pushCurrentMessageUpdate } from "../../store/actions/error"; import { uploadRuleContribution } from "../../utils/sendRuleContribution"; import { validatePackageInput } from "../../utils/validateRuleContrib"; import { targetFrameworkOptions } from "../Setup/ProfileSelection"; interface Props { source: RuleContribSource; } interface KeyValProps { label: string; description?: any; children: string | undefined; } export interface PackageContribution { packageNameSource: string; packageVersionSource: string | undefined; packageName: string; packageVersion: string; packageVersionLatest: boolean; targetFramework: readonly OptionDefinition[]; comments?: string; } const PackageRuleContributionInternal: React.FC<Props> = ({ source }) => { const cachedTargetFramework = window.electron.getState("targetFramework"); const history = useHistory() as MemoryHistory; const location = useLocation<HistoryState>(); const nextPagePath = path.dirname(location.pathname); const dispatch = useDispatch(); const [email, setEmail] = useState(window.electron.getState("email")); const [showEmailModal, setShowEmailModal] = useState(!isEmailSet()); const [packageName, setPackageName] = useState(""); const [packageVersion, setPackageVersion] = useState(""); const [packageError, setPackageError] = useState(""); const [versionError, setVersionError] = useState(""); const [targetFrameworkError, setTargetFrameworkError] = useState(""); const [submitLoading, setSubmitLoading] = useState(false); const [useLatestPackageVersion, setUseLatestPackageVersion] = useState(false); const [targetFramework, setTargetFramework] = useState<readonly OptionDefinition[]>([ { label: cachedTargetFramework.label, value: cachedTargetFramework.id } ]); const [comments, setComments] = useState(""); const onCancel = () => { history.goBack(); }; const setFlashbar = useCallback( messageContent => { dispatch(pushCurrentMessageUpdate(messageContent)); }, [dispatch] ); const declineProvideEmail = () => { setShowEmailModal(false); //history.goBack(); }; const onSubmit = async () => { setSubmitLoading(true); setPackageError(""); setVersionError(""); setTargetFrameworkError(""); const submission: PackageContribution = { packageNameSource: source.packageName, packageVersionSource: source.packageVersion, packageName: packageName, packageVersion: packageVersion, packageVersionLatest: useLatestPackageVersion, targetFramework: targetFramework, comments: comments }; if (await validateInput(submission)) { const formattedSubmission = formatPackageContribution(submission); const result = await uploadRuleContribution(email, formattedSubmission, submission.packageNameSource); if (result.status.status === "Success") { setFlashbar({ messageId: uuid(), type: "success", content: "Successfully submitted replacement suggestion", dismissible: true }); history.push(nextPagePath); } else { window.electron.writeReactErrLog("PackageRuleContribution", "Failed to send rule contribution - PA UI", result.errorValue) setFlashbar({ messageId: uuid(), type: "error", content: "Unable to reach the server to submit your suggestion. Please try again.", dismissible: true }); setSubmitLoading(false); } } else { setSubmitLoading(false); } }; const validateInput = async (submission: PackageContribution) => { //Error handling for API call try { // result is type ValidationResult: // {valid: boolean, field?: string, message?: string} const result = await validatePackageInput(submission); if (!result.valid) { switch (result.field) { case "packageName": if (result.message) setPackageError(result.message); break; case "packageVersion": if (result.message) setVersionError(result.message); break; case "targetFramework": if (result.message) setTargetFrameworkError(result.message); break; case "packageName/packageVersion": if (result.message) { setPackageError(result.message); setVersionError(result.message); } break; default: break; } return false; } } catch { // Shows an error flashbar at the top setFlashbar({ messageId: uuid(), type: "error", content: "Unable to reach the server to verify the provided package. Please try again.", dismissible: true }); return false; } return true; }; const formatPackageContribution = (submission: PackageContribution) => { return { Name: submission.packageNameSource, Version: submission.packageVersionSource, Packages: [ { Name: submission.packageNameSource, Type: "Nuget" } ], Recommendations: [ { Type: "Namespace", Name: submission.packageNameSource, Value: submission.packageNameSource, KeyType: "Name", ContainingType: "", RecommendedActions: [ { Source: "External", Preferred: "Yes", TargetFrameworks: submission.targetFramework.map(t => ({ Name: t.value, TargetCPU: ["x86", "x64", "ARM32", "ARM64"] })), Description: "", Actions: submission.packageVersionLatest ? [ { Name: "AddPackage", Type: "Package", Value: submission.packageName, Description: submission.comments } ] : [ { Name: "AddPackage", Type: "Package", Value: submission.packageName, Version: submission.packageVersion, Description: submission.comments } ] } ] } ] }; }; const ValueWithLabel: React.FC<KeyValProps> = ({ label, description, children }) => ( <SpaceBetween size="xxs"> <Box color="text-label">{label}</Box> <Box color="text-body-secondary" fontSize="body-s"> {description} </Box> <div>{children}</div> </SpaceBetween> ); const recommendationForm = ( <Form actions={ <SpaceBetween direction="horizontal" size="xs"> <Button variant="link" onClick={onCancel}> Cancel </Button> <Button id="rc-send-btn" loading={submitLoading} variant="primary" onClick={onSubmit}> Submit </Button> </SpaceBetween> } > <ColumnLayout columns={4}> <FormField id = "rc-package-name" label="Package name" description="Official name of the replacement package." stretch={true} errorText={packageError} > <Input value={packageName} onChange={({ detail }) => setPackageName(detail.value.trim())} placeholder="Example.Package.Name" /> </FormField> <FormField label="Package version" description='Provide a version number or check "Latest."' stretch={true} errorText={versionError} > <Input value={packageVersion} onChange={({ detail }) => setPackageVersion(detail.value)} disabled={useLatestPackageVersion} placeholder="1.0.0" /> <Checkbox id = "rc-version-check-box" onChange={({ detail }) => { setUseLatestPackageVersion(detail.checked); if (detail.checked) { setPackageVersion(""); setVersionError(""); } }} checked={useLatestPackageVersion} > Latest </Checkbox> </FormField> <FormField label="Target framework" description="Select the target frameworks." errorText={targetFrameworkError} stretch={true} > <Multiselect selectedOptions={targetFramework} options={targetFrameworkOptions} onChange={({ detail }) => setTargetFramework(detail.selectedOptions)} /> </FormField> <FormField id = "rc-comment" label={ <span> Comments <i>- optional</i> </span> } description="Include any additonal information." stretch={true} > <Input value={comments} onChange={({ detail }) => setComments(detail.value)} /> </FormField> </ColumnLayout> </Form> ); return ( <SpaceBetween size="l"> <EnterEmailModal visible={showEmailModal} onSaveExit={() => { setEmail(window.electron.getState("email")); setShowEmailModal(false); }} onCancel={() => declineProvideEmail()} /> <Container header={ <Header variant="h2" description="Please confirm that your e-mail and NuGet package details are correct. To update your e-mail, please click the setting icon on the right corner." actions={ <Button iconName="settings" variant="icon" onClick={() => setShowEmailModal(true)} /> } > User and NuGet package details </Header> } > <ColumnLayout columns={3} variant="text-grid"> <ValueWithLabel label="E-mail">{email}</ValueWithLabel> <ValueWithLabel label="Selected package name">{source?.packageName}</ValueWithLabel> <ValueWithLabel label="Selected package version">{source?.packageVersion}</ValueWithLabel> </ColumnLayout> </Container> <Container header={ <Header variant="h2" description="Please enter your replacement suggestion here."> Suggestion form </Header> } > <SpaceBetween size="l">{recommendationForm}</SpaceBetween> </Container> </SpaceBetween> ); }; export const PackageRuleContribution = React.memo(PackageRuleContributionInternal);
the_stack
import { render } from 'mustache'; import { cyan, green } from 'chalk'; import { Module, Component } from '../parser/formatters'; import { WorldLayout, GardenLayout, WallThickness, TreeLayout, TreeWidth, LeaveSet, LeafType, Position, Size } from './layout'; const Header = `<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="icon" href="favicon.png"> <title>ngworld</title> <script src="./src/aframe-master.js"></script> <script src="./src/aframe-extras.min.js"></script> <script src="./src/aframe-controller-cursor-component.min.js"></script> </head> <body> <a-scene physics="" canvas="" keyboard-shortcuts="" vr-mode-ui=""> `; const Footer = ` <a-entity id="restart" static-body="" geometry="primitive: plane; height: 400; width: 400" position="0 -5 0" rotation="-90 0 0" material="shader: flat; color: green"></a-entity> <!-- Camera --> <a-entity id="camera" camera="active:true" universal-controls="" kinematic-body="" jump-ability="enableDoubleJump: true; distance: 3;" position="11 1.4515555555555555 45" velocity="0 0 0" gamepad-controls="" keyboard-controls="" touch-controls="" hmd-controls="" mouse-controls="" rotation="4.35447924299426 92.93375437021959 0"> <a-animation attribute="position" begin="roof" dur="0" to="134 8 2.1"></a-animation> <a-animation attribute="position" begin="start" dur="0" to="125 1.8 2.1"></a-animation> <a-entity id="blockHand" hand-controls="right" controller-cursor intersection-spawn="event: click; mixin: voxel" position="0 0 5"></a-entity> <a-cursor intersection-spawn="event: click; mixin: voxel"></a-cursor> </a-entity> <!-- Lighting and background --> <a-sky src="images/sky.jpg" radius="5000" material="color:#FFF;shader:flat;src:url(images/sky.jpg)" geometry="primitive:sphere;radius:5000;segmentsWidth:64;segmentsHeight:64" scale="-1 1 1"></a-sky> <a-entity light="color:#fff;type:ambient" data-aframe-default-light=""></a-entity> <a-entity light="color:#fff;intensity:0.2" position="-1 2 1" data-aframe-default-light=""></a-entity> <canvas class="a-canvas" width="1152" height="1598" style="height: 799px; width: 576px;"></canvas> <div class="a-enter-vr" data-a-enter-vr-no-headset="" data-a-enter-vr-no-webvr=""> <button class="a-enter-vr-button"></button> <div class="a-enter-vr-modal"> <p>Your browser does not support WebVR. To enter VR, use a VR-compatible browser or a mobile phone.</p> <a href="http://mozvr.com/#start" target="_blank">Learn more.</a> </div> </div> <div class="a-orientation-modal a-hidden"><button>Exit VR</button></div></a-scene> <script> (function () { const entities = [].slice.call(document.getElementsByTagName('a-entity')). filter(e => /leaf-\\d-\\d-\\d/.test(e.id)); entities.forEach(e => e.addEventListener('click', _ => { if (e.getAttribute('data-shaked')) { return; } else { e.setAttribute('data-shaked', true); } const treeId = e.getAttribute('data-tree-id'); const tree = document.getElementById(treeId); tree.emit('shake-front-' + treeId); setTimeout(() => { document.getElementById(treeId).emit('shake-back-' + treeId); setTimeout(() => document.getElementById(treeId).emit('shake-ready-' + treeId), 150); }, 150); e.emit('shake-' + e.id); fetch('http://localhost:8081', { method: 'post', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ file: tree.getAttribute('data-template-url'), start: e.getAttribute('data-start-offset'), end: e.getAttribute('data-end-offset') }) }); })); }()); </script> </body> </html> `; const TreeTemplate = ` <a-entity id="{{id}}" geometry="primitive: box; depth: 0.1; height: {{height}}; width: 0.2" position="{{x}} {{y}} {{z}}" rotation="0 30 0" material="shader: standard; metalness: 0.6; src: url(images/dirt.jpg); repeat: 1 4" data-template-url="{{{templateUrl}}}"> <a-entity static-body="" geometry="primitive: box; depth: 0.1; height: {{height}}; width: 0.2" position="-0.1 0 0" rotation="2 60 0" material="shader: standard; metalness: 0.6; src: url(images/dirt.jpg); repeat: 1 4"></a-entity> <a-entity static-body="" geometry="primitive: box; depth: 0.1; height: {{height}}; width: 0.2" position="0 0 0.1" rotation="2 -90 0" material="shader: standard; metalness: 0.6; src: url(images/dirt.jpg); repeat: 1 4"></a-entity> <a-entity position="0 0 0.4" rotation="-35 -30 0" text="side: double; width: 5; color: white; align: center; value: {{label}};"> </a-entity> {{{leaves}}} <a-animation attribute="rotation"¬ dur="150"¬ to="5 30 0"¬ begin="shake-front-{{id}}" repeat="0">¬ </a-animation>¬ <a-animation attribute="rotation"¬ dur="150"¬ to="-3 30 0"¬ begin="shake-back-{{id}}" repeat="0">¬ </a-animation>¬ <a-animation attribute="rotation"¬ dur="150"¬ to="0 30 0"¬ begin="shake-ready-{{id}}" repeat="0">¬ </a-animation>¬ </a-entity> `; const LeafTemplate = ` <a-entity id="{{id}}" data-start-offset="{{startOffset}}" data-end-offset="{{endOffset}}" data-tree-id="{{treeId}}" geometry="primitive: box; depth: {{depth}}; height: {{height}}; width: {{width}}" position="{{x}} {{y}} {{z}}" material="shader: standard; metalness: 0.6; color: {{color}}; repeat: 1 1"> <a-entity position="0 0 {{halfLeaf}}" rotation="0 0 0" text="side: double; width: 2; color: white; align: center; value: {{label}};"> </a-entity> <a-entity position="-{{halfLeaf}} 0 0" rotation="0 -90 0" text="side: double; width: 2; color: white; align: center; value: {{label}};"> </a-entity> <a-entity position="{{halfLeaf}} 0 0" rotation="0 90 0" text="side: double; width: 2; color: white; align: center; value: {{label}};"> </a-entity> <a-entity position="0 0 -{{halfLeaf}}" rotation="0 180 0" text="side: double; width: 2; color: white; align: center; value: {{label}};"> </a-entity> <a-animation attribute="position"¬ dur="1000"¬ begin="shake-{{id}}" fill="forwards"¬ to="{{x}} 0 {{z}}"¬ repeat="0">¬ </a-animation>¬ </a-entity> `; const BoxTemplate = ` <a-entity static-body="" geometry="primitive: box; depth: {{depth}}; height: {{height}}; width: {{width}}" position="{{x}} {{y}} {{z}}" rotation="{{rotateX}} {{rotateY}} {{rotateZ}}" material="shader: flat; transparent: true; src: url(images/fence.jpg); repeat: {{repeatWidth}} 1"> </a-entity> `; const ModuleLabelTemplate = ` <a-entity geometry="primitive: plane; height: 1.2; width: {{width}}" position="{{x}} {{y}} {{z}}" rotation="0 {{rotation}} 0" material="shader: flat; side: double; background: #ddd;"> <a-entity position="0 0 0" text="width: 4; color: #222; align: {{align}}; value: {{label}};"></a-entity> <a-entity static-body="" geometry="primitive: plane; height: 1.5; width: 2" position="0 0 -0.02" rotation="0 0 0" material="shader: flat; side: double; src: url(images/wood.jpg); repeat: 2 2;"></a-entity> <a-entity static-body="" geometry="primitive: cylinder; height: 2; radius: 0.06" position="1 -1 -0.1" rotation="0 0 0" material="shader: flat; src: url(images/log.jpg); repeat: 3 1"></a-entity> <a-entity static-body="" geometry="primitive: cylinder; height: 2; radius: 0.06" position="-1 -1 -0.1" rotation="0 0 0" material="shader: flat; src: url(images/log.jpg); repeat: 3 1"></a-entity> </a-entity> `; const FrameTemplate = ` <a-entity static-body="" geometry="primitive: box; depth: {{depth}}; height: {{height}}; width: {{width}}" position="{{x}} {{y}} {{z}}" rotation="{{rotateX}} {{rotateY}} {{rotateZ}}" material="shader: flat; src: url(images/mountain.jpg); repeat: 1 1"> </a-entity> `; const FloorTemplate = ` <a-entity static-body="" geometry="primitive: plane; height: {{depth}}; width: {{width}}" position="{{x}} {{y}} {{z}}" rotation="-90 0 0" material="shader: flat; src: url(images/grass.jpg); repeat: 200 200"></a-entity> `; interface FloorProperties { depth: number; width: number; x: number; y: number; z: number; } interface FrameProperties { x: number; y: number; z: number; depth: number; height: number; width: number; rotateX: number; rotateY: number; rotateZ: number; } interface LeafProperties { color: string; x: number; y: number; z: number; label: string; width: number; height: number; depth: number; halfLeaf: number; id: string; treeId: string; endOffset: number; startOffset: number; } interface TreeProperties { x: number; y: number; z: number; height: number; label: string; id: string; leaves: string; templateUrl: string; } interface LabelProperties { label: string; align: string; x: number; y: number; z: number; color: string; width: number; rotation: number; } interface BoxProperties { depth: number; height: number; width: number; x: number; y: number; z: number; rotateX: number; rotateY: number; rotateZ: number; repeatWidth: number; } const DoorSize = { width: 3, height: 1.5 }; const TreeHeight = 7; const TreeBase = 1; const LeafHeight = 0.7; const LeafWidth = 0.7; const LeafDepth = 0.7; const getFrontWalls = (garden: GardenLayout) => { const frontWidth = garden.size.width; const frontBottomPartWidth = frontWidth / 2 - DoorSize.width / 2; const frontBottomPartHeight = DoorSize.height; const frontBottomLeft: BoxProperties = { depth: WallThickness, height: frontBottomPartHeight, width: frontBottomPartWidth, x: garden.position.x - (frontWidth / 4 + DoorSize.width / 4), y: garden.position.y, z: garden.position.z, rotateX: 0, rotateY: 0, rotateZ: 0, repeatWidth: frontBottomPartWidth }; const frontBottomRight: BoxProperties = { depth: WallThickness, height: frontBottomPartHeight, width: frontBottomPartWidth, x: garden.position.x + frontBottomPartWidth + DoorSize.width - (frontWidth / 4 + DoorSize.width / 4), y: garden.position.y, z: garden.position.z, rotateX: 0, rotateY: 0, rotateZ: 0, repeatWidth: frontBottomPartWidth }; // const frontTop: BoxProperties = { // depth: WallThickness, // height: garden.size.height - frontBottomPartHeight - garden.position.y, // width: garden.size.width, // x: garden.position.x, // y: frontBottomPartHeight, // z: garden.position.z, // rotateX: 0, // rotateY: 0, // rotateZ: 0 // }; const moduleLabel: LabelProperties = { x: garden.position.x - DoorSize.width, y: 1.8, z: garden.position.z + 1, label: garden.name, align: 'center', color: 'white', width: 2, rotation: Math.random() * 15 * (Math.random() > 0.5 ? -1 : 1) }; return ( render(ModuleLabelTemplate, moduleLabel) + // render(BoxTemplate, frontTop) + render(BoxTemplate, frontBottomLeft) + render(BoxTemplate, frontBottomRight) ); }; const getSideWalls = (garden: GardenLayout) => { const leftWall: BoxProperties = { x: garden.position.x - garden.size.width / 2 + WallThickness / 2, y: garden.position.y, z: garden.position.z - garden.size.depth / 2 + WallThickness / 2, width: garden.size.depth, height: garden.size.height, depth: WallThickness, rotateX: 0, rotateY: 90, rotateZ: 0, repeatWidth: garden.size.depth }; const rightWall: BoxProperties = { x: garden.position.x + garden.size.width / 2 - WallThickness / 2, y: garden.position.y, z: garden.position.z - garden.size.depth / 2 - WallThickness / 2, width: garden.size.depth, height: garden.size.height, depth: WallThickness, rotateX: 0, rotateY: 90, rotateZ: 0, repeatWidth: garden.size.depth }; const backWall: BoxProperties = { x: garden.position.x, y: garden.position.y, z: garden.position.z - garden.size.depth, width: garden.size.width, height: garden.size.height, depth: WallThickness, rotateX: 0, rotateY: 0, rotateZ: 0, repeatWidth: garden.size.depth }; return render(BoxTemplate, leftWall) + render(BoxTemplate, rightWall) + render(BoxTemplate, backWall); }; const getLeaves = (leaveSets: LeaveSet[], partialId: string, treeId: string) => { const totalLevels = leaveSets.length; const renderLevel = (leaves: LeaveSet, level: number) => { const fromBottom = (leaveSets.length - 1 - level) * LeafHeight + TreeHeight / 2 - LeafHeight; const perRow = Math.ceil(Math.sqrt(leaves.length)); const result: string[] = []; let rowXWidth = perRow * LeafWidth; const initialX = -(rowXWidth - LeafWidth) / 2; const initialZ = 0; let currentX = initialX; let currentZ = initialZ; for (let i = 0; i < leaves.length; i += 1) { let leaf = leaves[i]; let leafId = partialId + '-' + i; let leafProps: LeafProperties = { startOffset: leaf.startOffset, endOffset: leaf.endOffset, label: leaf.label, color: leaf.type === LeafType.Plain ? '#8CB300' : '#C1F01A', x: currentX, y: fromBottom, z: currentZ, width: LeafWidth, height: LeafHeight, depth: LeafDepth, halfLeaf: LeafWidth / 2, treeId: treeId, id: leafId }; result.push(render(LeafTemplate, leafProps)); currentX += LeafWidth; if (currentX > rowXWidth + initialX) { currentX = initialX; currentZ += LeafDepth; } } return result.join('\n'); }; let result = ''; for (let i = leaveSets.length - 1; i >= 0; i -= 1) { result += renderLevel(leaveSets[i], i); } return result; }; const getTrees = (trees: TreeLayout[], gardenId: number) => { return trees .map((t, idx) => [ { x: t.position.x, z: t.position.z, y: 0, height: TreeHeight, label: t.name, id: 'tree-' + gardenId + '-' + idx, leaves: '', templateUrl: t.templateUrl }, t, idx ]) .map(([props, layout, treeIdx]: [TreeProperties, TreeLayout, number]) => { const leaves = getLeaves(layout.leaves, 'leaf-' + gardenId + '-' + treeIdx, props.id); props.leaves = leaves; return render(TreeTemplate, props); }) .join('\n'); }; const renderGarden = (garden: GardenLayout, idx: number) => { return getTrees(garden.trees, idx) + getFrontWalls(garden) + getSideWalls(garden); }; const renderFrame = (p: Position, size: Size) => { const front: FrameProperties = { x: p.x, y: p.y, z: p.z, width: size.width, depth: 1, height: size.height, rotateX: 0, rotateY: 0, rotateZ: 0 }; const back: FrameProperties = { x: p.x, y: p.y, z: p.z - size.depth, width: size.width, depth: 1, height: size.height, rotateX: 0, rotateY: 0, rotateZ: 0 }; const left: FrameProperties = { x: p.x - size.width / 2, y: p.y, z: p.z - size.depth / 2, width: size.depth, depth: 1, height: size.height, rotateX: 0, rotateY: 90, rotateZ: 0 }; const right: FrameProperties = { x: p.x + size.width / 2, y: p.y, z: p.z - size.depth / 2, width: size.depth, depth: 1, height: size.height, rotateX: 0, rotateY: 90, rotateZ: 0 }; return ( render(FrameTemplate, front) + render(FrameTemplate, back) + render(FrameTemplate, left) + render(FrameTemplate, right) ); }; const renderFloor = (p: Position, s: Size) => { const template: FloorProperties = { x: p.x, y: -0.2, z: p.z, width: s.width + p.x, depth: s.depth + p.z }; return render(FloorTemplate, template); }; export const renderWorld = (layout: WorldLayout) => { console.log(cyan('Rendering world...')); const gardens = layout.gardens.map((g, idx) => renderGarden(g, idx)).join('\n'); const frame = renderFrame(layout.position, layout.size); const floor = renderFloor(layout.position, layout.size); const world = Header + gardens + frame + floor + Footer; console.log(green('World rendered!')); return world; };
the_stack
import { produce } from 'immer'; import clone from 'lodash-es/clone'; import fill from 'lodash-es/fill'; import includes from 'lodash-es/includes'; import isFinite from 'lodash-es/isFinite'; import isNumber from 'lodash-es/isNumber'; import values from 'lodash-es/values'; import { DiagramMakerData, DiagramMakerNode } from 'diagramMaker/state/types'; import { HierarchicalLayoutConfig } from './layoutActions'; // Internal type for manipulating nodes interface GraphNode { id: string; neighbors: number[]; parents: number[]; isFixed?: boolean; x?: number; y?: number; } enum TraversalStatus { NOT_VISITED, PROCESSING, VISITED } interface NodeDirection { angle: number; isFixed: boolean; } export default function hierarchicalLayout<NodeType, EdgeType>( state: DiagramMakerData<NodeType, EdgeType>, layoutConfig: HierarchicalLayoutConfig ): DiagramMakerData<NodeType, EdgeType> { // Initialize config values with defaults, if needed. const distanceMin = layoutConfig.distanceMin; const distanceMax = isNumber(layoutConfig.distanceMax) ? layoutConfig.distanceMax : (3 * distanceMin); const distanceDeclineRate = isNumber(layoutConfig.distanceDeclineRate) ? layoutConfig.distanceDeclineRate : 0.3; const initialGravityAngle = isNumber(layoutConfig.gravityAngle) ? normalizeAngle(-layoutConfig.gravityAngle) // As Y-axis points down, the angle must be inverted. : (Math.PI * 0.5); // Default gravity points straight down. const gravityStrength = isNumber(layoutConfig.gravityStrength) ? layoutConfig.gravityStrength : 0.0; // Construct an initial graph without calculated positioning. const fixedNodeIdSet: { [key: string]: boolean } = {}; layoutConfig.fixedNodeIds.forEach(nodeId => fixedNodeIdSet[nodeId] = true); const fixedNodes: number[] = []; const nodeIndex: { [key: string]: number } = {}; const graph: GraphNode[] = values(state.nodes).map((node, index) => { nodeIndex[node.id] = index; const graphNode: GraphNode = { id: node.id, neighbors: [], parents: [] }; const position = node.diagramMakerData.position; const size = node.diagramMakerData.size; if (fixedNodeIdSet[node.id]) { graphNode.isFixed = true; graphNode.x = position.x + size.width / 2; graphNode.y = position.y + size.height / 2; fixedNodes.push(index); } return graphNode; }); // Add neighbor information based on DiagramMaker edges. values(state.edges).forEach((edge) => { const srcIndex = nodeIndex[edge.src]; const destIndex = nodeIndex[edge.dest]; // Note: // The directionality of the graph is ignored. // No matter if we're laying out children nodes around the parent, // or parent nodes around the child, the same rules spread in both directions. graph[srcIndex].neighbors.push(destIndex); graph[destIndex].neighbors.push(srcIndex); }); // Calculate positioning during BFS traversal. const nodeStatus: TraversalStatus[] = graph.map( node => node.isFixed ? TraversalStatus.VISITED : TraversalStatus.NOT_VISITED ); let currentLayer: number[] = fixedNodes; let r = distanceMax; while (currentLayer.length) { // Mark current layer as VISITED. currentLayer.forEach((node) => { nodeStatus[node] = TraversalStatus.VISITED; }); // Calculate next layer by traversing neighbors of the current layer. const nextLayer: number[] = []; currentLayer.forEach((node) => { graph[node].neighbors.forEach((neighbor) => { if (nodeStatus[neighbor] === TraversalStatus.VISITED) { return; } graph[neighbor].parents.push(node); if (nodeStatus[neighbor] === TraversalStatus.NOT_VISITED) { nextLayer.push(neighbor); nodeStatus[neighbor] = TraversalStatus.PROCESSING; } }); }); // Position the next layer. // Start with the nodes that are connected to multiple fixed parents. // Place them in the centroid of all of their parents. nextLayer.forEach((node) => { if (graph[node].parents.length > 1) { const parentsCount = graph[node].parents.length; const sumX = graph[node].parents.reduce((sum, parent) => sum + (graph[parent].x as number), 0); graph[node].x = sumX / parentsCount; const sumY = graph[node].parents.reduce((sum, parent) => sum + (graph[parent].y as number), 0); graph[node].y = sumY / parentsCount; graph[node].isFixed = true; } }); // Calculate the fixtures (angles that are already fixed) for each node in the current layer. const fixtures: NodeDirection[][] = graph.map(node => []); currentLayer.forEach((node) => { graph[node].neighbors.forEach((neighbor) => { if (graph[neighbor].isFixed) { fixtures[node].push({ angle: getAngle(graph[node], graph[neighbor]), isFixed: true }); } }); sortNodeDirections(fixtures[node]); }); // Distribute all remaining free-hanging nodes between the fixtures. currentLayer.forEach((node) => { let gravityAngle = initialGravityAngle; const meanOfFixtures = meanOfAngles(fixtures[node].map(fixture => fixture.angle)); if (!isNaN(meanOfFixtures)) { gravityAngle = normalizeAngle(meanOfFixtures + Math.PI); } const freeNodesCount = graph[node].neighbors.length - fixtures[node].length; const arrangement = arrangeEvenly(freeNodesCount, fixtures[node], gravityAngle); applyGravity(arrangement, gravityAngle, gravityStrength); let arrangementIndex = 0; graph[node].neighbors.forEach((neighbor) => { if (!graph[neighbor].isFixed) { while (arrangement[arrangementIndex].isFixed) { arrangementIndex += 1; } const angle = arrangement[arrangementIndex].angle; graph[neighbor].x = (graph[node].x as number) + Math.cos(angle) * r; graph[neighbor].y = (graph[node].y as number) + Math.sin(angle) * r; graph[neighbor].isFixed = true; arrangementIndex += 1; } }); }); // Move on to the next layer. currentLayer = nextLayer; r = distanceMin + (r - distanceMin) * (1 - distanceDeclineRate); } // Update the original data with the calculated values. return produce(state, (draftState) => { graph.forEach((node) => { if (isFinite(node.x) && isFinite(node.y)) { const nodeSize = draftState.nodes[node.id].diagramMakerData.size; const diagramMakerNode = draftState.nodes[node.id].diagramMakerData.position = { x: (node.x as number) - nodeSize.width / 2, y: (node.y as number) - nodeSize.height / 2 }; } }); }); } /** * Arranges `nodesCount` number of angles between `fixtures` in the most even way. * * More technically: * Maximizes the smallest angle between any two nodes (free and fixed). */ function arrangeEvenly(nodesCount: number, fixtures: NodeDirection[], defaultAngle: number): NodeDirection[] { const arrangement: NodeDirection[] = []; // No nodes to arrange? Return fixtures unchanged. if (nodesCount <= 0) { return clone(fixtures); } // If there is no fixtures, just arrange nodes evenly. if (!fixtures.length) { const angleIncrement = (Math.PI * 2) / nodesCount; // General orientation should point to `defaultAngle`: // - For odd number of nodes, one of the nodes points to `defaultAngle`. // - For even number of nodes, `defaultAngle` is in the middle between two consecutive nodes. let angle = (nodesCount % 2 === 0) ? normalizeAngle(defaultAngle + angleIncrement * 0.5) : defaultAngle; for (let i = 0; i < nodesCount; i += 1) { arrangement.push({ angle, isFixed: false }); angle = normalizeAngle(angle + angleIncrement); } sortNodeDirections(arrangement); return arrangement; } // Calculate the segments bewteen the fixtures (in angles). const segments = []; for (let i = 1; i < fixtures.length; i += 1) { segments.push(fixtures[i].angle - fixtures[i - 1].angle); } segments.push((fixtures[0].angle + Math.PI * 2) - fixtures[fixtures.length - 1].angle); // Use dynamic programming to figure out the best arrangement. // `minAngle[x][y]` equals to the minimum angle in optimal arrangement // of Y number nodes in the 0..X segments. // // As example `minAngle[5][3]` equals to the minimal angle between any nodes, // when we arrange 5 nodes in segments 0, 1 and 2. // Initialize the table with 0 in each position. That's the worst outcome for optimal arrangement. const minAngle: number[][] = []; const bestNodesCount: number[][] = []; for (let segmentIndex = 0; segmentIndex < segments.length; segmentIndex += 1) { minAngle.push([]); bestNodesCount.push([]); for (let nodes = 0; nodes <= nodesCount; nodes += 1) { minAngle[segmentIndex].push(0); bestNodesCount[segmentIndex].push(0); } } // Initialize `minAngle[X][0]`. This is when we don't have any nodes to arrange. minAngle[0][0] = segments[0]; bestNodesCount[0][0] = 0; for (let segmentIndex = 1; segmentIndex < segments.length; segmentIndex += 1) { minAngle[segmentIndex][0] = Math.min(segments[segmentIndex], minAngle[segmentIndex - 1][0]); bestNodesCount[segmentIndex][0] = 0; } // Initialize `minAngle[0][X]`. This is when we arrange X nodes evenly in the first segment. for (let nodes = 1; nodes <= nodesCount; nodes += 1) { // Squeezing X nodes in a segment splits it into (X + 1) equal subsegments. minAngle[0][nodes] = segments[0] / (nodes + 1); bestNodesCount[0][nodes] = nodes; } // Calculate the minimal angle for each remaining cell. for (let segmentIndex = 1; segmentIndex < segments.length; segmentIndex += 1) { for (let nodes = 1; nodes <= nodesCount; nodes += 1) { let best = Math.min(minAngle[segmentIndex - 1][nodes], segments[segmentIndex]); let bestNodes = 0; for (let x = 1; x <= nodes; x += 1) { const current = Math.min(minAngle[segmentIndex - 1][nodes - x], segments[segmentIndex] / (x + 1)); if (current >= best) { best = current; bestNodes = x; } } minAngle[segmentIndex][nodes] = best; bestNodesCount[segmentIndex][nodes] = bestNodes; } } // Based on the results, extract the optimal number of nodes that should go in each segment. const segmentNodesCount: number[] = segments.map(segment => 0); let remaining = nodesCount; for (let segmentIndex = segments.length - 1; segmentIndex >= 0; segmentIndex -= 1) { segmentNodesCount[segmentIndex] = bestNodesCount[segmentIndex][remaining]; remaining -= segmentNodesCount[segmentIndex]; } // Finally, calculate and return the actual angles. for (let segmentIndex = 0; segmentIndex < segments.length; segmentIndex += 1) { arrangement.push(fixtures[segmentIndex]); let angle = fixtures[segmentIndex].angle; const angleIncrement = segments[segmentIndex] / (segmentNodesCount[segmentIndex] + 1); for (let node = 0; node < segmentNodesCount[segmentIndex]; node += 1) { angle += angleIncrement; angle = normalizeAngle(angle); arrangement.push({ angle, isFixed: false }); } } sortNodeDirections(arrangement); return arrangement; } /** * Moves all nodes in the direction of `gravityAngle` while not pressing too hard against the neighbors. * Fixed directions are not moved. */ function applyGravity(directions: NodeDirection[], gravityAngle: number, gravityStrength: number): void { // No nodes or no gravity, nothing to do here. if (!directions.length || gravityStrength <= 0) { return; } // If it's one node and it's free, move it to `gravityAngle`. // If it's fixed, nothing to do. if (directions.length === 1) { if (!directions[0].isFixed) { directions[0].angle = gravityAngle; } return; } const incIndex = (i: number) => ((i + 1) % directions.length); const decIndex = (i: number) => (i === 0 ? (directions.length - 1) : (i - 1)); // Find two nodes exactly before and after `gravityAngle`. let nextIndex = 0; while (nextIndex < directions.length - 1 && directions[nextIndex].angle < gravityAngle) { nextIndex += 1; } if (directions[nextIndex].angle < gravityAngle) { nextIndex = 0; } const previousIndex = decIndex(nextIndex); const anglePrevious = directions[previousIndex].angle; const angleNext = directions[nextIndex].angle; // Push `previousIndex` and `nextIndex` towards `gravityAngle` with a "special care": // Consider which of them are fixed and which are free and push the closest right to `gravityAngle`, // while also ensuring that we don't press towards the neighbor too hard. if (directions[previousIndex].isFixed && directions[nextIndex].isFixed) { // Both sides are fixed, nothing to do. } else if (directions[previousIndex].isFixed) { // If `previousIndex` is fixed, move the free `nextIndex` towards gravity. const pushedAngle = pushTowardsAngle(angleNext, anglePrevious, gravityStrength); if (angleBetween(gravityAngle, anglePrevious) >= angleBetween(pushedAngle, anglePrevious)) { // If moving node directly to `gravityAngle` won't squeeze it too hard to neighbor, let's do it. directions[nextIndex].angle = gravityAngle; } else { // However if it gets too close, use regular `pushTowardsAngle` formula instead. directions[nextIndex].angle = pushedAngle; } } else if (directions[nextIndex].isFixed) { // If `nextIndex` is fixed, move the free `previousIndex` towards gravity. const pushedAngle = pushTowardsAngle(anglePrevious, angleNext, gravityStrength); if (angleBetween(gravityAngle, angleNext) >= angleBetween(pushedAngle, angleNext)) { // If moving node directly to `gravityAngle` won't squeeze it too hard to neighbor, let's do it. directions[previousIndex].angle = gravityAngle; } else { // However if it gets too close, use regular `pushTowardsAngle` formula instead. directions[previousIndex].angle = pushedAngle; } } else { // Both `previousIndex` and `nextIndex` are free. const anglePreviousToGravity = angleBetween(anglePrevious, gravityAngle); const angleNextToGravity = angleBetween(angleNext, gravityAngle); if (Math.abs(angleNextToGravity - anglePreviousToGravity) < 0.01) { // Two free nodes are equally close to gravity. Move them equally closer, based on `gravityStrength`. directions[previousIndex].angle = pushTowardsAngle(directions[previousIndex].angle, gravityAngle, gravityStrength); directions[nextIndex].angle = pushTowardsAngle(directions[nextIndex].angle, gravityAngle, gravityStrength); } else if (anglePreviousToGravity <= angleNextToGravity) { // `previousIndex` is closer to `gravityAngle`. Move it right to `gravityAngle`. directions[previousIndex].angle = gravityAngle; directions[nextIndex].angle = pushTowardsAngle(angleNext, gravityAngle, gravityStrength); } else { // `nextIndex` is closer to `gravityAngle`. Move it right to `gravityAngle`. directions[nextIndex].angle = gravityAngle; directions[previousIndex].angle = pushTowardsAngle(anglePrevious, gravityAngle, gravityStrength); } } // Going counter-clockwise until we reach the diamterically opposite angle to `gravityAngle`. let index = incIndex(nextIndex); while (index !== previousIndex && isLeftTurn(gravityAngle, directions[index].angle)) { if (!directions[index].isFixed) { directions[index].angle = pushTowardsAngle(directions[index].angle, directions[decIndex(index)].angle, gravityStrength); } index = incIndex(index); } // Going clockwise until we reach the diamterically opposite angle to `gravityAngle`. index = decIndex(previousIndex); while (index !== nextIndex && !isLeftTurn(gravityAngle, directions[index].angle)) { if (!directions[index].isFixed) { directions[index].angle = pushTowardsAngle(directions[index].angle, directions[incIndex(index)].angle, gravityStrength); } index = decIndex(index); } sortNodeDirections(directions); } /** * Most functions expect directions to be sorted by the `angle`, * so that the traversal will happen around the circle. */ function sortNodeDirections(directions: NodeDirection[]): void { directions.sort((a, b) => a.angle - b.angle); } /** * Pushes the `angle` towards `targetAngle` with `strength`. * * The higher `strength` is, the closer `angle` will move towards: * - `strength` of 1.0 means that `targetAngle` pushes away with the same force as `angle` is being pushed towards. * - `strength` of 2.0 means that `targetAngle` is twice as strong as the `angle`. */ function pushTowardsAngle(angle: number, targetAngle: number, strength: number): number { const angleIncrement = (strength / (strength + 1)) * angleBetween(angle, targetAngle); if (isLeftTurn(angle, targetAngle)) { return normalizeAngle(angle + angleIncrement); } return normalizeAngle(angle - angleIncrement); } /** * Returns the mean (or "average") of `angles`. * Returns NaN, when angles are dimaterically opposite. */ function meanOfAngles(angles: number[]): number { if (!angles.length) { return NaN; } // https://en.wikipedia.org/wiki/Mean_of_circular_quantities#Mean_of_angles const x = angles .map(a => Math.cos(a)) .reduce((acc, value) => acc + value, 0); const y = angles .map(a => Math.sin(a)) .reduce((acc, value) => acc + value, 0); if (Math.abs(x) < 0.001 && Math.abs(y) < 0.001) { // The centroid is very close to the origin (0, 0) // which means that all angles balance each other out. return NaN; } return normalizeAngle(Math.atan2(y, x)); } /** * Returns true when `angle` is left (or "counter-clockwise") to `angleBase`. * * An angle is not considered left to itself: * isLeftTurn(a, a) -> false * * An angle is considered left to diametrically opposite angle: * isLeftTurn(a, a + PI) -> true */ function isLeftTurn(angleBase: number, angle: number): boolean { const angleOpposite = normalizeAngle(angleBase + Math.PI); if (angleBase < Math.PI) { return (angle > angleBase && angle <= angleOpposite); } return (angle > angleBase || angle <= angleOpposite); } /** * Finds the smaller angle between two angles. */ function angleBetween(angleA: number, angleB: number): number { const angle = Math.abs(angleA - angleB); return Math.min(angle, Math.PI * 2 - angle); } /** * Calculates the angle of vector from `node1` to `node2` relative to X axis. */ function getAngle(node1: GraphNode, node2: GraphNode): number { const x1 = node1.x as number; const y1 = node1.y as number; const x2 = node2.x as number; const y2 = node2.y as number; // Math.atan2(y, x) takes Y coordinate first. WAT?! // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atan2 const angle = Math.atan2(y2 - y1, x2 - x1); // Math.atan2(y, x) returns angle in the range [-PI, PI]. // Converting it to the positive range [0, 2 * PI] return normalizeAngle(angle); } /** * Normalizes any angle to range [0, 2 * PI). */ function normalizeAngle(angle: number): number { let result = angle; while (result < 0) { result += Math.PI * 2; } while (result >= Math.PI * 2) { result -= Math.PI * 2; } return result; }
the_stack
import {Query} from '@parca/parser'; import {QueryServiceClient, ProfileTypesResponse} from '@parca/client'; import {RpcError} from '@protobuf-ts/runtime-rpc'; import {ProfileSelection} from '@parca/profile'; import React, {useEffect, useState} from 'react'; import ProfileMetricsGraph from '../ProfileMetricsGraph'; import MatchersInput from '../MatchersInput'; import MergeButton from './MergeButton'; import CompareButton from './CompareButton'; import Card from '../Card'; import { DateTimeRangePicker, DateTimeRange, Select, Button, ButtonGroup, SelectElement, useGrpcMetadata, } from '../'; import {CloseIcon} from '@parca/icons'; import cx from 'classnames'; export interface QuerySelection { expression: string; from: number; to: number; merge: boolean; timeSelection: string; } interface ProfileSelectorProps { queryClient: QueryServiceClient; querySelection: QuerySelection; selectProfile: (source: ProfileSelection) => void; selectQuery: (query: QuerySelection) => void; closeProfile: () => void; enforcedProfileName: string; profileSelection: ProfileSelection | null; comparing: boolean; onCompareProfile: () => void; } interface WellKnownProfiles { [key: string]: { name: string; help: string; }; } export interface IProfileTypesResult { response?: ProfileTypesResponse; error?: RpcError; } export const useProfileTypes = (client: QueryServiceClient): IProfileTypesResult => { const [result, setResult] = useState<IProfileTypesResult>({}); const metadata = useGrpcMetadata(); useEffect(() => { const call = client.profileTypes({}, {meta: metadata}); call.response .then(response => setResult({response: response})) .catch(error => setResult({error: error})); }, [client, metadata]); return result; }; const wellKnownProfiles: WellKnownProfiles = { 'block:contentions:count:contentions:count': { name: 'Block Contentions Total', help: 'Stack traces that led to blocking on synchronization primitives.', }, 'block:delay:nanoseconds:contentions:count': { name: 'Block Contention Time Total', help: 'Time delayed stack traces caused by blocking on synchronization primitives.', }, // Unfortunately, fgprof does not set the period type and unit. 'fgprof:samples:count::': { name: 'Fgprof Samples Total', help: 'CPU profile samples observed regardless of their current On/Off CPU scheduling status', }, // Unfortunately, fgprof does not set the period type and unit. 'fgprof:time:nanoseconds::': { name: 'Fgprof Samples Time Total', help: 'CPU profile measured regardless of their current On/Off CPU scheduling status in nanoseconds', }, 'goroutine:goroutine:count:goroutine:count': { name: 'Goroutine Created Total', help: 'Stack traces that created all current goroutines.', }, 'memory:alloc_objects:count:space:bytes': { name: 'Memory Allocated Objects Total', help: 'A sampling of all past memory allocations by objects.', }, 'memory:alloc_space:bytes:space:bytes': { name: 'Memory Allocated Bytes Total', help: 'A sampling of all past memory allocations in bytes.', }, 'memory:alloc_objects:count:space:bytes:delta': { name: 'Memory Allocated Objects Delta', help: 'A sampling of all memory allocations during the observation by objects.', }, 'memory:alloc_space:bytes:space:bytes:delta': { name: 'Memory Allocated Bytes Delta', help: 'A sampling of all memory allocations during the observation in bytes.', }, 'memory:inuse_objects:count:space:bytes': { name: 'Memory In-Use Objects', help: 'A sampling of memory allocations of live objects by objects.', }, 'memory:inuse_space:bytes:space:bytes': { name: 'Memory In-Use Bytes', help: 'A sampling of memory allocations of live objects by bytes.', }, 'mutex:contentions:count:contentions:count': { name: 'Mutex Contentions Total', help: 'Stack traces of holders of contended mutexes.', }, 'mutex:delay:nanoseconds:contentions:count': { name: 'Mutex Contention Time Total', help: 'Time delayed stack traces caused by contended mutexes.', }, 'process_cpu:cpu:nanoseconds:cpu:nanoseconds:delta': { name: 'Process CPU Nanoseconds', help: 'CPU profile measured by the process itself in nanoseconds.', }, 'process_cpu:samples:count:cpu:nanoseconds:delta': { name: 'Process CPU Samples', help: 'CPU profile samples observed by the process itself.', }, 'parca_agent_cpu:samples:count:cpu:nanoseconds:delta': { name: 'CPU Samples', help: 'CPU profile samples observed by Parca Agent.', }, }; function profileSelectElement(name: string): SelectElement { const wellKnown = wellKnownProfiles[name]; if (wellKnown === undefined) return {active: <>{name}</>, expanded: <>{name}</>}; const title = wellKnown.name.replace(/ /g, '\u00a0'); return { active: <>{title}</>, expanded: ( <> <span>{title}</span> <br /> <span className="text-xs">{wellKnown.help}</span> </> ), }; } const ProfileSelector = ({ queryClient, querySelection, selectProfile, selectQuery, closeProfile, enforcedProfileName, profileSelection, comparing, onCompareProfile, }: ProfileSelectorProps): JSX.Element => { const {response, error} = useProfileTypes(queryClient); const profileNames = (error === undefined || error == null) && response !== undefined && response != null ? response.types.map( type => `${type.name}:${type.sampleType}:${type.sampleUnit}:${type.periodType}:${ type.periodUnit }${type.delta ? ':delta' : ''}` ) : []; const profileLabels = profileNames.map(name => ({ key: name, element: profileSelectElement(name), })); const [timeRangeSelection, setTimeRangeSelection] = useState( DateTimeRange.fromRangeKey(querySelection.timeSelection) ); const [queryExpressionString, setQueryExpressionString] = useState(querySelection.expression); useEffect(() => { if (enforcedProfileName !== '') { const [q, changed] = Query.parse(querySelection.expression).setProfileName( enforcedProfileName ); if (changed) { setQueryExpressionString(q.toString()); return; } } setQueryExpressionString(querySelection.expression); }, [enforcedProfileName, querySelection.expression]); const enforcedProfileNameQuery = (): Query => { const pq = Query.parse(queryExpressionString); const [q] = pq.setProfileName(enforcedProfileName); return q; }; const query = enforcedProfileName !== '' ? enforcedProfileNameQuery() : Query.parse(queryExpressionString); const selectedProfileName = query.profileName(); const setNewQueryExpression = (expr: string, merge: boolean): void => { selectQuery({ expression: expr, from: timeRangeSelection.getFromMs(), to: timeRangeSelection.getToMs(), merge: merge, timeSelection: timeRangeSelection.getRangeKey(), }); }; const setQueryExpression = (): void => { setNewQueryExpression(query.toString(), false); }; const addLabelMatcher = (key: string, value: string): void => { const [newQuery, changed] = Query.parse(queryExpressionString).setMatcher(key, value); if (changed) { setNewQueryExpression(newQuery.toString(), false); } }; const setMergedSelection = (): void => { setNewQueryExpression(queryExpressionString, true); }; const setMatchersString = (matchers: string): void => { const newExpressionString = `${selectedProfileName}{${matchers}}`; setQueryExpressionString(newExpressionString); }; const setProfileName = (profileName: string): void => { const [newQuery, changed] = query.setProfileName(profileName); if (changed) { const q = newQuery.toString(); setQueryExpressionString(q); } }; const handleCompareClick = (): void => onCompareProfile(); const searchDisabled = queryExpressionString === undefined || queryExpressionString === '' || queryExpressionString === '{}'; const mergeDisabled = selectedProfileName === '' || querySelection.expression === undefined; const compareDisabled = selectedProfileName === '' || querySelection.expression === undefined; return ( <Card> <Card.Header className={cx(comparing === true && 'overflow-x-scroll')}> <div className="flex space-x-4"> {comparing && ( <button type="button" onClick={() => closeProfile()}> <CloseIcon /> </button> )} <Select items={profileLabels} selectedKey={selectedProfileName} onSelection={setProfileName} placeholder="Select profile..." /> <MatchersInput queryClient={queryClient} setMatchersString={setMatchersString} runQuery={setQueryExpression} currentQuery={query} /> <DateTimeRangePicker onRangeSelection={setTimeRangeSelection} range={timeRangeSelection} /> {searchDisabled ? ( <div> <Button disabled={true}>Search</Button> </div> ) : ( <> <ButtonGroup style={{marginRight: 5}}> <MergeButton disabled={mergeDisabled} onClick={setMergedSelection} /> {!comparing && ( <CompareButton disabled={compareDisabled} onClick={handleCompareClick} /> )} </ButtonGroup> <div> <Button onClick={(e: React.MouseEvent<HTMLElement>) => { e.preventDefault(); setQueryExpression(); }} > Search </Button> </div> </> )} </div> </Card.Header> {!querySelection.merge && ( <Card.Body> {querySelection.expression !== undefined && querySelection.expression.length > 0 && querySelection.from !== undefined && querySelection.to !== undefined && (profileSelection == null || profileSelection.Type() !== 'merge') ? ( <ProfileMetricsGraph queryClient={queryClient} queryExpression={querySelection.expression} from={querySelection.from} to={querySelection.to} select={selectProfile} profile={profileSelection} setTimeRange={(range: DateTimeRange) => { setTimeRangeSelection(range); selectQuery({ expression: queryExpressionString, from: range.getFromMs(), to: range.getToMs(), merge: false, timeSelection: range.getRangeKey(), }); }} addLabelMatcher={addLabelMatcher} /> ) : ( <> {(profileSelection == null || profileSelection.Type() !== 'merge') && ( <div className="my-20 text-center"> <p>Run a query, and the result will be displayed here.</p> </div> )} </> )} </Card.Body> )} </Card> ); }; export default ProfileSelector;
the_stack