@vuu-ui/vuu-filters 0.8.23-debug → 0.8.24-debug

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cjs/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../packages/vuu-filters/src/index.ts", "../../../packages/vuu-filters/src/filter-bar/FilterBar.tsx", "../../../node_modules/clsx/dist/clsx.mjs", "../../../packages/vuu-filters/src/filter-builder-menu/FilterBuilderMenu.tsx", "../../../packages/vuu-filters/src/filter-clause/ExpandoCombobox.tsx", "../../../packages/vuu-filters/src/filter-clause/FilterClauseEditor.tsx", "../../../packages/vuu-filters/src/filter-clause/operator-utils.ts", "../../../packages/vuu-filters/src/filter-clause/NumericInput.tsx", "../../../packages/vuu-filters/src/filter-clause/FilterClauseTextValueEditor.tsx", "../../../packages/vuu-filters/src/filter-clause/FilterClauseValueEditor.tsx", "../../../packages/vuu-filters/src/filter-clause/DateInput.tsx", "../../../node_modules/@internationalized/date/dist/packages/@internationalized/date/src/index.ts", "../../../node_modules/@internationalized/date/dist/packages/@internationalized/date/src/CalendarDate.ts", "../../../node_modules/@internationalized/date/dist/packages/@internationalized/date/src/manipulation.ts", "../../../node_modules/@internationalized/date/dist/packages/@internationalized/date/src/conversion.ts", "../../../node_modules/@internationalized/date/dist/packages/@internationalized/date/src/calendars/GregorianCalendar.ts", "../../../node_modules/@internationalized/date/dist/packages/@internationalized/date/src/utils.ts", "../../../node_modules/@internationalized/date/dist/packages/@internationalized/date/src/queries.ts", "../../../node_modules/@internationalized/date/dist/packages/@internationalized/date/src/weekStartData.ts", "../../../node_modules/@internationalized/date/dist/packages/@internationalized/date/src/string.ts", "../../../node_modules/@internationalized/date/dist/packages/@internationalized/date/src/calendars/JapaneseCalendar.ts", "../../../node_modules/@internationalized/date/dist/packages/@internationalized/date/src/calendars/BuddhistCalendar.ts", "../../../node_modules/@internationalized/date/dist/packages/@internationalized/date/src/calendars/TaiwanCalendar.ts", "../../../node_modules/@internationalized/date/dist/packages/@internationalized/date/src/calendars/PersianCalendar.ts", "../../../node_modules/@internationalized/date/dist/packages/@internationalized/date/src/calendars/IndianCalendar.ts", "../../../node_modules/@internationalized/date/dist/packages/@internationalized/date/src/calendars/IslamicCalendar.ts", "../../../node_modules/@internationalized/date/dist/packages/@internationalized/date/src/calendars/HebrewCalendar.ts", "../../../node_modules/@internationalized/date/dist/packages/@internationalized/date/src/calendars/EthiopicCalendar.ts", "../../../node_modules/@internationalized/date/dist/packages/@internationalized/date/src/createCalendar.ts", "../../../node_modules/@internationalized/date/dist/packages/@internationalized/date/src/DateFormatter.ts", "../../../packages/vuu-filters/src/filter-clause/useFilterClauseEditor.ts", "../../../packages/vuu-filters/src/filter-pill/FilterPill.tsx", "../../../packages/vuu-filters/src/filter-pill-menu/FilterPillMenu.tsx", "../../../packages/vuu-filters/src/filter-pill-menu/FilterPillMenuOptions.ts", "../../../packages/vuu-filters/src/filter-pill/filterAsReactNode.tsx", "../../../packages/vuu-filters/src/filter-pill/getFilterLabel.ts", "../../../packages/vuu-filters/src/filter-utils.ts", "../../../packages/vuu-filters/src/filter-bar/FilterBarMenu.tsx", "../../../packages/vuu-filters/src/filter-bar/useFilterBar.ts", "../../../packages/vuu-filters/src/filter-bar/useFilterState.ts", "../../../packages/vuu-filters/src/filter-bar/useApplyFilterOnChange.ts", "../../../packages/vuu-filters/src/filter-input/FilterInput.tsx", "../../../packages/vuu-filters/src/filter-input/useCodeMirrorEditor.ts", "../../../node_modules/@lezer/common/dist/index.js", "../../../node_modules/@lezer/lr/dist/index.js", "../../../packages/vuu-filter-parser/src/generated/filter-parser.js", "../../../packages/vuu-filter-parser/src/FilterTreeWalker.ts", "../../../packages/vuu-filter-parser/src/FilterParser.ts", "../../../packages/vuu-filters/src/filter-input/FilterLanguage.ts", "../../../packages/vuu-filters/src/filter-input/highlighting.ts", "../../../packages/vuu-filters/src/filter-input/theme.ts", "../../../packages/vuu-filters/src/filter-input/useFilterAutoComplete.ts", "../../../packages/vuu-filters/src/filter-input/useFilterSuggestionProvider.ts", "../../../packages/vuu-filters/src/filter-input/filterInfo.ts", "../../../packages/vuu-filters/src/local-config.ts"],
4
- "sourcesContent": ["export * from \"./filter-bar\";\nexport * from \"./filter-builder-menu\";\nexport * from \"./filter-clause\";\nexport * from \"./filter-input\";\nexport * from \"./filter-pill\";\nexport * from \"./filter-utils\";\nexport * from \"./local-config\";\n", "import { DataSourceFilter, TableSchema } from \"@vuu-ui/vuu-data-types\";\nimport { Filter, FilterState } from \"@vuu-ui/vuu-filter-types\";\nimport { Prompt } from \"@vuu-ui/vuu-popups\";\nimport { Toolbar } from \"@vuu-ui/vuu-ui-controls\";\nimport { ColumnDescriptor } from \"@vuu-ui/vuu-table-types\";\nimport { Button } from \"@salt-ds/core\";\nimport cx from \"clsx\";\nimport { HTMLAttributes, ReactElement, useRef } from \"react\";\nimport { FilterBuilderMenu } from \"../filter-builder-menu\";\nimport { FilterClauseEditor, FilterClauseEditorProps } from \"../filter-clause\";\nimport { FilterPill } from \"../filter-pill\";\nimport { filterClauses as getFilterClauses } from \"../filter-utils\";\nimport { FilterBarMenu } from \"./FilterBarMenu\";\nimport { useFilterBar } from \"./useFilterBar\";\n\nimport \"./FilterBar.css\";\n\nexport interface FilterBarProps extends HTMLAttributes<HTMLDivElement> {\n FilterClauseEditorProps?: Partial<FilterClauseEditorProps>;\n /**\n * This is used to apply tailored filters based on column types and other attributes.\n * NOTE: Always make sure that these are passed with proper re-render optimization, otherwise,\n * might end up with infinite state updates.\n */\n columnDescriptors: ColumnDescriptor[];\n defaultFilterState?: FilterState;\n filterState?: FilterState;\n onApplyFilter: (filter: DataSourceFilter) => void;\n onFilterDeleted?: (filter: Filter) => void;\n onFilterRenamed?: (filter: Filter, name: string) => void;\n onFilterStateChanged?: (state: FilterState) => void;\n showMenu?: boolean;\n tableSchema?: TableSchema;\n}\n\nconst classBase = \"vuuFilterBar\";\n\nexport const FilterBar = ({\n FilterClauseEditorProps,\n className: classNameProp,\n columnDescriptors,\n defaultFilterState,\n filterState,\n onApplyFilter,\n onFilterDeleted,\n onFilterRenamed,\n onFilterStateChanged,\n showMenu: showMenuProp = false,\n tableSchema,\n ...htmlAttributes\n}: FilterBarProps) => {\n const rootRef = useRef<HTMLDivElement>(null);\n const {\n activeFilterIndex,\n addButtonProps,\n columnsByName,\n editFilter,\n filters,\n onBlurFilterClause,\n onCancelFilterClause,\n onClickAddFilter,\n onClickRemoveFilter,\n onChangeFilterClause,\n onChangeActiveFilterIndex,\n onFocusFilterClause,\n onNavigateOutOfBounds,\n onKeyDownFilterbar,\n onKeyDownMenu,\n onMenuAction,\n pillProps,\n promptProps,\n showMenu,\n } = useFilterBar({\n containerRef: rootRef,\n columnDescriptors,\n defaultFilterState,\n filterState,\n onApplyFilter,\n onFilterStateChanged,\n onFilterDeleted,\n onFilterRenamed,\n showMenu: showMenuProp,\n });\n\n const className = cx(classBase, classNameProp, {\n [`${classBase}-display`]: editFilter === undefined,\n [`${classBase}-edit`]: editFilter !== undefined,\n });\n\n const getChildren = () => {\n const items: ReactElement[] = [];\n if (editFilter === undefined) {\n filters.forEach((filter, i) => {\n items.push(\n <FilterPill\n {...pillProps}\n columnsByName={columnsByName}\n filter={filter}\n key={`filter-${i}`}\n />\n );\n });\n return items;\n } else if (editFilter) {\n const filterClauses = getFilterClauses(editFilter);\n items.push(\n <div className={`${classBase}-Editor`} key={`editor`}>\n {filterClauses.map((f, i) => (\n <FilterClauseEditor\n {...FilterClauseEditorProps}\n columnsByName={columnsByName}\n filterClause={f}\n key={`editor-${i}`}\n onCancel={onCancelFilterClause}\n onChange={onChangeFilterClause(i)}\n onBlur={onBlurFilterClause}\n onFocus={onFocusFilterClause}\n tableSchema={tableSchema}\n />\n ))}\n </div>\n );\n if (showMenu) {\n items.push(\n <FilterBuilderMenu\n key=\"menu\"\n onMenuAction={onMenuAction}\n ListProps={{ onKeyDownCapture: onKeyDownMenu }}\n />\n );\n }\n items.push(\n <Button\n className={`${classBase}-remove`}\n data-align=\"right\"\n data-icon=\"cross\"\n key=\"filter-remove\"\n onClick={onClickRemoveFilter}\n variant=\"primary\"\n />\n );\n\n return items;\n }\n };\n\n return (\n <div\n {...htmlAttributes}\n className={className}\n onKeyDown={onKeyDownFilterbar}\n ref={rootRef}\n >\n <FilterBarMenu />\n <Toolbar\n activeItemIndex={activeFilterIndex}\n height={28}\n onActiveChange={onChangeActiveFilterIndex}\n onNavigateOutOfBounds={onNavigateOutOfBounds}\n selectionStrategy=\"multiple-special-key\"\n >\n {getChildren()}\n </Toolbar>\n {editFilter === undefined ? (\n <Button\n {...addButtonProps}\n className={`${classBase}-add`}\n data-icon=\"plus\"\n data-selectable={false}\n key=\"filter-add\"\n onClick={onClickAddFilter}\n tabIndex={0}\n variant=\"primary\"\n />\n ) : null}\n\n {promptProps ? (\n <Prompt\n {...promptProps}\n PopupProps={{\n anchorElement: rootRef,\n offsetTop: 16,\n placement: \"below-center\",\n }}\n />\n ) : null}\n </div>\n );\n};\n", "function r(e){var t,f,n=\"\";if(\"string\"==typeof e||\"number\"==typeof e)n+=e;else if(\"object\"==typeof e)if(Array.isArray(e))for(t=0;t<e.length;t++)e[t]&&(f=r(e[t]))&&(n&&(n+=\" \"),n+=f);else for(t in e)e[t]&&(n&&(n+=\" \"),n+=t);return n}export function clsx(){for(var e,t,f=0,n=\"\";f<arguments.length;)(e=arguments[f++])&&(t=r(e))&&(n&&(n+=\" \"),n+=t);return n}export default clsx;", "import { ContextMenuProps } from \"@vuu-ui/vuu-popups\";\nimport { MenuActionHandler } from \"@vuu-ui/vuu-data-types\";\nimport { ReactElement, useCallback, useRef } from \"react\";\nimport { PopupComponent as Popup, Portal } from \"@vuu-ui/vuu-popups\";\nimport { List, ListItem, ListProps } from \"@vuu-ui/vuu-ui-controls\";\n\nimport \"./FilterBuilderMenu.css\";\n\nconst classBase = \"vuuFilterBuilderMenu\";\n\nexport interface FilterBuilderMenuProps\n extends Omit<ContextMenuProps, \"children\"> {\n ListProps?: Pick<ListProps, \"onKeyDownCapture\">;\n onMenuAction: MenuActionHandler;\n}\n\nexport const FilterBuilderMenu = ({\n ListProps,\n onMenuAction,\n}: FilterBuilderMenuProps) => {\n const ref = useRef<HTMLSpanElement>(null);\n const listRef = useCallback((el: HTMLDivElement | null) => {\n if (el) {\n requestAnimationFrame(() => {\n el.focus();\n });\n }\n }, []);\n\n const handleSelect = useCallback(\n (evt, selected: ReactElement) => {\n const {\n props: { \"data-action\": action },\n } = selected;\n onMenuAction({ type: \"menu-action\", menuId: action, options: {} });\n },\n [onMenuAction]\n );\n\n return (\n <>\n <span className={`${classBase}-trigger`} ref={ref} />\n <Portal>\n <Popup anchorElement={ref} placement=\"right\">\n <List\n {...ListProps}\n className={`${classBase}List`}\n defaultHighlightedIndex={0}\n itemHeight={22}\n ref={listRef}\n onSelect={handleSelect}\n style={{ position: \"relative\" }}\n width={100}\n >\n <ListItem data-action=\"apply-save\">\n <span className=\"vuuMenuButton\">APPLY AND SAVE</span>\n </ListItem>\n <ListItem data-action=\"and-clause\">AND</ListItem>\n <ListItem data-action=\"or-clause\">OR</ListItem>\n </List>\n </Popup>\n </Portal>\n </>\n );\n};\n", "import { itemToString as defaultToString } from \"@vuu-ui/vuu-utils\";\nimport {\n ComboBox,\n ComboBoxProps,\n MultiSelectionHandler,\n SelectionStrategy,\n SingleSelectionHandler,\n} from \"@vuu-ui/vuu-ui-controls\";\nimport cx from \"clsx\";\nimport {\n FormEvent,\n ForwardedRef,\n forwardRef,\n ReactElement,\n useCallback,\n useMemo,\n useRef,\n useState,\n} from \"react\";\n\nimport \"./ExpandoCombobox.css\";\n\nconst classBase = \"vuuExpandoCombobox\";\n\nconst NO_INPUT_PROPS = {};\n\nexport interface ExpandoComboboxProps<\n Item = string,\n S extends SelectionStrategy = \"default\"\n> extends Omit<ComboBoxProps<Item, S>, \"itemToString\" | \"value\"> {\n itemToString?: (item: unknown) => string;\n onInputChange?: (evt: FormEvent<HTMLInputElement>) => void;\n value?: string | string[];\n}\n\nexport const ExpandoCombobox = forwardRef(function ExpandoCombobox<\n Item = string,\n S extends SelectionStrategy = \"default\"\n>(\n {\n className: classNameProp,\n InputProps: InputPropsProp = NO_INPUT_PROPS,\n ListProps: ListPropsProp,\n onInputChange,\n onSelectionChange,\n selectionStrategy,\n source,\n style,\n title,\n value = \"\",\n ...props\n }: ExpandoComboboxProps<Item, S>,\n forwardedRef: ForwardedRef<HTMLDivElement>\n) {\n const [text, setText] = useState(value);\n const { itemToString = defaultToString } = props;\n const initialValue = useRef(value);\n\n const itemsToString = useCallback<<I = Item>(items: I[]) => string>(\n (items) => {\n const [first, ...rest] = items;\n if (rest.length) {\n return `${itemToString(first)} + ${rest.length}`;\n } else {\n return itemToString(first);\n }\n },\n [itemToString]\n );\n\n const handleInputChange = useCallback(\n (evt: FormEvent<HTMLInputElement>) => {\n const { value } = evt.target as HTMLInputElement;\n setText(value);\n onInputChange?.(evt);\n },\n [onInputChange]\n );\n\n const handleSetSelectedText = useCallback((text: string) => {\n setText(text);\n }, []);\n\n const [InputProps, ListProps] = useMemo<\n [ComboBoxProps[\"InputProps\"], any]\n >(() => {\n const { inputProps, ...restInputProps } = InputPropsProp;\n return [\n {\n ...restInputProps,\n className: `${classBase}-Input`,\n endAdornment: null,\n inputProps: {\n ...inputProps,\n autoComplete: \"off\",\n onInput: handleInputChange,\n },\n },\n {\n ...ListPropsProp,\n className: cx(\"vuuMenuList\", ListPropsProp?.className),\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n \"data-mode\": \"light\",\n displayedItemCount: 10,\n itemHeight: 22,\n maxWidth: 300,\n minWidth: 80,\n width: \"content-width\",\n },\n ];\n }, [InputPropsProp, handleInputChange, ListPropsProp]);\n\n const handleSelectionChange = useCallback(\n (_, selected) => {\n if (Array.isArray(selected)) {\n (onSelectionChange as MultiSelectionHandler<Item>)?.(\n null,\n selected as Item[]\n );\n } else if (selected) {\n setText(itemToString(selected));\n (onSelectionChange as SingleSelectionHandler<Item>)?.(\n null,\n selected as Item\n );\n }\n },\n [itemToString, onSelectionChange]\n );\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const getDefaultSelected = (): any => {\n if (initialValue.current === undefined) {\n return undefined;\n } else if (Array.isArray(initialValue.current)) {\n return source?.filter((item) =>\n initialValue.current.includes(itemToString(item))\n );\n } else {\n return source?.find(\n (item) => itemToString(item) === initialValue.current\n );\n }\n };\n\n const popupProps = {\n minWidth: \"fit-content\",\n };\n return (\n <div\n className={cx(classBase, classNameProp)}\n data-text={text}\n ref={forwardedRef}\n style={style}\n >\n <ComboBox<Item, S>\n {...props}\n PopupProps={popupProps}\n allowEnterCommitsText\n defaultSelected={getDefaultSelected()}\n defaultValue={\n Array.isArray(initialValue.current)\n ? itemsToString<string>(initialValue.current)\n : initialValue.current\n }\n fullWidth\n ListProps={ListProps}\n InputProps={InputProps}\n itemsToString={itemsToString}\n onSelectionChange={handleSelectionChange}\n onSetSelectedText={handleSetSelectedText}\n selectionStrategy={selectionStrategy}\n source={source}\n />\n </div>\n );\n}) as <Item, S extends SelectionStrategy = \"default\">(\n props: ExpandoComboboxProps<Item, S> & {\n ref?: ForwardedRef<HTMLDivElement>;\n }\n) => ReactElement<ExpandoComboboxProps<Item, S>>;\n", "import { SuggestionFetcher } from \"@vuu-ui/vuu-data-react\";\nimport { TableSchema } from \"@vuu-ui/vuu-data-types\";\nimport {\n ColumnDescriptorsByName,\n FilterClause,\n} from \"@vuu-ui/vuu-filter-types\";\nimport { ColumnDescriptor } from \"@vuu-ui/vuu-table-types\";\nimport { CloseReason } from \"@vuu-ui/vuu-ui-controls\";\nimport { Button } from \"@salt-ds/core\";\nimport cx from \"clsx\";\nimport { HTMLAttributes, useMemo } from \"react\";\nimport { ExpandoCombobox } from \"./ExpandoCombobox\";\nimport { getOperators } from \"./operator-utils\";\nimport { FilterClauseValueEditor } from \"./FilterClauseValueEditor\";\nimport {\n FilterClauseCancelHandler,\n useFilterClauseEditor,\n} from \"./useFilterClauseEditor\";\n\nimport \"./FilterClauseEditor.css\";\n\nexport interface FilterClauseEditorProps\n extends Omit<HTMLAttributes<HTMLDivElement>, \"onChange\"> {\n columnsByName: ColumnDescriptorsByName;\n filterClause: Partial<FilterClause>;\n onCancel?: FilterClauseCancelHandler;\n onChange: (filterClause: Partial<FilterClause>) => void;\n onDropdownClose?: (closeReason: CloseReason) => void;\n onDropdownOpen?: () => void;\n suggestionProvider?: () => SuggestionFetcher;\n tableSchema?: TableSchema;\n}\n\nconst classBase = \"vuuFilterClause\";\n\nexport const FilterClauseEditor = ({\n className,\n columnsByName,\n onCancel,\n onChange,\n onDropdownClose,\n onDropdownOpen,\n filterClause,\n suggestionProvider,\n tableSchema,\n ...htmlAttributes\n}: FilterClauseEditorProps) => {\n const {\n InputProps,\n columnRef,\n onChangeValue,\n onClear,\n onClearKeyDown,\n onDeselectValue,\n onColumnSelect,\n onOperatorSelect,\n operator,\n operatorRef,\n selectedColumn,\n value,\n } = useFilterClauseEditor({\n filterClause,\n onCancel,\n onChange,\n columnsByName,\n });\n\n const columns = useMemo(() => Object.values(columnsByName), [columnsByName]);\n\n return (\n <div className={cx(classBase, className)} {...htmlAttributes} tabIndex={0}>\n <ExpandoCombobox<ColumnDescriptor>\n InputProps={InputProps}\n allowBackspaceClearsSelection\n className={cx(`${classBase}Field`, `${classBase}Column`)}\n data-field=\"column\"\n initialHighlightedIndex={0}\n itemToString={(column) => (column as ColumnDescriptor).name}\n onListItemSelect={onColumnSelect}\n ref={columnRef}\n source={columns}\n title=\"column\"\n value={selectedColumn?.name ?? \"\"}\n />\n {selectedColumn?.name ? (\n <ExpandoCombobox<string>\n InputProps={InputProps}\n allowBackspaceClearsSelection\n className={cx(`${classBase}Field`, `${classBase}Operator`, {\n [`${classBase}Operator-hidden`]: selectedColumn === null,\n })}\n data-field=\"operator\"\n initialHighlightedIndex={0}\n onListItemSelect={onOperatorSelect}\n ref={operatorRef}\n source={getOperators(selectedColumn)}\n title=\"operator\"\n value={operator ?? \"\"}\n />\n ) : null}\n <FilterClauseValueEditor\n InputProps={InputProps}\n onChangeValue={onChangeValue}\n onDeselectValue={onDeselectValue}\n operator={operator}\n selectedColumn={selectedColumn}\n suggestionProvider={suggestionProvider}\n table={tableSchema?.table}\n value={value}\n />\n {value !== undefined ? (\n <Button\n className={`${classBase}-clearButton`}\n onClick={onClear}\n onKeyDown={onClearKeyDown}\n data-icon=\"close\"\n />\n ) : null}\n </div>\n );\n};\n", "import { ColumnDescriptor } from \"@vuu-ui/vuu-table-types\";\nimport { isNumericColumn, isTextColumn } from \"@vuu-ui/vuu-utils\";\n\nexport const textOperators = [\"=\", \"in\", \"!=\", \"starts\", \"ends\"];\nexport const numericperators = [\"=\", \"!=\", \">\", \">=\", \"<\", \"<=\"];\n\nexport const getOperators = (column: ColumnDescriptor): string[] => {\n if (isTextColumn(column)) {\n return textOperators;\n } else if (isNumericColumn(column)) {\n return numericperators;\n } else {\n throw Error(\"getOperators only supports text and numeric columns\");\n }\n};\n", "import {\n ChangeEvent,\n forwardRef,\n ForwardedRef,\n HTMLAttributes,\n RefObject,\n useState,\n useCallback,\n KeyboardEvent,\n} from \"react\";\nimport { ExpandoInput } from \"@vuu-ui/vuu-ui-controls\";\nimport { isValidNumber } from \"@vuu-ui/vuu-utils\";\nimport { FilterClauseValueEditor } from \"./filterClauseTypes\";\n\nexport interface NumericInputProps\n extends FilterClauseValueEditor<number>,\n HTMLAttributes<HTMLDivElement> {\n operatorInputRef?: RefObject<HTMLInputElement>;\n operator: string;\n ref: RefObject<HTMLDivElement>;\n value?: number;\n}\n\nexport const NumericInput = forwardRef(function NumericInput(\n {\n InputProps,\n className,\n onInputComplete,\n value: valueProp,\n }: NumericInputProps,\n forwardedRef: ForwardedRef<HTMLDivElement>\n) {\n const [value, setValue] = useState<string>(\n isValidNumber(valueProp) ? valueProp.toString() : \"\"\n );\n\n // useEffect(() => {\n // setValueInputValue(\"\");\n // }, [column]);\n\n const handleChange = useCallback((evt: ChangeEvent<HTMLInputElement>) => {\n const { value } = evt.target as HTMLInputElement;\n\n const numericValue = parseFloat(value);\n if (isValidNumber(numericValue)) {\n console.log(\"its valid\");\n }\n setValue(value);\n }, []);\n\n const handleKeyDown = useCallback(\n (evt: KeyboardEvent<HTMLInputElement>) => {\n if (evt.key === \"Enter\") {\n const { value } = evt.target as HTMLInputElement;\n const numericValue = parseFloat(value);\n if (isValidNumber(numericValue)) {\n onInputComplete(numericValue);\n }\n }\n },\n [onInputComplete]\n );\n\n return (\n <ExpandoInput\n {...InputProps}\n className={className}\n value={value}\n ref={forwardedRef}\n onChange={handleChange}\n onKeyDown={handleKeyDown}\n />\n );\n});\n", "import {\n FormEvent,\n ForwardedRef,\n forwardRef,\n HTMLAttributes,\n KeyboardEvent,\n RefObject,\n useCallback,\n useEffect,\n useMemo,\n useState,\n} from \"react\";\nimport { TypeaheadParams, VuuTable } from \"@vuu-ui/vuu-protocol-types\";\nimport {\n SuggestionFetcher,\n useTypeaheadSuggestions,\n} from \"@vuu-ui/vuu-data-react\";\nimport {\n ExpandoInput,\n MultiSelectionHandler,\n SingleSelectionHandler,\n} from \"@vuu-ui/vuu-ui-controls\";\nimport { ExpandoCombobox } from \"./ExpandoCombobox\";\nimport { FilterClauseValueEditor } from \"./filterClauseTypes\";\nimport { TableSchemaTable } from \"@vuu-ui/vuu-data-types\";\n\nconst selectionKeys = [\"Enter\", \" \"];\n\nconst getVuuTable = (schemaTable: TableSchemaTable): VuuTable => {\n if (schemaTable.session) {\n const { module, session } = schemaTable;\n return { module, table: session };\n } else {\n return schemaTable;\n }\n};\n\nexport interface TextInputProps\n extends FilterClauseValueEditor,\n HTMLAttributes<HTMLDivElement> {\n \"data-field\"?: string;\n ref: RefObject<HTMLDivElement>;\n operator: string;\n suggestionProvider?: () => SuggestionFetcher;\n value: string | string[];\n}\n\nconst NO_DATA_MATCH = [\"No matching data\"];\n\nexport const FilterClauseTextValueEditor = forwardRef(function TextInput(\n {\n InputProps: InputPropsProp = {},\n className,\n column,\n \"data-field\": dataField,\n onDeselect,\n onInputComplete,\n operator,\n suggestionProvider = useTypeaheadSuggestions,\n table,\n value,\n }: TextInputProps,\n forwardedRef: ForwardedRef<HTMLDivElement>\n) {\n const isMultiValue = operator === \"in\";\n\n // If we have a multiselect text value which we are editing, this will render\n // a comma delimited list of the selected values. That is not what we display\n // by default when using a multiselect combo. Its not a huge problem - as soon\n // as user focuses this component and we display dropdown, input text is cleared\n // (so user can type to filter list) until dropdown closes again. <ight need to\n // revisit.\n const [valueInputValue, setValueInputValue] = useState(\n value?.toString() ?? \"\"\n );\n const [typeaheadValues, setTypeaheadValues] = useState<string[]>([]);\n\n const getSuggestions = suggestionProvider();\n\n const handleSingleValueSelectionChange = useCallback<SingleSelectionHandler>(\n (_, value) => onInputComplete(value),\n [onInputComplete]\n );\n\n const handleMultiValueSelectionChange = useCallback<MultiSelectionHandler>(\n (_, values) => onInputComplete(values),\n [onInputComplete]\n );\n\n useEffect(() => {\n if (table) {\n const vuuTable = getVuuTable(table);\n const params: TypeaheadParams =\n valueInputValue && !isMultiValue\n ? [vuuTable, column.name, valueInputValue]\n : [vuuTable, column.name];\n getSuggestions(params)\n .then((suggestions) => {\n if (suggestions.length === 0 && valueInputValue) {\n setTypeaheadValues(NO_DATA_MATCH);\n } else {\n setTypeaheadValues(suggestions);\n }\n })\n .catch((err) => {\n console.error(\"Error getting suggestions\", err);\n });\n }\n }, [table, column, valueInputValue, getSuggestions, isMultiValue]);\n\n const handleInputChange = useCallback((evt: FormEvent<HTMLInputElement>) => {\n const { value } = evt.target as HTMLInputElement;\n setValueInputValue(value);\n }, []);\n\n const InputProps = useMemo(() => {\n if (operator !== \"in\") {\n const { inputProps, ...restInputProps } = InputPropsProp;\n return {\n ...restInputProps,\n inputProps: {\n ...inputProps,\n onKeyDown: (evt: KeyboardEvent<HTMLInputElement>) => {\n if (evt.key === \"Enter\" && valueInputValue !== \"\") {\n evt.stopPropagation();\n evt.preventDefault();\n onInputComplete(valueInputValue);\n } else {\n inputProps?.onKeyDown?.(evt);\n }\n },\n },\n };\n } else {\n return InputPropsProp;\n }\n }, [InputPropsProp, onInputComplete, operator, valueInputValue]);\n\n const getValueInputField = useCallback(() => {\n switch (operator) {\n case \"in\":\n return (\n <ExpandoCombobox\n InputProps={InputProps}\n className={className}\n data-field={dataField}\n initialHighlightedIndex={0}\n source={typeaheadValues}\n onInputChange={handleInputChange}\n onSelectionChange={handleMultiValueSelectionChange}\n ref={forwardedRef}\n selectionStrategy=\"multiple\"\n selectionKeys={selectionKeys}\n value={value}\n />\n );\n case \"starts\": {\n return (\n <ExpandoCombobox<string>\n InputProps={InputProps}\n ListProps={{\n className: \"vuuIllustrationsOnly\",\n disabled: true,\n }}\n allowFreeText\n className={className}\n data-field={dataField}\n initialHighlightedIndex={0}\n disableFilter={\n typeaheadValues === NO_DATA_MATCH && valueInputValue?.length > 0\n }\n source={typeaheadValues}\n onInputChange={handleInputChange}\n onSelectionChange={handleSingleValueSelectionChange}\n ref={forwardedRef}\n value={value}\n />\n );\n }\n\n case \"ends\":\n return (\n <ExpandoInput\n {...InputProps}\n className={className}\n data-field={dataField}\n value={valueInputValue}\n ref={forwardedRef}\n onChange={handleInputChange}\n />\n );\n\n default:\n //TODO get a ref to input and listen to changes - connect these to typeahead\n return (\n <ExpandoCombobox<string>\n InputProps={InputProps}\n allowBackspaceClearsSelection\n allowFreeText\n className={className}\n data-field={dataField}\n initialHighlightedIndex={0}\n source={typeaheadValues}\n title=\"value\"\n onInputChange={handleInputChange}\n onDeselect={onDeselect}\n onSelectionChange={handleSingleValueSelectionChange}\n ref={forwardedRef}\n value={value}\n />\n );\n }\n }, [\n InputProps,\n operator,\n className,\n dataField,\n typeaheadValues,\n handleInputChange,\n handleMultiValueSelectionChange,\n forwardedRef,\n value,\n valueInputValue,\n onDeselect,\n handleSingleValueSelectionChange,\n ]);\n\n return getValueInputField();\n});\n", "import { TableSchema } from \"@vuu-ui/vuu-data-types\";\nimport cx from \"clsx\";\nimport { NumericInput } from \"./NumericInput\";\nimport { FilterClauseTextValueEditor } from \"./FilterClauseTextValueEditor\";\nimport { useFilterClauseEditor } from \"./useFilterClauseEditor\";\n\nimport { NumericFilterClauseOp } from \"@vuu-ui/vuu-filter-types\";\nimport { isDateTimeColumn } from \"@vuu-ui/vuu-utils\";\nimport { DateInput } from \"./DateInput\";\nimport { FilterClauseEditorProps } from \"./FilterClauseEditor\";\n\nconst classBase = \"vuuFilterClause\";\n\ntype InputElementProps = Pick<\n ReturnType<typeof useFilterClauseEditor>,\n | \"selectedColumn\"\n | \"operator\"\n | \"InputProps\"\n | \"onChangeValue\"\n | \"onDeselectValue\"\n | \"value\"\n> &\n Pick<FilterClauseEditorProps, \"suggestionProvider\"> & {\n table?: TableSchema[\"table\"];\n };\n\nexport const FilterClauseValueEditor: React.FC<InputElementProps> = ({\n selectedColumn,\n operator,\n InputProps,\n onChangeValue,\n onDeselectValue,\n suggestionProvider,\n table,\n value,\n}) => {\n if (selectedColumn === undefined || operator === undefined) {\n return null;\n }\n\n if (isDateTimeColumn(selectedColumn)) {\n return (\n <DateInput\n value={value as number}\n operator={operator as NumericFilterClauseOp}\n onInputComplete={onChangeValue}\n />\n );\n }\n\n switch (selectedColumn.serverDataType) {\n case \"string\":\n case \"char\":\n return (\n <FilterClauseTextValueEditor\n InputProps={InputProps}\n className={cx(`${classBase}Field`, `${classBase}Value`)}\n column={selectedColumn}\n data-field=\"value\"\n onDeselect={onDeselectValue}\n onInputComplete={onChangeValue}\n operator={operator}\n suggestionProvider={suggestionProvider}\n table={table}\n value={value as string | string[]}\n />\n );\n case \"int\":\n case \"long\":\n case \"double\":\n return (\n <NumericInput\n InputProps={InputProps}\n className={cx(`${classBase}Field`, `${classBase}Value`)}\n column={selectedColumn}\n onInputComplete={onChangeValue}\n operator={operator}\n />\n );\n default:\n console.log(\"returning null\");\n return null;\n }\n};\n", "import React, { useCallback, useState } from \"react\";\nimport { getLocalTimeZone, DateValue } from \"@internationalized/date\";\nimport { DatePicker } from \"@vuu-ui/vuu-ui-controls\";\nimport { toCalendarDate } from \"@vuu-ui/vuu-utils\";\nimport { NumericFilterClauseOp } from \"@vuu-ui/vuu-filter-types\";\nimport { FilterClauseValueEditor } from \"./filterClauseTypes\";\n\ninterface Props\n extends Pick<FilterClauseValueEditor<number>, \"onInputComplete\"> {\n value: number | undefined;\n operator: NumericFilterClauseOp;\n}\n\nexport const DateInput: React.FC<Props> = (props) => {\n const { value, onInputComplete, operator } = props;\n const toEpochMilliS = getEpochMillisConverter(operator);\n\n const [date, setDate] = useState<DateValue | undefined>(() =>\n getInitialState(value)\n );\n\n const onSelectedDateChange = useCallback((d: DateValue | undefined) => {\n setDate(d);\n }, []);\n\n const onBlur = useCallback(() => {\n date && onInputComplete(toEpochMilliS(date));\n }, [date, onInputComplete, toEpochMilliS]);\n\n return (\n <DatePicker\n className={\"vuuFilterClause-DatePicker\"}\n selectedDate={date}\n onBlur={onBlur}\n onSelectedDateChange={onSelectedDateChange}\n closeOnSelection\n hideOutOfRangeDates\n />\n );\n};\n\nfunction getInitialState(value: Props[\"value\"]) {\n return value ? toCalendarDate(new Date(value)) : undefined;\n}\n\nconst getEpochMillisConverter =\n (op: NumericFilterClauseOp) =>\n (date: DateValue, timezone: string = getLocalTimeZone()): number => {\n const d = date.toDate(timezone);\n switch (op) {\n case \">\":\n case \"<=\":\n d.setHours(23, 59, 59, 999);\n return d.getTime();\n case \">=\":\n case \"<\":\n case \"=\": // converted to \"< `start of next day` and >= `start of this day`\" when query is created\n case \"!=\": // converted to \">= `start of next day` or < `start of this day`\" when query is created\n d.setHours(0, 0, 0, 0);\n return d.getTime();\n }\n };\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nexport type {\n AnyCalendarDate,\n AnyTime,\n AnyDateTime,\n Calendar,\n DateDuration,\n TimeDuration,\n DateTimeDuration,\n DateFields,\n TimeFields,\n DateField,\n TimeField,\n Disambiguation,\n CycleOptions,\n CycleTimeOptions\n} from './types';\n\nexport {CalendarDate, CalendarDateTime, Time, ZonedDateTime} from './CalendarDate';\nexport {GregorianCalendar} from './calendars/GregorianCalendar';\nexport {JapaneseCalendar} from './calendars/JapaneseCalendar';\nexport {BuddhistCalendar} from './calendars/BuddhistCalendar';\nexport {TaiwanCalendar} from './calendars/TaiwanCalendar';\nexport {PersianCalendar} from './calendars/PersianCalendar';\nexport {IndianCalendar} from './calendars/IndianCalendar';\nexport {IslamicCivilCalendar, IslamicTabularCalendar, IslamicUmalquraCalendar} from './calendars/IslamicCalendar';\nexport {HebrewCalendar} from './calendars/HebrewCalendar';\nexport {EthiopicCalendar, EthiopicAmeteAlemCalendar, CopticCalendar} from './calendars/EthiopicCalendar';\nexport {createCalendar} from './createCalendar';\nexport {\n toCalendarDate,\n toCalendarDateTime,\n toTime,\n toCalendar,\n toZoned,\n toTimeZone,\n toLocalTimeZone,\n fromDate,\n fromAbsolute\n} from './conversion';\nexport {\n isSameDay,\n isSameMonth,\n isSameYear,\n isEqualDay,\n isEqualMonth,\n isEqualYear,\n isToday,\n getDayOfWeek,\n now,\n today,\n getHoursInDay,\n getLocalTimeZone,\n startOfMonth,\n startOfWeek,\n startOfYear,\n endOfMonth,\n endOfWeek,\n endOfYear,\n getMinimumMonthInYear,\n getMinimumDayInMonth,\n getWeeksInMonth,\n minDate,\n maxDate,\n isWeekend,\n isWeekday\n} from './queries';\nexport {\n parseDate,\n parseDateTime,\n parseTime,\n parseAbsolute,\n parseAbsoluteToLocal,\n parseZonedDateTime,\n parseDuration\n} from './string';\nexport {DateFormatter} from './DateFormatter';\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {add, addTime, addZoned, constrain, constrainTime, cycleDate, cycleTime, cycleZoned, set, setTime, setZoned, subtract, subtractTime, subtractZoned} from './manipulation';\nimport {AnyCalendarDate, AnyTime, Calendar, CycleOptions, CycleTimeOptions, DateDuration, DateField, DateFields, DateTimeDuration, Disambiguation, TimeDuration, TimeField, TimeFields} from './types';\nimport {compareDate, compareTime} from './queries';\nimport {dateTimeToString, dateToString, timeToString, zonedDateTimeToString} from './string';\nimport {GregorianCalendar} from './calendars/GregorianCalendar';\nimport {toCalendarDateTime, toDate, toZoned, zonedToDate} from './conversion';\n\nfunction shiftArgs(args: any[]) {\n let calendar: Calendar = typeof args[0] === 'object'\n ? args.shift()\n : new GregorianCalendar();\n\n let era: string;\n if (typeof args[0] === 'string') {\n era = args.shift();\n } else {\n let eras = calendar.getEras();\n era = eras[eras.length - 1];\n }\n\n let year = args.shift();\n let month = args.shift();\n let day = args.shift();\n\n return [calendar, era, year, month, day];\n}\n\n/** A CalendarDate represents a date without any time components in a specific calendar system. */\nexport class CalendarDate {\n // This prevents TypeScript from allowing other types with the same fields to match.\n // i.e. a ZonedDateTime should not be be passable to a parameter that expects CalendarDate.\n // If that behavior is desired, use the AnyCalendarDate interface instead.\n // @ts-ignore\n #type;\n /** The calendar system associated with this date, e.g. Gregorian. */\n public readonly calendar: Calendar;\n /** The calendar era for this date, e.g. \"BC\" or \"AD\". */\n public readonly era: string;\n /** The year of this date within the era. */\n public readonly year: number;\n /**\n * The month number within the year. Note that some calendar systems such as Hebrew\n * may have a variable number of months per year. Therefore, month numbers may not\n * always correspond to the same month names in different years.\n */\n public readonly month: number;\n /** The day number within the month. */\n public readonly day: number;\n\n constructor(year: number, month: number, day: number);\n constructor(era: string, year: number, month: number, day: number);\n constructor(calendar: Calendar, year: number, month: number, day: number);\n constructor(calendar: Calendar, era: string, year: number, month: number, day: number);\n constructor(...args: any[]) {\n let [calendar, era, year, month, day] = shiftArgs(args);\n this.calendar = calendar;\n this.era = era;\n this.year = year;\n this.month = month;\n this.day = day;\n\n constrain(this);\n }\n\n /** Returns a copy of this date. */\n copy(): CalendarDate {\n if (this.era) {\n return new CalendarDate(this.calendar, this.era, this.year, this.month, this.day);\n } else {\n return new CalendarDate(this.calendar, this.year, this.month, this.day);\n }\n }\n\n /** Returns a new `CalendarDate` with the given duration added to it. */\n add(duration: DateDuration): CalendarDate {\n return add(this, duration);\n }\n\n /** Returns a new `CalendarDate` with the given duration subtracted from it. */\n subtract(duration: DateDuration): CalendarDate {\n return subtract(this, duration);\n }\n\n /** Returns a new `CalendarDate` with the given fields set to the provided values. Other fields will be constrained accordingly. */\n set(fields: DateFields): CalendarDate {\n return set(this, fields);\n }\n\n /**\n * Returns a new `CalendarDate` with the given field adjusted by a specified amount.\n * When the resulting value reaches the limits of the field, it wraps around.\n */\n cycle(field: DateField, amount: number, options?: CycleOptions): CalendarDate {\n return cycleDate(this, field, amount, options);\n }\n\n /** Converts the date to a native JavaScript Date object, with the time set to midnight in the given time zone. */\n toDate(timeZone: string): Date {\n return toDate(this, timeZone);\n }\n\n /** Converts the date to an ISO 8601 formatted string. */\n toString(): string {\n return dateToString(this);\n }\n\n /** Compares this date with another. A negative result indicates that this date is before the given one, and a positive date indicates that it is after. */\n compare(b: AnyCalendarDate): number {\n return compareDate(this, b);\n }\n}\n\n/** A Time represents a clock time without any date components. */\nexport class Time {\n // This prevents TypeScript from allowing other types with the same fields to match.\n // @ts-ignore\n #type;\n /** The hour, numbered from 0 to 23. */\n public readonly hour: number;\n /** The minute in the hour. */\n public readonly minute: number;\n /** The second in the minute. */\n public readonly second: number;\n /** The millisecond in the second. */\n public readonly millisecond: number;\n\n constructor(\n hour: number = 0,\n minute: number = 0,\n second: number = 0,\n millisecond: number = 0\n ) {\n this.hour = hour;\n this.minute = minute;\n this.second = second;\n this.millisecond = millisecond;\n constrainTime(this);\n }\n\n /** Returns a copy of this time. */\n copy(): Time {\n return new Time(this.hour, this.minute, this.second, this.millisecond);\n }\n\n /** Returns a new `Time` with the given duration added to it. */\n add(duration: TimeDuration) {\n return addTime(this, duration);\n }\n\n /** Returns a new `Time` with the given duration subtracted from it. */\n subtract(duration: TimeDuration) {\n return subtractTime(this, duration);\n }\n\n /** Returns a new `Time` with the given fields set to the provided values. Other fields will be constrained accordingly. */\n set(fields: TimeFields) {\n return setTime(this, fields);\n }\n\n /**\n * Returns a new `Time` with the given field adjusted by a specified amount.\n * When the resulting value reaches the limits of the field, it wraps around.\n */\n cycle(field: TimeField, amount: number, options?: CycleTimeOptions) {\n return cycleTime(this, field, amount, options);\n }\n\n /** Converts the time to an ISO 8601 formatted string. */\n toString() {\n return timeToString(this);\n }\n\n /** Compares this time with another. A negative result indicates that this time is before the given one, and a positive time indicates that it is after. */\n compare(b: AnyTime) {\n return compareTime(this, b);\n }\n}\n\n/** A CalendarDateTime represents a date and time without a time zone, in a specific calendar system. */\nexport class CalendarDateTime {\n // This prevents TypeScript from allowing other types with the same fields to match.\n // @ts-ignore\n #type;\n /** The calendar system associated with this date, e.g. Gregorian. */\n public readonly calendar: Calendar;\n /** The calendar era for this date, e.g. \"BC\" or \"AD\". */\n public readonly era: string;\n /** The year of this date within the era. */\n public readonly year: number;\n /**\n * The month number within the year. Note that some calendar systems such as Hebrew\n * may have a variable number of months per year. Therefore, month numbers may not\n * always correspond to the same month names in different years.\n */\n public readonly month: number;\n /** The day number within the month. */\n public readonly day: number;\n /** The hour in the day, numbered from 0 to 23. */\n public readonly hour: number;\n /** The minute in the hour. */\n public readonly minute: number;\n /** The second in the minute. */\n public readonly second: number;\n /** The millisecond in the second. */\n public readonly millisecond: number;\n\n constructor(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number);\n constructor(era: string, year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number);\n constructor(calendar: Calendar, year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number);\n constructor(calendar: Calendar, era: string, year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number);\n constructor(...args: any[]) {\n let [calendar, era, year, month, day] = shiftArgs(args);\n this.calendar = calendar;\n this.era = era;\n this.year = year;\n this.month = month;\n this.day = day;\n this.hour = args.shift() || 0;\n this.minute = args.shift() || 0;\n this.second = args.shift() || 0;\n this.millisecond = args.shift() || 0;\n\n constrain(this);\n }\n\n /** Returns a copy of this date. */\n copy(): CalendarDateTime {\n if (this.era) {\n return new CalendarDateTime(this.calendar, this.era, this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond);\n } else {\n return new CalendarDateTime(this.calendar, this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond);\n }\n }\n\n /** Returns a new `CalendarDateTime` with the given duration added to it. */\n add(duration: DateTimeDuration): CalendarDateTime {\n return add(this, duration);\n }\n\n /** Returns a new `CalendarDateTime` with the given duration subtracted from it. */\n subtract(duration: DateTimeDuration): CalendarDateTime {\n return subtract(this, duration);\n }\n\n /** Returns a new `CalendarDateTime` with the given fields set to the provided values. Other fields will be constrained accordingly. */\n set(fields: DateFields & TimeFields): CalendarDateTime {\n return set(setTime(this, fields), fields);\n }\n\n /**\n * Returns a new `CalendarDateTime` with the given field adjusted by a specified amount.\n * When the resulting value reaches the limits of the field, it wraps around.\n */\n cycle(field: DateField | TimeField, amount: number, options?: CycleTimeOptions): CalendarDateTime {\n switch (field) {\n case 'era':\n case 'year':\n case 'month':\n case 'day':\n return cycleDate(this, field, amount, options);\n default:\n return cycleTime(this, field, amount, options);\n }\n }\n\n /** Converts the date to a native JavaScript Date object in the given time zone. */\n toDate(timeZone: string, disambiguation?: Disambiguation): Date {\n return toDate(this, timeZone, disambiguation);\n }\n\n /** Converts the date to an ISO 8601 formatted string. */\n toString(): string {\n return dateTimeToString(this);\n }\n\n /** Compares this date with another. A negative result indicates that this date is before the given one, and a positive date indicates that it is after. */\n compare(b: CalendarDate | CalendarDateTime | ZonedDateTime): number {\n let res = compareDate(this, b);\n if (res === 0) {\n return compareTime(this, toCalendarDateTime(b));\n }\n\n return res;\n }\n}\n\n/** A ZonedDateTime represents a date and time in a specific time zone and calendar system. */\nexport class ZonedDateTime {\n // This prevents TypeScript from allowing other types with the same fields to match.\n // @ts-ignore\n #type;\n /** The calendar system associated with this date, e.g. Gregorian. */\n public readonly calendar: Calendar;\n /** The calendar era for this date, e.g. \"BC\" or \"AD\". */\n public readonly era: string;\n /** The year of this date within the era. */\n public readonly year: number;\n /**\n * The month number within the year. Note that some calendar systems such as Hebrew\n * may have a variable number of months per year. Therefore, month numbers may not\n * always correspond to the same month names in different years.\n */\n public readonly month: number;\n /** The day number within the month. */\n public readonly day: number;\n /** The hour in the day, numbered from 0 to 23. */\n public readonly hour: number;\n /** The minute in the hour. */\n public readonly minute: number;\n /** The second in the minute. */\n public readonly second: number;\n /** The millisecond in the second. */\n public readonly millisecond: number;\n /** The IANA time zone identifier that this date and time is represented in. */\n public readonly timeZone: string;\n /** The UTC offset for this time, in milliseconds. */\n public readonly offset: number;\n\n constructor(year: number, month: number, day: number, timeZone: string, offset: number, hour?: number, minute?: number, second?: number, millisecond?: number);\n constructor(era: string, year: number, month: number, day: number, timeZone: string, offset: number, hour?: number, minute?: number, second?: number, millisecond?: number);\n constructor(calendar: Calendar, year: number, month: number, day: number, timeZone: string, offset: number, hour?: number, minute?: number, second?: number, millisecond?: number);\n constructor(calendar: Calendar, era: string, year: number, month: number, day: number, timeZone: string, offset: number, hour?: number, minute?: number, second?: number, millisecond?: number);\n constructor(...args: any[]) {\n let [calendar, era, year, month, day] = shiftArgs(args);\n let timeZone = args.shift();\n let offset = args.shift();\n this.calendar = calendar;\n this.era = era;\n this.year = year;\n this.month = month;\n this.day = day;\n this.timeZone = timeZone;\n this.offset = offset;\n this.hour = args.shift() || 0;\n this.minute = args.shift() || 0;\n this.second = args.shift() || 0;\n this.millisecond = args.shift() || 0;\n\n constrain(this);\n }\n\n /** Returns a copy of this date. */\n copy(): ZonedDateTime {\n if (this.era) {\n return new ZonedDateTime(this.calendar, this.era, this.year, this.month, this.day, this.timeZone, this.offset, this.hour, this.minute, this.second, this.millisecond);\n } else {\n return new ZonedDateTime(this.calendar, this.year, this.month, this.day, this.timeZone, this.offset, this.hour, this.minute, this.second, this.millisecond);\n }\n }\n\n /** Returns a new `ZonedDateTime` with the given duration added to it. */\n add(duration: DateTimeDuration) {\n return addZoned(this, duration);\n }\n\n /** Returns a new `ZonedDateTime` with the given duration subtracted from it. */\n subtract(duration: DateTimeDuration) {\n return subtractZoned(this, duration);\n }\n\n /** Returns a new `ZonedDateTime` with the given fields set to the provided values. Other fields will be constrained accordingly. */\n set(fields: DateFields & TimeFields, disambiguation?: Disambiguation) {\n return setZoned(this, fields, disambiguation);\n }\n\n /**\n * Returns a new `ZonedDateTime` with the given field adjusted by a specified amount.\n * When the resulting value reaches the limits of the field, it wraps around.\n */\n cycle(field: DateField | TimeField, amount: number, options?: CycleTimeOptions) {\n return cycleZoned(this, field, amount, options);\n }\n\n /** Converts the date to a native JavaScript Date object. */\n toDate() {\n return zonedToDate(this);\n }\n\n /** Converts the date to an ISO 8601 formatted string, including the UTC offset and time zone identifier. */\n toString() {\n return zonedDateTimeToString(this);\n }\n\n /** Converts the date to an ISO 8601 formatted string in UTC. */\n toAbsoluteString() {\n return this.toDate().toISOString();\n }\n\n /** Compares this date with another. A negative result indicates that this date is before the given one, and a positive date indicates that it is after. */\n compare(b: CalendarDate | CalendarDateTime | ZonedDateTime) {\n // TODO: Is this a bad idea??\n return this.toDate().getTime() - toZoned(b, this.timeZone).toDate().getTime();\n }\n}\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {AnyCalendarDate, AnyDateTime, AnyTime, CycleOptions, CycleTimeOptions, DateDuration, DateField, DateFields, DateTimeDuration, Disambiguation, TimeDuration, TimeField, TimeFields} from './types';\nimport {CalendarDate, CalendarDateTime, Time, ZonedDateTime} from './CalendarDate';\nimport {epochFromDate, fromAbsolute, toAbsolute, toCalendar, toCalendarDateTime} from './conversion';\nimport {GregorianCalendar} from './calendars/GregorianCalendar';\nimport {Mutable} from './utils';\n\nconst ONE_HOUR = 3600000;\n\nexport function add(date: CalendarDateTime, duration: DateTimeDuration): CalendarDateTime;\nexport function add(date: CalendarDate, duration: DateDuration): CalendarDate;\nexport function add(date: CalendarDate | CalendarDateTime, duration: DateTimeDuration): CalendarDate | CalendarDateTime;\nexport function add(date: CalendarDate | CalendarDateTime, duration: DateTimeDuration) {\n let mutableDate: Mutable<AnyCalendarDate | AnyDateTime> = date.copy();\n let days = 'hour' in mutableDate ? addTimeFields(mutableDate, duration) : 0;\n\n addYears(mutableDate, duration.years || 0);\n if (mutableDate.calendar.balanceYearMonth) {\n mutableDate.calendar.balanceYearMonth(mutableDate, date);\n }\n\n mutableDate.month += duration.months || 0;\n\n balanceYearMonth(mutableDate);\n constrainMonthDay(mutableDate);\n\n mutableDate.day += (duration.weeks || 0) * 7;\n mutableDate.day += duration.days || 0;\n mutableDate.day += days;\n\n balanceDay(mutableDate);\n\n if (mutableDate.calendar.balanceDate) {\n mutableDate.calendar.balanceDate(mutableDate);\n }\n\n // Constrain in case adding ended up with a date outside the valid range for the calendar system.\n // The behavior here is slightly different than when constraining in the `set` function in that\n // we adjust smaller fields to their minimum/maximum values rather than constraining each field\n // individually. This matches the general behavior of `add` vs `set` regarding how fields are balanced.\n if (mutableDate.year < 1) {\n mutableDate.year = 1;\n mutableDate.month = 1;\n mutableDate.day = 1;\n }\n\n let maxYear = mutableDate.calendar.getYearsInEra(mutableDate);\n if (mutableDate.year > maxYear) {\n let isInverseEra = mutableDate.calendar.isInverseEra?.(mutableDate);\n mutableDate.year = maxYear;\n mutableDate.month = isInverseEra ? 1 : mutableDate.calendar.getMonthsInYear(mutableDate);\n mutableDate.day = isInverseEra ? 1 : mutableDate.calendar.getDaysInMonth(mutableDate);\n }\n\n if (mutableDate.month < 1) {\n mutableDate.month = 1;\n mutableDate.day = 1;\n }\n\n let maxMonth = mutableDate.calendar.getMonthsInYear(mutableDate);\n if (mutableDate.month > maxMonth) {\n mutableDate.month = maxMonth;\n mutableDate.day = mutableDate.calendar.getDaysInMonth(mutableDate);\n }\n\n mutableDate.day = Math.max(1, Math.min(mutableDate.calendar.getDaysInMonth(mutableDate), mutableDate.day));\n return mutableDate;\n}\n\nfunction addYears(date: Mutable<AnyCalendarDate>, years: number) {\n if (date.calendar.isInverseEra?.(date)) {\n years = -years;\n }\n\n date.year += years;\n}\n\nfunction balanceYearMonth(date: Mutable<AnyCalendarDate>) {\n while (date.month < 1) {\n addYears(date, -1);\n date.month += date.calendar.getMonthsInYear(date);\n }\n\n let monthsInYear = 0;\n while (date.month > (monthsInYear = date.calendar.getMonthsInYear(date))) {\n date.month -= monthsInYear;\n addYears(date, 1);\n }\n}\n\nfunction balanceDay(date: Mutable<AnyCalendarDate>) {\n while (date.day < 1) {\n date.month--;\n balanceYearMonth(date);\n date.day += date.calendar.getDaysInMonth(date);\n }\n\n while (date.day > date.calendar.getDaysInMonth(date)) {\n date.day -= date.calendar.getDaysInMonth(date);\n date.month++;\n balanceYearMonth(date);\n }\n}\n\nfunction constrainMonthDay(date: Mutable<AnyCalendarDate>) {\n date.month = Math.max(1, Math.min(date.calendar.getMonthsInYear(date), date.month));\n date.day = Math.max(1, Math.min(date.calendar.getDaysInMonth(date), date.day));\n}\n\nexport function constrain(date: Mutable<AnyCalendarDate>) {\n if (date.calendar.constrainDate) {\n date.calendar.constrainDate(date);\n }\n\n date.year = Math.max(1, Math.min(date.calendar.getYearsInEra(date), date.year));\n constrainMonthDay(date);\n}\n\nexport function invertDuration(duration: DateTimeDuration): DateTimeDuration {\n let inverseDuration = {};\n for (let key in duration) {\n if (typeof duration[key] === 'number') {\n inverseDuration[key] = -duration[key];\n }\n }\n\n return inverseDuration;\n}\n\nexport function subtract(date: CalendarDateTime, duration: DateTimeDuration): CalendarDateTime;\nexport function subtract(date: CalendarDate, duration: DateDuration): CalendarDate;\nexport function subtract(date: CalendarDate | CalendarDateTime, duration: DateTimeDuration): CalendarDate | CalendarDateTime {\n return add(date, invertDuration(duration));\n}\n\nexport function set(date: CalendarDateTime, fields: DateFields): CalendarDateTime;\nexport function set(date: CalendarDate, fields: DateFields): CalendarDate;\nexport function set(date: CalendarDate | CalendarDateTime, fields: DateFields) {\n let mutableDate: Mutable<AnyCalendarDate> = date.copy();\n\n if (fields.era != null) {\n mutableDate.era = fields.era;\n }\n\n if (fields.year != null) {\n mutableDate.year = fields.year;\n }\n\n if (fields.month != null) {\n mutableDate.month = fields.month;\n }\n\n if (fields.day != null) {\n mutableDate.day = fields.day;\n }\n\n constrain(mutableDate);\n return mutableDate;\n}\n\nexport function setTime(value: CalendarDateTime, fields: TimeFields): CalendarDateTime;\nexport function setTime(value: Time, fields: TimeFields): Time;\nexport function setTime(value: Time | CalendarDateTime, fields: TimeFields) {\n let mutableValue: Mutable<Time | CalendarDateTime> = value.copy();\n\n if (fields.hour != null) {\n mutableValue.hour = fields.hour;\n }\n\n if (fields.minute != null) {\n mutableValue.minute = fields.minute;\n }\n\n if (fields.second != null) {\n mutableValue.second = fields.second;\n }\n\n if (fields.millisecond != null) {\n mutableValue.millisecond = fields.millisecond;\n }\n\n constrainTime(mutableValue);\n return mutableValue;\n}\n\nfunction balanceTime(time: Mutable<AnyTime>): number {\n time.second += Math.floor(time.millisecond / 1000);\n time.millisecond = nonNegativeMod(time.millisecond, 1000);\n\n time.minute += Math.floor(time.second / 60);\n time.second = nonNegativeMod(time.second, 60);\n\n time.hour += Math.floor(time.minute / 60);\n time.minute = nonNegativeMod(time.minute, 60);\n\n let days = Math.floor(time.hour / 24);\n time.hour = nonNegativeMod(time.hour, 24);\n\n return days;\n}\n\nexport function constrainTime(time: Mutable<AnyTime>) {\n time.millisecond = Math.max(0, Math.min(time.millisecond, 1000));\n time.second = Math.max(0, Math.min(time.second, 59));\n time.minute = Math.max(0, Math.min(time.minute, 59));\n time.hour = Math.max(0, Math.min(time.hour, 23));\n}\n\nfunction nonNegativeMod(a: number, b: number) {\n let result = a % b;\n if (result < 0) {\n result += b;\n }\n return result;\n}\n\nfunction addTimeFields(time: Mutable<AnyTime>, duration: TimeDuration): number {\n time.hour += duration.hours || 0;\n time.minute += duration.minutes || 0;\n time.second += duration.seconds || 0;\n time.millisecond += duration.milliseconds || 0;\n return balanceTime(time);\n}\n\nexport function addTime(time: Time, duration: TimeDuration): Time {\n let res = time.copy();\n addTimeFields(res, duration);\n return res;\n}\n\nexport function subtractTime(time: Time, duration: TimeDuration): Time {\n return addTime(time, invertDuration(duration));\n}\n\nexport function cycleDate(value: CalendarDateTime, field: DateField, amount: number, options?: CycleOptions): CalendarDateTime;\nexport function cycleDate(value: CalendarDate, field: DateField, amount: number, options?: CycleOptions): CalendarDate;\nexport function cycleDate(value: CalendarDate | CalendarDateTime, field: DateField, amount: number, options?: CycleOptions) {\n let mutable: Mutable<CalendarDate | CalendarDateTime> = value.copy();\n\n switch (field) {\n case 'era': {\n let eras = value.calendar.getEras();\n let eraIndex = eras.indexOf(value.era);\n if (eraIndex < 0) {\n throw new Error('Invalid era: ' + value.era);\n }\n eraIndex = cycleValue(eraIndex, amount, 0, eras.length - 1, options?.round);\n mutable.era = eras[eraIndex];\n\n // Constrain the year and other fields within the era, so the era doesn't change when we balance below.\n constrain(mutable);\n break;\n }\n case 'year': {\n if (mutable.calendar.isInverseEra?.(mutable)) {\n amount = -amount;\n }\n\n // The year field should not cycle within the era as that can cause weird behavior affecting other fields.\n // We need to also allow values < 1 so that decrementing goes to the previous era. If we get -Infinity back\n // we know we wrapped around after reaching 9999 (the maximum), so set the year back to 1.\n mutable.year = cycleValue(value.year, amount, -Infinity, 9999, options?.round);\n if (mutable.year === -Infinity) {\n mutable.year = 1;\n }\n\n if (mutable.calendar.balanceYearMonth) {\n mutable.calendar.balanceYearMonth(mutable, value);\n }\n break;\n }\n case 'month':\n mutable.month = cycleValue(value.month, amount, 1, value.calendar.getMonthsInYear(value), options?.round);\n break;\n case 'day':\n mutable.day = cycleValue(value.day, amount, 1, value.calendar.getDaysInMonth(value), options?.round);\n break;\n default:\n throw new Error('Unsupported field ' + field);\n }\n\n if (value.calendar.balanceDate) {\n value.calendar.balanceDate(mutable);\n }\n\n constrain(mutable);\n return mutable;\n}\n\nexport function cycleTime(value: CalendarDateTime, field: TimeField, amount: number, options?: CycleTimeOptions): CalendarDateTime;\nexport function cycleTime(value: Time, field: TimeField, amount: number, options?: CycleTimeOptions): Time;\nexport function cycleTime(value: Time | CalendarDateTime, field: TimeField, amount: number, options?: CycleTimeOptions) {\n let mutable: Mutable<Time | CalendarDateTime> = value.copy();\n\n switch (field) {\n case 'hour': {\n let hours = value.hour;\n let min = 0;\n let max = 23;\n if (options?.hourCycle === 12) {\n let isPM = hours >= 12;\n min = isPM ? 12 : 0;\n max = isPM ? 23 : 11;\n }\n mutable.hour = cycleValue(hours, amount, min, max, options?.round);\n break;\n }\n case 'minute':\n mutable.minute = cycleValue(value.minute, amount, 0, 59, options?.round);\n break;\n case 'second':\n mutable.second = cycleValue(value.second, amount, 0, 59, options?.round);\n break;\n case 'millisecond':\n mutable.millisecond = cycleValue(value.millisecond, amount, 0, 999, options?.round);\n break;\n default:\n throw new Error('Unsupported field ' + field);\n }\n\n return mutable;\n}\n\nfunction cycleValue(value: number, amount: number, min: number, max: number, round = false) {\n if (round) {\n value += Math.sign(amount);\n\n if (value < min) {\n value = max;\n }\n\n let div = Math.abs(amount);\n if (amount > 0) {\n value = Math.ceil(value / div) * div;\n } else {\n value = Math.floor(value / div) * div;\n }\n\n if (value > max) {\n value = min;\n }\n } else {\n value += amount;\n if (value < min) {\n value = max - (min - value - 1);\n } else if (value > max) {\n value = min + (value - max - 1);\n }\n }\n\n return value;\n}\n\nexport function addZoned(dateTime: ZonedDateTime, duration: DateTimeDuration): ZonedDateTime {\n let ms: number;\n if ((duration.years != null && duration.years !== 0) || (duration.months != null && duration.months !== 0) || (duration.weeks != null && duration.weeks !== 0) || (duration.days != null && duration.days !== 0)) {\n let res = add(toCalendarDateTime(dateTime), {\n years: duration.years,\n months: duration.months,\n weeks: duration.weeks,\n days: duration.days\n });\n\n // Changing the date may change the timezone offset, so we need to recompute\n // using the 'compatible' disambiguation.\n ms = toAbsolute(res, dateTime.timeZone);\n } else {\n // Otherwise, preserve the offset of the original date.\n ms = epochFromDate(dateTime) - dateTime.offset;\n }\n\n // Perform time manipulation in milliseconds rather than on the original time fields to account for DST.\n // For example, adding one hour during a DST transition may result in the hour field staying the same or\n // skipping an hour. This results in the offset field changing value instead of the specified field.\n ms += duration.milliseconds || 0;\n ms += (duration.seconds || 0) * 1000;\n ms += (duration.minutes || 0) * 60 * 1000;\n ms += (duration.hours || 0) * 60 * 60 * 1000;\n\n let res = fromAbsolute(ms, dateTime.timeZone);\n return toCalendar(res, dateTime.calendar);\n}\n\nexport function subtractZoned(dateTime: ZonedDateTime, duration: DateTimeDuration): ZonedDateTime {\n return addZoned(dateTime, invertDuration(duration));\n}\n\nexport function cycleZoned(dateTime: ZonedDateTime, field: DateField | TimeField, amount: number, options?: CycleTimeOptions): ZonedDateTime {\n // For date fields, we want the time to remain consistent and the UTC offset to potentially change to account for DST changes.\n // For time fields, we want the time to change by the amount given. This may result in the hour field staying the same, but the UTC\n // offset changing in the case of a backward DST transition, or skipping an hour in the case of a forward DST transition.\n switch (field) {\n case 'hour': {\n let min = 0;\n let max = 23;\n if (options?.hourCycle === 12) {\n let isPM = dateTime.hour >= 12;\n min = isPM ? 12 : 0;\n max = isPM ? 23 : 11;\n }\n\n // The minimum and maximum hour may be affected by daylight saving time.\n // For example, it might jump forward at midnight, and skip 1am.\n // Or it might end at midnight and repeat the 11pm hour. To handle this, we get\n // the possible absolute times for the min and max, and find the maximum range\n // that is within the current day.\n let plainDateTime = toCalendarDateTime(dateTime);\n let minDate = toCalendar(setTime(plainDateTime, {hour: min}), new GregorianCalendar());\n let minAbsolute = [toAbsolute(minDate, dateTime.timeZone, 'earlier'), toAbsolute(minDate, dateTime.timeZone, 'later')]\n .filter(ms => fromAbsolute(ms, dateTime.timeZone).day === minDate.day)[0];\n\n let maxDate = toCalendar(setTime(plainDateTime, {hour: max}), new GregorianCalendar());\n let maxAbsolute = [toAbsolute(maxDate, dateTime.timeZone, 'earlier'), toAbsolute(maxDate, dateTime.timeZone, 'later')]\n .filter(ms => fromAbsolute(ms, dateTime.timeZone).day === maxDate.day).pop();\n\n // Since hours may repeat, we need to operate on the absolute time in milliseconds.\n // This is done in hours from the Unix epoch so that cycleValue works correctly,\n // and then converted back to milliseconds.\n let ms = epochFromDate(dateTime) - dateTime.offset;\n let hours = Math.floor(ms / ONE_HOUR);\n let remainder = ms % ONE_HOUR;\n ms = cycleValue(\n hours,\n amount,\n Math.floor(minAbsolute / ONE_HOUR),\n Math.floor(maxAbsolute / ONE_HOUR),\n options?.round\n ) * ONE_HOUR + remainder;\n\n // Now compute the new timezone offset, and convert the absolute time back to local time.\n return toCalendar(fromAbsolute(ms, dateTime.timeZone), dateTime.calendar);\n }\n case 'minute':\n case 'second':\n case 'millisecond':\n // @ts-ignore\n return cycleTime(dateTime, field, amount, options);\n case 'era':\n case 'year':\n case 'month':\n case 'day': {\n let res = cycleDate(toCalendarDateTime(dateTime), field, amount, options);\n let ms = toAbsolute(res, dateTime.timeZone);\n return toCalendar(fromAbsolute(ms, dateTime.timeZone), dateTime.calendar);\n }\n default:\n throw new Error('Unsupported field ' + field);\n }\n}\n\nexport function setZoned(dateTime: ZonedDateTime, fields: DateFields & TimeFields, disambiguation?: Disambiguation): ZonedDateTime {\n // Set the date/time fields, and recompute the UTC offset to account for DST changes.\n // We also need to validate by converting back to a local time in case hours are skipped during forward DST transitions.\n let plainDateTime = toCalendarDateTime(dateTime);\n let res = setTime(set(plainDateTime, fields), fields);\n\n // If the resulting plain date time values are equal, return the original time.\n // We don't want to change the offset when setting the time to the same value.\n if (res.compare(plainDateTime) === 0) {\n return dateTime;\n }\n\n let ms = toAbsolute(res, dateTime.timeZone, disambiguation);\n return toCalendar(fromAbsolute(ms, dateTime.timeZone), dateTime.calendar);\n}\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Portions of the code in this file are based on code from the TC39 Temporal proposal.\n// Original licensing can be found in the NOTICE file in the root directory of this source tree.\n\nimport {AnyCalendarDate, AnyDateTime, AnyTime, Calendar, DateFields, Disambiguation, TimeFields} from './types';\nimport {CalendarDate, CalendarDateTime, Time, ZonedDateTime} from './CalendarDate';\nimport {constrain} from './manipulation';\nimport {getExtendedYear, GregorianCalendar} from './calendars/GregorianCalendar';\nimport {getLocalTimeZone} from './queries';\nimport {Mutable} from './utils';\n\nexport function epochFromDate(date: AnyDateTime) {\n date = toCalendar(date, new GregorianCalendar());\n let year = getExtendedYear(date.era, date.year);\n return epochFromParts(year, date.month, date.day, date.hour, date.minute, date.second, date.millisecond);\n}\n\nfunction epochFromParts(year: number, month: number, day: number, hour: number, minute: number, second: number, millisecond: number) {\n // Note: Date.UTC() interprets one and two-digit years as being in the\n // 20th century, so don't use it\n let date = new Date();\n date.setUTCHours(hour, minute, second, millisecond);\n date.setUTCFullYear(year, month - 1, day);\n return date.getTime();\n}\n\nexport function getTimeZoneOffset(ms: number, timeZone: string) {\n // Fast path for UTC.\n if (timeZone === 'UTC') {\n return 0;\n }\n\n // Fast path: for local timezone after 1970, use native Date.\n if (ms > 0 && timeZone === getLocalTimeZone()) {\n return new Date(ms).getTimezoneOffset() * -60 * 1000;\n }\n\n let {year, month, day, hour, minute, second} = getTimeZoneParts(ms, timeZone);\n let utc = epochFromParts(year, month, day, hour, minute, second, 0);\n return utc - Math.floor(ms / 1000) * 1000;\n}\n\nconst formattersByTimeZone = new Map<string, Intl.DateTimeFormat>();\n\nfunction getTimeZoneParts(ms: number, timeZone: string) {\n let formatter = formattersByTimeZone.get(timeZone);\n if (!formatter) {\n formatter = new Intl.DateTimeFormat('en-US', {\n timeZone,\n hour12: false,\n era: 'short',\n year: 'numeric',\n month: 'numeric',\n day: 'numeric',\n hour: 'numeric',\n minute: 'numeric',\n second: 'numeric'\n });\n\n formattersByTimeZone.set(timeZone, formatter);\n }\n\n let parts = formatter.formatToParts(new Date(ms));\n let namedParts: {[name: string]: string} = {};\n for (let part of parts) {\n if (part.type !== 'literal') {\n namedParts[part.type] = part.value;\n }\n }\n\n\n return {\n // Firefox returns B instead of BC... https://bugzilla.mozilla.org/show_bug.cgi?id=1752253\n year: namedParts.era === 'BC' || namedParts.era === 'B' ? -namedParts.year + 1 : +namedParts.year,\n month: +namedParts.month,\n day: +namedParts.day,\n hour: namedParts.hour === '24' ? 0 : +namedParts.hour, // bugs.chromium.org/p/chromium/issues/detail?id=1045791\n minute: +namedParts.minute,\n second: +namedParts.second\n };\n}\n\nconst DAYMILLIS = 86400000;\n\nexport function possibleAbsolutes(date: CalendarDateTime, timeZone: string): number[] {\n let ms = epochFromDate(date);\n let earlier = ms - getTimeZoneOffset(ms - DAYMILLIS, timeZone);\n let later = ms - getTimeZoneOffset(ms + DAYMILLIS, timeZone);\n return getValidWallTimes(date, timeZone, earlier, later);\n}\n\nfunction getValidWallTimes(date: CalendarDateTime, timeZone: string, earlier: number, later: number): number[] {\n let found = earlier === later ? [earlier] : [earlier, later];\n return found.filter(absolute => isValidWallTime(date, timeZone, absolute));\n}\n\nfunction isValidWallTime(date: CalendarDateTime, timeZone: string, absolute: number) {\n let parts = getTimeZoneParts(absolute, timeZone);\n return date.year === parts.year\n && date.month === parts.month\n && date.day === parts.day\n && date.hour === parts.hour\n && date.minute === parts.minute\n && date.second === parts.second;\n}\n\nexport function toAbsolute(date: CalendarDate | CalendarDateTime, timeZone: string, disambiguation: Disambiguation = 'compatible'): number {\n let dateTime = toCalendarDateTime(date);\n\n // Fast path: if the time zone is UTC, use native Date.\n if (timeZone === 'UTC') {\n return epochFromDate(dateTime);\n }\n\n // Fast path: if the time zone is the local timezone and disambiguation is compatible, use native Date.\n if (timeZone === getLocalTimeZone() && disambiguation === 'compatible') {\n dateTime = toCalendar(dateTime, new GregorianCalendar());\n\n // Don't use Date constructor here because two-digit years are interpreted in the 20th century.\n let date = new Date();\n let year = getExtendedYear(dateTime.era, dateTime.year);\n date.setFullYear(year, dateTime.month - 1, dateTime.day);\n date.setHours(dateTime.hour, dateTime.minute, dateTime.second, dateTime.millisecond);\n return date.getTime();\n }\n\n let ms = epochFromDate(dateTime);\n let offsetBefore = getTimeZoneOffset(ms - DAYMILLIS, timeZone);\n let offsetAfter = getTimeZoneOffset(ms + DAYMILLIS, timeZone);\n let valid = getValidWallTimes(dateTime, timeZone, ms - offsetBefore, ms - offsetAfter);\n\n if (valid.length === 1) {\n return valid[0];\n }\n\n if (valid.length > 1) {\n switch (disambiguation) {\n // 'compatible' means 'earlier' for \"fall back\" transitions\n case 'compatible':\n case 'earlier':\n return valid[0];\n case 'later':\n return valid[valid.length - 1];\n case 'reject':\n throw new RangeError('Multiple possible absolute times found');\n }\n }\n\n switch (disambiguation) {\n case 'earlier':\n return Math.min(ms - offsetBefore, ms - offsetAfter);\n // 'compatible' means 'later' for \"spring forward\" transitions\n case 'compatible':\n case 'later':\n return Math.max(ms - offsetBefore, ms - offsetAfter);\n case 'reject':\n throw new RangeError('No such absolute time found');\n }\n}\n\nexport function toDate(dateTime: CalendarDate | CalendarDateTime, timeZone: string, disambiguation: Disambiguation = 'compatible'): Date {\n return new Date(toAbsolute(dateTime, timeZone, disambiguation));\n}\n\n/**\n * Takes a Unix epoch (milliseconds since 1970) and converts it to the provided time zone.\n */\nexport function fromAbsolute(ms: number, timeZone: string): ZonedDateTime {\n let offset = getTimeZoneOffset(ms, timeZone);\n let date = new Date(ms + offset);\n let year = date.getUTCFullYear();\n let month = date.getUTCMonth() + 1;\n let day = date.getUTCDate();\n let hour = date.getUTCHours();\n let minute = date.getUTCMinutes();\n let second = date.getUTCSeconds();\n let millisecond = date.getUTCMilliseconds();\n\n return new ZonedDateTime(year, month, day, timeZone, offset, hour, minute, second, millisecond);\n}\n\n/**\n * Takes a `Date` object and converts it to the provided time zone.\n */\nexport function fromDate(date: Date, timeZone: string): ZonedDateTime {\n return fromAbsolute(date.getTime(), timeZone);\n}\n\nexport function fromDateToLocal(date: Date): ZonedDateTime {\n return fromDate(date, getLocalTimeZone());\n}\n\n/** Converts a value with date components such as a `CalendarDateTime` or `ZonedDateTime` into a `CalendarDate`. */\nexport function toCalendarDate(dateTime: AnyCalendarDate): CalendarDate {\n return new CalendarDate(dateTime.calendar, dateTime.era, dateTime.year, dateTime.month, dateTime.day);\n}\n\nexport function toDateFields(date: AnyCalendarDate): DateFields {\n return {\n era: date.era,\n year: date.year,\n month: date.month,\n day: date.day\n };\n}\n\nexport function toTimeFields(date: AnyTime): TimeFields {\n return {\n hour: date.hour,\n minute: date.minute,\n second: date.second,\n millisecond: date.millisecond\n };\n}\n\n/**\n * Converts a date value to a `CalendarDateTime`. An optional `Time` value can be passed to set the time\n * of the resulting value, otherwise it will default to midnight.\n */\nexport function toCalendarDateTime(date: CalendarDate | CalendarDateTime | ZonedDateTime, time?: AnyTime): CalendarDateTime {\n let hour = 0, minute = 0, second = 0, millisecond = 0;\n if ('timeZone' in date) {\n ({hour, minute, second, millisecond} = date);\n } else if ('hour' in date && !time) {\n return date;\n }\n\n if (time) {\n ({hour, minute, second, millisecond} = time);\n }\n\n return new CalendarDateTime(\n date.calendar,\n date.era,\n date.year,\n date.month,\n date.day,\n hour,\n minute,\n second,\n millisecond\n );\n}\n\n/** Extracts the time components from a value containing a date and time. */\nexport function toTime(dateTime: CalendarDateTime | ZonedDateTime): Time {\n return new Time(dateTime.hour, dateTime.minute, dateTime.second, dateTime.millisecond);\n}\n\n/** Converts a date from one calendar system to another. */\nexport function toCalendar<T extends AnyCalendarDate>(date: T, calendar: Calendar): T {\n if (date.calendar.identifier === calendar.identifier) {\n return date;\n }\n\n let calendarDate = calendar.fromJulianDay(date.calendar.toJulianDay(date));\n let copy: Mutable<T> = date.copy();\n copy.calendar = calendar;\n copy.era = calendarDate.era;\n copy.year = calendarDate.year;\n copy.month = calendarDate.month;\n copy.day = calendarDate.day;\n constrain(copy);\n return copy;\n}\n\n/**\n * Converts a date value to a `ZonedDateTime` in the provided time zone. The `disambiguation` option can be set\n * to control how values that fall on daylight saving time changes are interpreted.\n */\nexport function toZoned(date: CalendarDate | CalendarDateTime | ZonedDateTime, timeZone: string, disambiguation?: Disambiguation): ZonedDateTime {\n if (date instanceof ZonedDateTime) {\n if (date.timeZone === timeZone) {\n return date;\n }\n\n return toTimeZone(date, timeZone);\n }\n\n let ms = toAbsolute(date, timeZone, disambiguation);\n return fromAbsolute(ms, timeZone);\n}\n\nexport function zonedToDate(date: ZonedDateTime) {\n let ms = epochFromDate(date) - date.offset;\n return new Date(ms);\n}\n\n/** Converts a `ZonedDateTime` from one time zone to another. */\nexport function toTimeZone(date: ZonedDateTime, timeZone: string): ZonedDateTime {\n let ms = epochFromDate(date) - date.offset;\n return toCalendar(fromAbsolute(ms, timeZone), date.calendar);\n}\n\n/** Converts the given `ZonedDateTime` into the user's local time zone. */\nexport function toLocalTimeZone(date: ZonedDateTime): ZonedDateTime {\n return toTimeZone(date, getLocalTimeZone());\n}\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Portions of the code in this file are based on code from ICU.\n// Original licensing can be found in the NOTICE file in the root directory of this source tree.\n\nimport {AnyCalendarDate, Calendar} from '../types';\nimport {CalendarDate} from '../CalendarDate';\nimport {mod, Mutable} from '../utils';\n\nconst EPOCH = 1721426; // 001/01/03 Julian C.E.\nexport function gregorianToJulianDay(era: string, year: number, month: number, day: number): number {\n year = getExtendedYear(era, year);\n\n let y1 = year - 1;\n let monthOffset = -2;\n if (month <= 2) {\n monthOffset = 0;\n } else if (isLeapYear(year)) {\n monthOffset = -1;\n }\n\n return (\n EPOCH -\n 1 +\n 365 * y1 +\n Math.floor(y1 / 4) -\n Math.floor(y1 / 100) +\n Math.floor(y1 / 400) +\n Math.floor((367 * month - 362) / 12 + monthOffset + day)\n );\n}\n\nexport function isLeapYear(year: number): boolean {\n return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n}\n\nexport function getExtendedYear(era: string, year: number): number {\n return era === 'BC' ? 1 - year : year;\n}\n\nexport function fromExtendedYear(year: number): [string, number] {\n let era = 'AD';\n if (year <= 0) {\n era = 'BC';\n year = 1 - year;\n }\n\n return [era, year];\n}\n\nconst daysInMonth = {\n standard: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],\n leapyear: [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n};\n\n/**\n * The Gregorian calendar is the most commonly used calendar system in the world. It supports two eras: BC, and AD.\n * Years always contain 12 months, and 365 or 366 days depending on whether it is a leap year.\n */\nexport class GregorianCalendar implements Calendar {\n identifier = 'gregory';\n\n fromJulianDay(jd: number): CalendarDate {\n let jd0 = jd;\n let depoch = jd0 - EPOCH;\n let quadricent = Math.floor(depoch / 146097);\n let dqc = mod(depoch, 146097);\n let cent = Math.floor(dqc / 36524);\n let dcent = mod(dqc, 36524);\n let quad = Math.floor(dcent / 1461);\n let dquad = mod(dcent, 1461);\n let yindex = Math.floor(dquad / 365);\n\n let extendedYear = quadricent * 400 + cent * 100 + quad * 4 + yindex + (cent !== 4 && yindex !== 4 ? 1 : 0);\n let [era, year] = fromExtendedYear(extendedYear);\n let yearDay = jd0 - gregorianToJulianDay(era, year, 1, 1);\n let leapAdj = 2;\n if (jd0 < gregorianToJulianDay(era, year, 3, 1)) {\n leapAdj = 0;\n } else if (isLeapYear(year)) {\n leapAdj = 1;\n }\n let month = Math.floor(((yearDay + leapAdj) * 12 + 373) / 367);\n let day = jd0 - gregorianToJulianDay(era, year, month, 1) + 1;\n\n return new CalendarDate(era, year, month, day);\n }\n\n toJulianDay(date: AnyCalendarDate): number {\n return gregorianToJulianDay(date.era, date.year, date.month, date.day);\n }\n\n getDaysInMonth(date: AnyCalendarDate): number {\n return daysInMonth[isLeapYear(date.year) ? 'leapyear' : 'standard'][date.month - 1];\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n getMonthsInYear(date: AnyCalendarDate): number {\n return 12;\n }\n\n getDaysInYear(date: AnyCalendarDate): number {\n return isLeapYear(date.year) ? 366 : 365;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n getYearsInEra(date: AnyCalendarDate): number {\n return 9999;\n }\n\n getEras() {\n return ['BC', 'AD'];\n }\n\n isInverseEra(date: AnyCalendarDate): boolean {\n return date.era === 'BC';\n }\n\n balanceDate(date: Mutable<AnyCalendarDate>) {\n if (date.year <= 0) {\n date.era = date.era === 'BC' ? 'AD' : 'BC';\n date.year = 1 - date.year;\n }\n }\n}\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {CalendarDate, CalendarDateTime} from './CalendarDate';\n\nexport type Mutable<T> = {\n -readonly[P in keyof T]: T[P]\n};\n\nexport function mod(amount: number, numerator: number): number {\n return amount - numerator * Math.floor(amount / numerator);\n}\n\nexport function copy(date: CalendarDate): Mutable<CalendarDate> {\n if (date.era) {\n return new CalendarDate(date.calendar, date.era, date.year, date.month, date.day);\n } else {\n return new CalendarDate(date.calendar, date.year, date.month, date.day);\n }\n}\n\nexport function copyDateTime(date: CalendarDateTime): Mutable<CalendarDateTime> {\n if (date.era) {\n return new CalendarDateTime(date.calendar, date.era, date.year, date.month, date.day, date.hour, date.minute, date.second, date.millisecond);\n } else {\n return new CalendarDateTime(date.calendar, date.year, date.month, date.day, date.hour, date.minute, date.second);\n }\n}\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {AnyCalendarDate, AnyTime} from './types';\nimport {CalendarDate, CalendarDateTime, ZonedDateTime} from './CalendarDate';\nimport {fromAbsolute, toAbsolute, toCalendar, toCalendarDate} from './conversion';\nimport {weekStartData} from './weekStartData';\n\ntype DateValue = CalendarDate | CalendarDateTime | ZonedDateTime;\n\n/** Returns whether the given dates occur on the same day, regardless of the time or calendar system. */\nexport function isSameDay(a: DateValue, b: DateValue): boolean {\n b = toCalendar(b, a.calendar);\n return a.era === b.era && a.year === b.year && a.month === b.month && a.day === b.day;\n}\n\n/** Returns whether the given dates occur in the same month, using the calendar system of the first date. */\nexport function isSameMonth(a: DateValue, b: DateValue): boolean {\n b = toCalendar(b, a.calendar);\n // In the Japanese calendar, months can span multiple eras/years, so only compare the first of the month.\n a = startOfMonth(a);\n b = startOfMonth(b);\n return a.era === b.era && a.year === b.year && a.month === b.month;\n}\n\n/** Returns whether the given dates occur in the same year, using the calendar system of the first date. */\nexport function isSameYear(a: DateValue, b: DateValue): boolean {\n b = toCalendar(b, a.calendar);\n a = startOfYear(a);\n b = startOfYear(b);\n return a.era === b.era && a.year === b.year;\n}\n\n/** Returns whether the given dates occur on the same day, and are of the same calendar system. */\nexport function isEqualDay(a: DateValue, b: DateValue): boolean {\n return a.calendar.identifier === b.calendar.identifier && a.era === b.era && a.year === b.year && a.month === b.month && a.day === b.day;\n}\n\n/** Returns whether the given dates occur in the same month, and are of the same calendar system. */\nexport function isEqualMonth(a: DateValue, b: DateValue): boolean {\n a = startOfMonth(a);\n b = startOfMonth(b);\n return a.calendar.identifier === b.calendar.identifier && a.era === b.era && a.year === b.year && a.month === b.month;\n}\n\n/** Returns whether the given dates occur in the same year, and are of the same calendar system. */\nexport function isEqualYear(a: DateValue, b: DateValue): boolean {\n a = startOfYear(a);\n b = startOfYear(b);\n return a.calendar.identifier === b.calendar.identifier && a.era === b.era && a.year === b.year;\n}\n\n/** Returns whether the date is today in the given time zone. */\nexport function isToday(date: DateValue, timeZone: string): boolean {\n return isSameDay(date, today(timeZone));\n}\n\n/**\n * Returns the day of week for the given date and locale. Days are numbered from zero to six,\n * where zero is the first day of the week in the given locale. For example, in the United States,\n * the first day of the week is Sunday, but in France it is Monday.\n */\nexport function getDayOfWeek(date: DateValue, locale: string): number {\n let julian = date.calendar.toJulianDay(date);\n\n // If julian is negative, then julian % 7 will be negative, so we adjust\n // accordingly. Julian day 0 is Monday.\n let dayOfWeek = Math.ceil(julian + 1 - getWeekStart(locale)) % 7;\n if (dayOfWeek < 0) {\n dayOfWeek += 7;\n }\n\n return dayOfWeek;\n}\n\n/** Returns the current time in the given time zone. */\nexport function now(timeZone: string): ZonedDateTime {\n return fromAbsolute(Date.now(), timeZone);\n}\n\n/** Returns today's date in the given time zone. */\nexport function today(timeZone: string): CalendarDate {\n return toCalendarDate(now(timeZone));\n}\n\nexport function compareDate(a: AnyCalendarDate, b: AnyCalendarDate): number {\n return a.calendar.toJulianDay(a) - b.calendar.toJulianDay(b);\n}\n\nexport function compareTime(a: AnyTime, b: AnyTime): number {\n return timeToMs(a) - timeToMs(b);\n}\n\nfunction timeToMs(a: AnyTime): number {\n return a.hour * 60 * 60 * 1000 + a.minute * 60 * 1000 + a.second * 1000 + a.millisecond;\n}\n\n/**\n * Returns the number of hours in the given date and time zone.\n * Usually this is 24, but it could be 23 or 25 if the date is on a daylight saving transition.\n */\nexport function getHoursInDay(a: CalendarDate, timeZone: string): number {\n let ms = toAbsolute(a, timeZone);\n let tomorrow = a.add({days: 1});\n let tomorrowMs = toAbsolute(tomorrow, timeZone);\n return (tomorrowMs - ms) / 3600000;\n}\n\nlet localTimeZone = null;\n\n/** Returns the time zone identifier for the current user. */\nexport function getLocalTimeZone(): string {\n // TODO: invalidate this somehow?\n if (localTimeZone == null) {\n localTimeZone = new Intl.DateTimeFormat().resolvedOptions().timeZone;\n }\n\n return localTimeZone;\n}\n\n/** Returns the first date of the month for the given date. */\nexport function startOfMonth(date: ZonedDateTime): ZonedDateTime;\nexport function startOfMonth(date: CalendarDateTime): CalendarDateTime;\nexport function startOfMonth(date: CalendarDate): CalendarDate;\nexport function startOfMonth(date: DateValue): DateValue;\nexport function startOfMonth(date: DateValue): DateValue {\n // Use `subtract` instead of `set` so we don't get constrained in an era.\n return date.subtract({days: date.day - 1});\n}\n\n/** Returns the last date of the month for the given date. */\nexport function endOfMonth(date: ZonedDateTime): ZonedDateTime;\nexport function endOfMonth(date: CalendarDateTime): CalendarDateTime;\nexport function endOfMonth(date: CalendarDate): CalendarDate;\nexport function endOfMonth(date: DateValue): DateValue;\nexport function endOfMonth(date: DateValue): DateValue {\n return date.add({days: date.calendar.getDaysInMonth(date) - date.day});\n}\n\n/** Returns the first day of the year for the given date. */\nexport function startOfYear(date: ZonedDateTime): ZonedDateTime;\nexport function startOfYear(date: CalendarDateTime): CalendarDateTime;\nexport function startOfYear(date: CalendarDate): CalendarDate;\nexport function startOfYear(date: DateValue): DateValue;\nexport function startOfYear(date: DateValue): DateValue {\n return startOfMonth(date.subtract({months: date.month - 1}));\n}\n\n/** Returns the last day of the year for the given date. */\nexport function endOfYear(date: ZonedDateTime): ZonedDateTime;\nexport function endOfYear(date: CalendarDateTime): CalendarDateTime;\nexport function endOfYear(date: CalendarDate): CalendarDate;\nexport function endOfYear(date: DateValue): DateValue;\nexport function endOfYear(date: DateValue): DateValue {\n return endOfMonth(date.add({months: date.calendar.getMonthsInYear(date) - date.month}));\n}\n\nexport function getMinimumMonthInYear(date: AnyCalendarDate) {\n if (date.calendar.getMinimumMonthInYear) {\n return date.calendar.getMinimumMonthInYear(date);\n }\n\n return 1;\n}\n\nexport function getMinimumDayInMonth(date: AnyCalendarDate) {\n if (date.calendar.getMinimumDayInMonth) {\n return date.calendar.getMinimumDayInMonth(date);\n }\n\n return 1;\n}\n\n/** Returns the first date of the week for the given date and locale. */\nexport function startOfWeek(date: ZonedDateTime, locale: string): ZonedDateTime;\nexport function startOfWeek(date: CalendarDateTime, locale: string): CalendarDateTime;\nexport function startOfWeek(date: CalendarDate, locale: string): CalendarDate;\nexport function startOfWeek(date: DateValue, locale: string): DateValue;\nexport function startOfWeek(date: DateValue, locale: string): DateValue {\n let dayOfWeek = getDayOfWeek(date, locale);\n return date.subtract({days: dayOfWeek});\n}\n\n/** Returns the last date of the week for the given date and locale. */\nexport function endOfWeek(date: ZonedDateTime, locale: string): ZonedDateTime;\nexport function endOfWeek(date: CalendarDateTime, locale: string): CalendarDateTime;\nexport function endOfWeek(date: CalendarDate, locale: string): CalendarDate;\nexport function endOfWeek(date: DateValue, locale: string): DateValue {\n return startOfWeek(date, locale).add({days: 6});\n}\n\nconst cachedRegions = new Map<string, string>();\n\nfunction getRegion(locale: string) {\n // If the Intl.Locale API is available, use it to get the region for the locale.\n // @ts-ignore\n if (Intl.Locale) {\n // Constructing an Intl.Locale is expensive, so cache the result.\n let region = cachedRegions.get(locale);\n if (!region) {\n // @ts-ignore\n region = new Intl.Locale(locale).maximize().region;\n cachedRegions.set(locale, region);\n }\n return region;\n }\n\n // If not, just try splitting the string.\n // If the second part of the locale string is 'u',\n // then this is a unicode extension, so ignore it.\n // Otherwise, it should be the region.\n let part = locale.split('-')[1];\n return part === 'u' ? null : part;\n}\n\nfunction getWeekStart(locale: string) {\n // TODO: use Intl.Locale for this once browsers support the weekInfo property\n // https://github.com/tc39/proposal-intl-locale-info\n let region = getRegion(locale);\n return weekStartData[region] || 0;\n}\n\n/** Returns the number of weeks in the given month and locale. */\nexport function getWeeksInMonth(date: DateValue, locale: string): number {\n let days = date.calendar.getDaysInMonth(date);\n return Math.ceil((getDayOfWeek(startOfMonth(date), locale) + days) / 7);\n}\n\n/** Returns the lesser of the two provider dates. */\nexport function minDate<A extends DateValue, B extends DateValue>(a: A, b: B): A | B {\n if (a && b) {\n return a.compare(b) <= 0 ? a : b;\n }\n\n return a || b;\n}\n\n/** Returns the greater of the two provider dates. */\nexport function maxDate<A extends DateValue, B extends DateValue>(a: A, b: B): A | B {\n if (a && b) {\n return a.compare(b) >= 0 ? a : b;\n }\n\n return a || b;\n}\n\nconst WEEKEND_DATA = {\n AF: [4, 5],\n AE: [5, 6],\n BH: [5, 6],\n DZ: [5, 6],\n EG: [5, 6],\n IL: [5, 6],\n IQ: [5, 6],\n IR: [5, 5],\n JO: [5, 6],\n KW: [5, 6],\n LY: [5, 6],\n OM: [5, 6],\n QA: [5, 6],\n SA: [5, 6],\n SD: [5, 6],\n SY: [5, 6],\n YE: [5, 6]\n};\n\n/** Returns whether the given date is on a weekend in the given locale. */\nexport function isWeekend(date: DateValue, locale: string): boolean {\n let julian = date.calendar.toJulianDay(date);\n\n // If julian is negative, then julian % 7 will be negative, so we adjust\n // accordingly. Julian day 0 is Monday.\n let dayOfWeek = Math.ceil(julian + 1) % 7;\n if (dayOfWeek < 0) {\n dayOfWeek += 7;\n }\n\n let region = getRegion(locale);\n // Use Intl.Locale for this once weekInfo is supported.\n // https://github.com/tc39/proposal-intl-locale-info\n let [start, end] = WEEKEND_DATA[region] || [6, 0];\n return dayOfWeek === start || dayOfWeek === end;\n}\n\n/** Returns whether the given date is on a weekday in the given locale. */\nexport function isWeekday(date: DateValue, locale: string): boolean {\n return !isWeekend(date, locale);\n}\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Data from https://github.com/unicode-cldr/cldr-core/blob/master/supplemental/weekData.json\n// Locales starting on Sunday have been removed for compression.\nexport const weekStartData = {\n '001': 1,\n AD: 1,\n AE: 6,\n AF: 6,\n AI: 1,\n AL: 1,\n AM: 1,\n AN: 1,\n AR: 1,\n AT: 1,\n AU: 1,\n AX: 1,\n AZ: 1,\n BA: 1,\n BE: 1,\n BG: 1,\n BH: 6,\n BM: 1,\n BN: 1,\n BY: 1,\n CH: 1,\n CL: 1,\n CM: 1,\n CN: 1,\n CR: 1,\n CY: 1,\n CZ: 1,\n DE: 1,\n DJ: 6,\n DK: 1,\n DZ: 6,\n EC: 1,\n EE: 1,\n EG: 6,\n ES: 1,\n FI: 1,\n FJ: 1,\n FO: 1,\n FR: 1,\n GB: 1,\n GE: 1,\n GF: 1,\n GP: 1,\n GR: 1,\n HR: 1,\n HU: 1,\n IE: 1,\n IQ: 6,\n IR: 6,\n IS: 1,\n IT: 1,\n JO: 6,\n KG: 1,\n KW: 6,\n KZ: 1,\n LB: 1,\n LI: 1,\n LK: 1,\n LT: 1,\n LU: 1,\n LV: 1,\n LY: 6,\n MC: 1,\n MD: 1,\n ME: 1,\n MK: 1,\n MN: 1,\n MQ: 1,\n MV: 5,\n MY: 1,\n NL: 1,\n NO: 1,\n NZ: 1,\n OM: 6,\n PL: 1,\n QA: 6,\n RE: 1,\n RO: 1,\n RS: 1,\n RU: 1,\n SD: 6,\n SE: 1,\n SI: 1,\n SK: 1,\n SM: 1,\n SY: 6,\n TJ: 1,\n TM: 1,\n TR: 1,\n UA: 1,\n UY: 1,\n UZ: 1,\n VA: 1,\n VN: 1,\n XK: 1\n};\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {AnyDateTime, DateTimeDuration, Disambiguation} from './types';\nimport {CalendarDate, CalendarDateTime, Time, ZonedDateTime} from './CalendarDate';\nimport {epochFromDate, fromAbsolute, possibleAbsolutes, toAbsolute, toCalendar, toCalendarDateTime, toTimeZone} from './conversion';\nimport {getLocalTimeZone} from './queries';\nimport {GregorianCalendar} from './calendars/GregorianCalendar';\nimport {Mutable} from './utils';\n\nconst TIME_RE = /^(\\d{2})(?::(\\d{2}))?(?::(\\d{2}))?(\\.\\d+)?$/;\nconst DATE_RE = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\nconst DATE_TIME_RE = /^(\\d{4})-(\\d{2})-(\\d{2})(?:T(\\d{2}))?(?::(\\d{2}))?(?::(\\d{2}))?(\\.\\d+)?$/;\nconst ZONED_DATE_TIME_RE = /^(\\d{4})-(\\d{2})-(\\d{2})(?:T(\\d{2}))?(?::(\\d{2}))?(?::(\\d{2}))?(\\.\\d+)?(?:([+-]\\d{2})(?::?(\\d{2}))?)?\\[(.*?)\\]$/;\nconst ABSOLUTE_RE = /^(\\d{4})-(\\d{2})-(\\d{2})(?:T(\\d{2}))?(?::(\\d{2}))?(?::(\\d{2}))?(\\.\\d+)?(?:(?:([+-]\\d{2})(?::?(\\d{2}))?)|Z)$/;\nconst DATE_TIME_DURATION_RE =\n /^((?<negative>-)|\\+)?P((?<years>\\d*)Y)?((?<months>\\d*)M)?((?<weeks>\\d*)W)?((?<days>\\d*)D)?((?<time>T)((?<hours>\\d*[.,]?\\d{1,9})H)?((?<minutes>\\d*[.,]?\\d{1,9})M)?((?<seconds>\\d*[.,]?\\d{1,9})S)?)?$/;\nconst requiredDurationTimeGroups = ['hours', 'minutes', 'seconds'];\nconst requiredDurationGroups = ['years', 'months', 'weeks', 'days', ...requiredDurationTimeGroups];\n\n/** Parses an ISO 8601 time string. */\nexport function parseTime(value: string): Time {\n let m = value.match(TIME_RE);\n if (!m) {\n throw new Error('Invalid ISO 8601 time string: ' + value);\n }\n\n return new Time(\n parseNumber(m[1], 0, 23),\n m[2] ? parseNumber(m[2], 0, 59) : 0,\n m[3] ? parseNumber(m[3], 0, 59) : 0,\n m[4] ? parseNumber(m[4], 0, Infinity) * 1000 : 0\n );\n}\n\n/** Parses an ISO 8601 date string, with no time components. */\nexport function parseDate(value: string): CalendarDate {\n let m = value.match(DATE_RE);\n if (!m) {\n throw new Error('Invalid ISO 8601 date string: ' + value);\n }\n\n let date: Mutable<CalendarDate> = new CalendarDate(\n parseNumber(m[1], 0, 9999),\n parseNumber(m[2], 1, 12),\n 1\n );\n\n date.day = parseNumber(m[3], 0, date.calendar.getDaysInMonth(date));\n return date as CalendarDate;\n}\n\n/** Parses an ISO 8601 date and time string, with no time zone. */\nexport function parseDateTime(value: string): CalendarDateTime {\n let m = value.match(DATE_TIME_RE);\n if (!m) {\n throw new Error('Invalid ISO 8601 date time string: ' + value);\n }\n\n let date: Mutable<CalendarDateTime> = new CalendarDateTime(\n parseNumber(m[1], 1, 9999),\n parseNumber(m[2], 1, 12),\n 1,\n m[4] ? parseNumber(m[4], 0, 23) : 0,\n m[5] ? parseNumber(m[5], 0, 59) : 0,\n m[6] ? parseNumber(m[6], 0, 59) : 0,\n m[7] ? parseNumber(m[7], 0, Infinity) * 1000 : 0\n );\n\n date.day = parseNumber(m[3], 0, date.calendar.getDaysInMonth(date));\n return date as CalendarDateTime;\n}\n\n/**\n * Parses an ISO 8601 date and time string with a time zone extension and optional UTC offset\n * (e.g. \"2021-11-07T00:45[America/Los_Angeles]\" or \"2021-11-07T00:45-07:00[America/Los_Angeles]\").\n * Ambiguous times due to daylight saving time transitions are resolved according to the `disambiguation`\n * parameter.\n */\nexport function parseZonedDateTime(value: string, disambiguation?: Disambiguation): ZonedDateTime {\n let m = value.match(ZONED_DATE_TIME_RE);\n if (!m) {\n throw new Error('Invalid ISO 8601 date time string: ' + value);\n }\n\n let date: Mutable<ZonedDateTime> = new ZonedDateTime(\n parseNumber(m[1], 1, 9999),\n parseNumber(m[2], 1, 12),\n 1,\n m[10],\n 0,\n m[4] ? parseNumber(m[4], 0, 23) : 0,\n m[5] ? parseNumber(m[5], 0, 59) : 0,\n m[6] ? parseNumber(m[6], 0, 59) : 0,\n m[7] ? parseNumber(m[7], 0, Infinity) * 1000 : 0\n );\n\n date.day = parseNumber(m[3], 0, date.calendar.getDaysInMonth(date));\n\n let plainDateTime = toCalendarDateTime(date as ZonedDateTime);\n\n let ms: number;\n if (m[8]) {\n date.offset = parseNumber(m[8], -23, 23) * 60 * 60 * 1000 + parseNumber(m[9] ?? '0', 0, 59) * 60 * 1000;\n ms = epochFromDate(date as ZonedDateTime) - date.offset;\n\n // Validate offset against parsed date.\n let absolutes = possibleAbsolutes(plainDateTime, date.timeZone);\n if (!absolutes.includes(ms)) {\n throw new Error(`Offset ${offsetToString(date.offset)} is invalid for ${dateTimeToString(date)} in ${date.timeZone}`);\n }\n } else {\n // Convert to absolute and back to fix invalid times due to DST.\n ms = toAbsolute(toCalendarDateTime(plainDateTime), date.timeZone, disambiguation);\n }\n\n return fromAbsolute(ms, date.timeZone);\n}\n\n/**\n * Parses an ISO 8601 date and time string with a UTC offset (e.g. \"2021-11-07T07:45:00Z\"\n * or \"2021-11-07T07:45:00-07:00\"). The result is converted to the provided time zone.\n */\nexport function parseAbsolute(value: string, timeZone: string): ZonedDateTime {\n let m = value.match(ABSOLUTE_RE);\n if (!m) {\n throw new Error('Invalid ISO 8601 date time string: ' + value);\n }\n\n let date: Mutable<ZonedDateTime> = new ZonedDateTime(\n parseNumber(m[1], 1, 9999),\n parseNumber(m[2], 1, 12),\n 1,\n timeZone,\n 0,\n m[4] ? parseNumber(m[4], 0, 23) : 0,\n m[5] ? parseNumber(m[5], 0, 59) : 0,\n m[6] ? parseNumber(m[6], 0, 59) : 0,\n m[7] ? parseNumber(m[7], 0, Infinity) * 1000 : 0\n );\n\n date.day = parseNumber(m[3], 0, date.calendar.getDaysInMonth(date));\n\n if (m[8]) {\n date.offset = parseNumber(m[8], -23, 23) * 60 * 60 * 1000 + parseNumber(m[9] ?? '0', 0, 59) * 60 * 1000;\n }\n\n return toTimeZone(date as ZonedDateTime, timeZone);\n}\n\n/**\n * Parses an ISO 8601 date and time string with a UTC offset (e.g. \"2021-11-07T07:45:00Z\"\n * or \"2021-11-07T07:45:00-07:00\"). The result is converted to the user's local time zone.\n */\nexport function parseAbsoluteToLocal(value: string): ZonedDateTime {\n return parseAbsolute(value, getLocalTimeZone());\n}\n\nfunction parseNumber(value: string, min: number, max: number) {\n let val = Number(value);\n if (val < min || val > max) {\n throw new RangeError(`Value out of range: ${min} <= ${val} <= ${max}`);\n }\n\n return val;\n}\n\nexport function timeToString(time: Time): string {\n return `${String(time.hour).padStart(2, '0')}:${String(time.minute).padStart(2, '0')}:${String(time.second).padStart(2, '0')}${time.millisecond ? String(time.millisecond / 1000).slice(1) : ''}`;\n}\n\nexport function dateToString(date: CalendarDate): string {\n let gregorianDate = toCalendar(date, new GregorianCalendar());\n return `${String(gregorianDate.year).padStart(4, '0')}-${String(gregorianDate.month).padStart(2, '0')}-${String(gregorianDate.day).padStart(2, '0')}`;\n}\n\nexport function dateTimeToString(date: AnyDateTime): string {\n // @ts-ignore\n return `${dateToString(date)}T${timeToString(date)}`;\n}\n\nfunction offsetToString(offset: number) {\n let sign = Math.sign(offset) < 0 ? '-' : '+';\n offset = Math.abs(offset);\n let offsetHours = Math.floor(offset / (60 * 60 * 1000));\n let offsetMinutes = (offset % (60 * 60 * 1000)) / (60 * 1000);\n return `${sign}${String(offsetHours).padStart(2, '0')}:${String(offsetMinutes).padStart(2, '0')}`;\n}\n\nexport function zonedDateTimeToString(date: ZonedDateTime): string {\n return `${dateTimeToString(date)}${offsetToString(date.offset)}[${date.timeZone}]`;\n}\n\n/**\n * Parses an ISO 8601 duration string (e.g. \"P3Y6M6W4DT12H30M5S\").\n * @param value An ISO 8601 duration string.\n * @returns A DateTimeDuration object.\n */\nexport function parseDuration(value: string): Required<DateTimeDuration> {\n const match = value.match(DATE_TIME_DURATION_RE);\n\n if (!match) {\n throw new Error(`Invalid ISO 8601 Duration string: ${value}`);\n }\n\n const parseDurationGroup = (\n group: string | undefined,\n isNegative: boolean,\n min: number,\n max: number\n ): number => {\n if (!group) {\n return 0;\n }\n try {\n const sign = isNegative ? -1 : 1;\n return sign * parseNumber(group.replace(',', '.'), min, max);\n } catch {\n throw new Error(`Invalid ISO 8601 Duration string: ${value}`);\n }\n };\n\n const isNegative = !!match.groups?.negative;\n\n const hasRequiredGroups = requiredDurationGroups.some(group => match.groups?.[group]);\n\n if (!hasRequiredGroups) {\n throw new Error(`Invalid ISO 8601 Duration string: ${value}`);\n }\n\n const durationStringIncludesTime = match.groups?.time;\n\n if (durationStringIncludesTime) {\n const hasRequiredDurationTimeGroups = requiredDurationTimeGroups.some(group => match.groups?.[group]);\n if (!hasRequiredDurationTimeGroups) {\n throw new Error(`Invalid ISO 8601 Duration string: ${value}`);\n }\n }\n\n const duration: Mutable<DateTimeDuration> = {\n years: parseDurationGroup(match.groups?.years, isNegative, 0, 9999),\n months: parseDurationGroup(match.groups?.months, isNegative, 0, 12),\n weeks: parseDurationGroup(match.groups?.weeks, isNegative, 0, Infinity),\n days: parseDurationGroup(match.groups?.days, isNegative, 0, 31),\n hours: parseDurationGroup(match.groups?.hours, isNegative, 0, 23),\n minutes: parseDurationGroup(match.groups?.minutes, isNegative, 0, 59),\n seconds: parseDurationGroup(match.groups?.seconds, isNegative, 0, 59)\n };\n\n if (((duration.hours % 1) !== 0) && (duration.minutes || duration.seconds)) {\n throw new Error(`Invalid ISO 8601 Duration string: ${value} - only the smallest unit can be fractional`);\n }\n\n if (((duration.minutes % 1) !== 0) && duration.seconds) {\n throw new Error(`Invalid ISO 8601 Duration string: ${value} - only the smallest unit can be fractional`);\n }\n\n return duration as Required<DateTimeDuration>;\n}\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Portions of the code in this file are based on code from the TC39 Temporal proposal.\n// Original licensing can be found in the NOTICE file in the root directory of this source tree.\n\nimport {AnyCalendarDate} from '../types';\nimport {CalendarDate} from '../CalendarDate';\nimport {GregorianCalendar} from './GregorianCalendar';\nimport {Mutable} from '../utils';\n\nconst ERA_START_DATES = [[1868, 9, 8], [1912, 7, 30], [1926, 12, 25], [1989, 1, 8], [2019, 5, 1]];\nconst ERA_END_DATES = [[1912, 7, 29], [1926, 12, 24], [1989, 1, 7], [2019, 4, 30]];\nconst ERA_ADDENDS = [1867, 1911, 1925, 1988, 2018];\nconst ERA_NAMES = ['meiji', 'taisho', 'showa', 'heisei', 'reiwa'];\n\nfunction findEraFromGregorianDate(date: AnyCalendarDate) {\n const idx = ERA_START_DATES.findIndex(([year, month, day]) => {\n if (date.year < year) {\n return true;\n }\n\n if (date.year === year && date.month < month) {\n return true;\n }\n\n if (date.year === year && date.month === month && date.day < day) {\n return true;\n }\n\n return false;\n });\n\n if (idx === -1) {\n return ERA_START_DATES.length - 1;\n }\n\n if (idx === 0) {\n return 0;\n }\n\n return idx - 1;\n}\n\nfunction toGregorian(date: AnyCalendarDate) {\n let eraAddend = ERA_ADDENDS[ERA_NAMES.indexOf(date.era)];\n if (!eraAddend) {\n throw new Error('Unknown era: ' + date.era);\n }\n\n return new CalendarDate(\n date.year + eraAddend,\n date.month,\n date.day\n );\n}\n\n/**\n * The Japanese calendar is based on the Gregorian calendar, but with eras for the reign of each Japanese emperor.\n * Whenever a new emperor ascends to the throne, a new era begins and the year starts again from 1.\n * Note that eras before 1868 (Gregorian) are not currently supported by this implementation.\n */\nexport class JapaneseCalendar extends GregorianCalendar {\n identifier = 'japanese';\n\n fromJulianDay(jd: number): CalendarDate {\n let date = super.fromJulianDay(jd);\n let era = findEraFromGregorianDate(date);\n\n return new CalendarDate(\n this,\n ERA_NAMES[era],\n date.year - ERA_ADDENDS[era],\n date.month,\n date.day\n );\n }\n\n toJulianDay(date: AnyCalendarDate) {\n return super.toJulianDay(toGregorian(date));\n }\n\n balanceDate(date: Mutable<AnyCalendarDate>) {\n let gregorianDate = toGregorian(date);\n let era = findEraFromGregorianDate(gregorianDate);\n\n if (ERA_NAMES[era] !== date.era) {\n date.era = ERA_NAMES[era];\n date.year = gregorianDate.year - ERA_ADDENDS[era];\n }\n\n // Constrain in case we went before the first supported era.\n this.constrainDate(date);\n }\n\n constrainDate(date: Mutable<AnyCalendarDate>) {\n let idx = ERA_NAMES.indexOf(date.era);\n let end = ERA_END_DATES[idx];\n if (end != null) {\n let [endYear, endMonth, endDay] = end;\n\n // Constrain the year to the maximum possible value in the era.\n // Then constrain the month and day fields within that.\n let maxYear = endYear - ERA_ADDENDS[idx];\n date.year = Math.max(1, Math.min(maxYear, date.year));\n if (date.year === maxYear) {\n date.month = Math.min(endMonth, date.month);\n\n if (date.month === endMonth) {\n date.day = Math.min(endDay, date.day);\n }\n }\n }\n\n if (date.year === 1 && idx >= 0) {\n let [, startMonth, startDay] = ERA_START_DATES[idx];\n date.month = Math.max(startMonth, date.month);\n\n if (date.month === startMonth) {\n date.day = Math.max(startDay, date.day);\n }\n }\n }\n\n getEras() {\n return ERA_NAMES;\n }\n\n getYearsInEra(date: AnyCalendarDate): number {\n // Get the number of years in the era, taking into account the date's month and day fields.\n let era = ERA_NAMES.indexOf(date.era);\n let cur = ERA_START_DATES[era];\n let next = ERA_START_DATES[era + 1];\n if (next == null) {\n // 9999 gregorian is the maximum year allowed.\n return 9999 - cur[0] + 1;\n }\n\n let years = next[0] - cur[0];\n\n if (date.month < next[1] || (date.month === next[1] && date.day < next[2])) {\n years++;\n }\n\n return years;\n }\n\n getDaysInMonth(date: AnyCalendarDate): number {\n return super.getDaysInMonth(toGregorian(date));\n }\n\n getMinimumMonthInYear(date: AnyCalendarDate): number {\n let start = getMinimums(date);\n return start ? start[1] : 1;\n }\n\n getMinimumDayInMonth(date: AnyCalendarDate): number {\n let start = getMinimums(date);\n return start && date.month === start[1] ? start[2] : 1;\n }\n}\n\nfunction getMinimums(date: AnyCalendarDate) {\n if (date.year === 1) {\n let idx = ERA_NAMES.indexOf(date.era);\n return ERA_START_DATES[idx];\n }\n}\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Portions of the code in this file are based on code from ICU.\n// Original licensing can be found in the NOTICE file in the root directory of this source tree.\n\nimport {AnyCalendarDate} from '../types';\nimport {CalendarDate} from '../CalendarDate';\nimport {fromExtendedYear, getExtendedYear, GregorianCalendar} from './GregorianCalendar';\n\nconst BUDDHIST_ERA_START = -543;\n\n/**\n * The Buddhist calendar is the same as the Gregorian calendar, but counts years\n * starting from the birth of Buddha in 543 BC (Gregorian). It supports only one\n * era, identified as 'BE'.\n */\nexport class BuddhistCalendar extends GregorianCalendar {\n identifier = 'buddhist';\n\n fromJulianDay(jd: number): CalendarDate {\n let gregorianDate = super.fromJulianDay(jd);\n let year = getExtendedYear(gregorianDate.era, gregorianDate.year);\n return new CalendarDate(\n this,\n year - BUDDHIST_ERA_START,\n gregorianDate.month,\n gregorianDate.day\n );\n }\n\n toJulianDay(date: AnyCalendarDate) {\n return super.toJulianDay(toGregorian(date));\n }\n\n getEras() {\n return ['BE'];\n }\n\n getDaysInMonth(date: AnyCalendarDate): number {\n return super.getDaysInMonth(toGregorian(date));\n }\n\n balanceDate() {}\n}\n\nfunction toGregorian(date: AnyCalendarDate) {\n let [era, year] = fromExtendedYear(date.year + BUDDHIST_ERA_START);\n return new CalendarDate(\n era,\n year,\n date.month,\n date.day\n );\n}\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Portions of the code in this file are based on code from ICU.\n// Original licensing can be found in the NOTICE file in the root directory of this source tree.\n\nimport {AnyCalendarDate} from '../types';\nimport {CalendarDate} from '../CalendarDate';\nimport {fromExtendedYear, getExtendedYear, GregorianCalendar} from './GregorianCalendar';\nimport {Mutable} from '../utils';\n\nconst TAIWAN_ERA_START = 1911;\n\nfunction gregorianYear(date: AnyCalendarDate) {\n return date.era === 'minguo'\n ? date.year + TAIWAN_ERA_START\n : 1 - date.year + TAIWAN_ERA_START;\n}\n\nfunction gregorianToTaiwan(year: number): [string, number] {\n let y = year - TAIWAN_ERA_START;\n if (y > 0) {\n return ['minguo', y];\n } else {\n return ['before_minguo', 1 - y];\n }\n}\n\n/**\n * The Taiwanese calendar is the same as the Gregorian calendar, but years\n * are numbered starting from 1912 (Gregorian). Two eras are supported:\n * 'before_minguo' and 'minguo'.\n */\nexport class TaiwanCalendar extends GregorianCalendar {\n identifier = 'roc'; // Republic of China\n\n fromJulianDay(jd: number): CalendarDate {\n let date = super.fromJulianDay(jd);\n let extendedYear = getExtendedYear(date.era, date.year);\n let [era, year] = gregorianToTaiwan(extendedYear);\n return new CalendarDate(this, era, year, date.month, date.day);\n }\n\n toJulianDay(date: AnyCalendarDate) {\n return super.toJulianDay(toGregorian(date));\n }\n\n getEras() {\n return ['before_minguo', 'minguo'];\n }\n\n balanceDate(date: Mutable<AnyCalendarDate>) {\n let [era, year] = gregorianToTaiwan(gregorianYear(date));\n date.era = era;\n date.year = year;\n }\n\n isInverseEra(date: AnyCalendarDate): boolean {\n return date.era === 'before_minguo';\n }\n\n getDaysInMonth(date: AnyCalendarDate): number {\n return super.getDaysInMonth(toGregorian(date));\n }\n\n getYearsInEra(date: AnyCalendarDate): number {\n return date.era === 'before_minguo' ? 9999 : 9999 - TAIWAN_ERA_START;\n }\n}\n\nfunction toGregorian(date: AnyCalendarDate) {\n let [era, year] = fromExtendedYear(gregorianYear(date));\n return new CalendarDate(\n era,\n year,\n date.month,\n date.day\n );\n}\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Portions of the code in this file are based on code from ICU.\n// Original licensing can be found in the NOTICE file in the root directory of this source tree.\n\nimport {AnyCalendarDate, Calendar} from '../types';\nimport {CalendarDate} from '../CalendarDate';\nimport {mod} from '../utils';\n\nconst PERSIAN_EPOCH = 1948321; // 622/03/19 Julian C.E.\n\nfunction isLeapYear(year: number): boolean {\n let y0 = year > 0 ? year - 474 : year - 473;\n let y1 = mod(y0, 2820) + 474;\n\n return mod((y1 + 38) * 31, 128) < 31;\n}\n\nfunction persianToJulianDay(year: number, month: number, day: number): number {\n let y0 = year > 0 ? year - 474 : year - 473;\n let y1 = mod(y0, 2820) + 474;\n let offset = month <= 7 ? 31 * (month - 1) : 30 * (month - 1) + 6;\n\n return (\n PERSIAN_EPOCH -\n 1 +\n 1029983 * Math.floor(y0 / 2820) +\n 365 * (y1 - 1) +\n Math.floor((31 * y1 - 5) / 128) +\n offset +\n day\n );\n}\n\n/**\n * The Persian calendar is the main calendar used in Iran and Afghanistan. It has 12 months\n * in each year, the first 6 of which have 31 days, and the next 5 have 30 days. The 12th month\n * has either 29 or 30 days depending on whether it is a leap year. The Persian year starts\n * around the March equinox.\n */\nexport class PersianCalendar implements Calendar {\n identifier = 'persian';\n\n fromJulianDay(jd: number): CalendarDate {\n let d0 = jd - persianToJulianDay(475, 1, 1);\n let n2820 = Math.floor(d0 / 1029983);\n let d1 = mod(d0, 1029983);\n let y2820 = d1 === 1029982 ? 2820 : Math.floor((128 * d1 + 46878) / 46751);\n let year = 474 + 2820 * n2820 + y2820;\n if (year <= 0) {\n year--;\n }\n\n let yDay = jd - persianToJulianDay(year, 1, 1) + 1;\n let month = yDay <= 186 ? Math.ceil(yDay / 31) : Math.ceil((yDay - 6) / 31);\n let day = jd - persianToJulianDay(year, month, 1) + 1;\n\n return new CalendarDate(this, year, month, day);\n }\n\n toJulianDay(date: AnyCalendarDate): number {\n return persianToJulianDay(date.year, date.month, date.day);\n }\n\n getMonthsInYear(): number {\n return 12;\n }\n\n getDaysInMonth(date: AnyCalendarDate): number {\n if (date.month <= 6) {\n return 31;\n }\n\n if (date.month <= 11) {\n return 30;\n }\n\n return isLeapYear(date.year) ? 30 : 29;\n }\n\n getEras() {\n return ['AP'];\n }\n\n getYearsInEra(): number {\n // 9378-10-10 persian is 9999-12-31 gregorian.\n // Round down to 9377 to set the maximum full year.\n return 9377;\n }\n}\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Portions of the code in this file are based on code from ICU.\n// Original licensing can be found in the NOTICE file in the root directory of this source tree.\n\nimport {AnyCalendarDate} from '../types';\nimport {CalendarDate} from '../CalendarDate';\nimport {fromExtendedYear, GregorianCalendar, gregorianToJulianDay, isLeapYear} from './GregorianCalendar';\n\n// Starts in 78 AD,\nconst INDIAN_ERA_START = 78;\n\n// The Indian year starts 80 days later than the Gregorian year.\nconst INDIAN_YEAR_START = 80;\n\n/**\n * The Indian National Calendar is similar to the Gregorian calendar, but with\n * years numbered since the Saka era in 78 AD (Gregorian). There are 12 months\n * in each year, with either 30 or 31 days. Only one era identifier is supported: 'saka'.\n */\nexport class IndianCalendar extends GregorianCalendar {\n identifier = 'indian';\n\n fromJulianDay(jd: number): CalendarDate {\n // Gregorian date for Julian day\n let date = super.fromJulianDay(jd);\n\n // Year in Saka era\n let indianYear = date.year - INDIAN_ERA_START;\n\n // Day number in Gregorian year (starting from 0)\n let yDay = jd - gregorianToJulianDay(date.era, date.year, 1, 1);\n\n let leapMonth: number;\n if (yDay < INDIAN_YEAR_START) {\n // Day is at the end of the preceding Saka year\n indianYear--;\n\n // Days in leapMonth this year, previous Gregorian year\n leapMonth = isLeapYear(date.year - 1) ? 31 : 30;\n yDay += leapMonth + (31 * 5) + (30 * 3) + 10;\n } else {\n // Days in leapMonth this year\n leapMonth = isLeapYear(date.year) ? 31 : 30;\n yDay -= INDIAN_YEAR_START;\n }\n\n let indianMonth: number;\n let indianDay: number;\n if (yDay < leapMonth) {\n indianMonth = 1;\n indianDay = yDay + 1;\n } else {\n let mDay = yDay - leapMonth;\n if (mDay < (31 * 5)) {\n indianMonth = Math.floor(mDay / 31) + 2;\n indianDay = (mDay % 31) + 1;\n } else {\n mDay -= 31 * 5;\n indianMonth = Math.floor(mDay / 30) + 7;\n indianDay = (mDay % 30) + 1;\n }\n }\n\n return new CalendarDate(this, indianYear, indianMonth, indianDay);\n }\n\n toJulianDay(date: AnyCalendarDate) {\n let extendedYear = date.year + INDIAN_ERA_START;\n let [era, year] = fromExtendedYear(extendedYear);\n\n let leapMonth: number;\n let jd: number;\n if (isLeapYear(year)) {\n leapMonth = 31;\n jd = gregorianToJulianDay(era, year, 3, 21);\n } else {\n leapMonth = 30;\n jd = gregorianToJulianDay(era, year, 3, 22);\n }\n\n if (date.month === 1) {\n return jd + date.day - 1;\n }\n\n jd += leapMonth + Math.min(date.month - 2, 5) * 31;\n\n if (date.month >= 8) {\n jd += (date.month - 7) * 30;\n }\n\n jd += date.day - 1;\n return jd;\n }\n\n getDaysInMonth(date: AnyCalendarDate): number {\n if (date.month === 1 && isLeapYear(date.year + INDIAN_ERA_START)) {\n return 31;\n }\n\n if (date.month >= 2 && date.month <= 6) {\n return 31;\n }\n\n return 30;\n }\n\n getYearsInEra(): number {\n // 9999-12-31 gregorian is 9920-10-10 indian.\n // Round down to 9919 for the last full year.\n return 9919;\n }\n\n getEras() {\n return ['saka'];\n }\n\n balanceDate() {}\n}\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Portions of the code in this file are based on code from ICU.\n// Original licensing can be found in the NOTICE file in the root directory of this source tree.\n\nimport {AnyCalendarDate, Calendar} from '../types';\nimport {CalendarDate} from '../CalendarDate';\n\nconst CIVIL_EPOC = 1948440; // CE 622 July 16 Friday (Julian calendar) / CE 622 July 19 (Gregorian calendar)\nconst ASTRONOMICAL_EPOC = 1948439; // CE 622 July 15 Thursday (Julian calendar)\nconst UMALQURA_YEAR_START = 1300;\nconst UMALQURA_YEAR_END = 1600;\nconst UMALQURA_START_DAYS = 460322;\n\nfunction islamicToJulianDay(epoch: number, year: number, month: number, day: number): number {\n return day +\n Math.ceil(29.5 * (month - 1)) +\n (year - 1) * 354 +\n Math.floor((3 + 11 * year) / 30) +\n epoch - 1;\n}\n\nfunction julianDayToIslamic(calendar: Calendar, epoch: number, jd: number) {\n let year = Math.floor((30 * (jd - epoch) + 10646) / 10631);\n let month = Math.min(12, Math.ceil((jd - (29 + islamicToJulianDay(epoch, year, 1, 1))) / 29.5) + 1);\n let day = jd - islamicToJulianDay(epoch, year, month, 1) + 1;\n\n return new CalendarDate(calendar, year, month, day);\n}\n\nfunction isLeapYear(year: number): boolean {\n return (14 + 11 * year) % 30 < 11;\n}\n\n/**\n * The Islamic calendar, also known as the \"Hijri\" calendar, is used throughout much of the Arab world.\n * The civil variant uses simple arithmetic rules rather than astronomical calculations to approximate\n * the traditional calendar, which is based on sighting of the crescent moon. It uses Friday, July 16 622 CE (Julian) as the epoch.\n * Each year has 12 months, with either 354 or 355 days depending on whether it is a leap year.\n * Learn more about the available Islamic calendars [here](https://cldr.unicode.org/development/development-process/design-proposals/islamic-calendar-types).\n */\nexport class IslamicCivilCalendar implements Calendar {\n identifier = 'islamic-civil';\n\n fromJulianDay(jd: number): CalendarDate {\n return julianDayToIslamic(this, CIVIL_EPOC, jd);\n }\n\n toJulianDay(date: AnyCalendarDate) {\n return islamicToJulianDay(CIVIL_EPOC, date.year, date.month, date.day);\n }\n\n getDaysInMonth(date: AnyCalendarDate): number {\n let length = 29 + date.month % 2;\n if (date.month === 12 && isLeapYear(date.year)) {\n length++;\n }\n\n return length;\n }\n\n getMonthsInYear(): number {\n return 12;\n }\n\n getDaysInYear(date: AnyCalendarDate): number {\n return isLeapYear(date.year) ? 355 : 354;\n }\n\n getYearsInEra(): number {\n // 9999 gregorian\n return 9665;\n }\n\n getEras() {\n return ['AH'];\n }\n}\n\n/**\n * The Islamic calendar, also known as the \"Hijri\" calendar, is used throughout much of the Arab world.\n * The tabular variant uses simple arithmetic rules rather than astronomical calculations to approximate\n * the traditional calendar, which is based on sighting of the crescent moon. It uses Thursday, July 15 622 CE (Julian) as the epoch.\n * Each year has 12 months, with either 354 or 355 days depending on whether it is a leap year.\n * Learn more about the available Islamic calendars [here](https://cldr.unicode.org/development/development-process/design-proposals/islamic-calendar-types).\n */\nexport class IslamicTabularCalendar extends IslamicCivilCalendar {\n identifier = 'islamic-tbla';\n\n fromJulianDay(jd: number): CalendarDate {\n return julianDayToIslamic(this, ASTRONOMICAL_EPOC, jd);\n }\n\n toJulianDay(date: AnyCalendarDate) {\n return islamicToJulianDay(ASTRONOMICAL_EPOC, date.year, date.month, date.day);\n }\n}\n\n// Generated by scripts/generate-umalqura.js\nconst UMALQURA_DATA = 'qgpUDckO1AbqBmwDrQpVBakGkgepC9QF2gpcBS0NlQZKB1QLagutBa4ETwoXBYsGpQbVCtYCWwmdBE0KJg2VDawFtgm6AlsKKwWVCsoG6Qr0AnYJtgJWCcoKpAvSC9kF3AJtCU0FpQpSC6ULtAW2CVcFlwJLBaMGUgdlC2oFqworBZUMSg2lDcoF1gpXCasESwmlClILagt1BXYCtwhbBFUFqQW0BdoJ3QRuAjYJqgpUDbIN1QXaAlsJqwRVCkkLZAtxC7QFtQpVCiUNkg7JDtQG6QprCasEkwpJDaQNsg25CroEWworBZUKKgtVC1wFvQQ9Ah0JlQpKC1oLbQW2AjsJmwRVBqkGVAdqC2wFrQpVBSkLkgupC9QF2gpaBasKlQVJB2QHqgu1BbYCVgpNDiULUgtqC60FrgIvCZcESwalBqwG1gpdBZ0ETQoWDZUNqgW1BdoCWwmtBJUFygbkBuoK9QS2AlYJqgpUC9IL2QXqAm0JrQSVCkoLpQuyBbUJ1gSXCkcFkwZJB1ULagVrCisFiwpGDaMNygXWCtsEawJLCaUKUgtpC3UFdgG3CFsCKwVlBbQF2gntBG0BtgimClINqQ3UBdoKWwmrBFMGKQdiB6kLsgW1ClUFJQuSDckO0gbpCmsFqwRVCikNVA2qDbUJugQ7CpsETQqqCtUK2gJdCV4ELgqaDFUNsga5BroEXQotBZUKUguoC7QLuQXaAloJSgukDdEO6AZqC20FNQWVBkoNqA3UDdoGWwWdAisGFQtKC5ULqgWuCi4JjwwnBZUGqgbWCl0FnQI=';\nlet UMALQURA_MONTHLENGTH: Uint16Array;\nlet UMALQURA_YEAR_START_TABLE: Uint32Array;\n\nfunction umalquraYearStart(year: number): number {\n return UMALQURA_START_DAYS + UMALQURA_YEAR_START_TABLE[year - UMALQURA_YEAR_START];\n}\n\nfunction umalquraMonthLength(year: number, month: number): number {\n let idx = (year - UMALQURA_YEAR_START);\n let mask = (0x01 << (11 - (month - 1)));\n if ((UMALQURA_MONTHLENGTH[idx] & mask) === 0) {\n return 29;\n } else {\n return 30;\n }\n}\n\nfunction umalquraMonthStart(year: number, month: number): number {\n let day = umalquraYearStart(year);\n for (let i = 1; i < month; i++) {\n day += umalquraMonthLength(year, i);\n }\n return day;\n}\n\nfunction umalquraYearLength(year: number): number {\n return UMALQURA_YEAR_START_TABLE[year + 1 - UMALQURA_YEAR_START] - UMALQURA_YEAR_START_TABLE[year - UMALQURA_YEAR_START];\n}\n\n/**\n * The Islamic calendar, also known as the \"Hijri\" calendar, is used throughout much of the Arab world.\n * The Umalqura variant is primarily used in Saudi Arabia. It is a lunar calendar, based on astronomical\n * calculations that predict the sighting of a crescent moon. Month and year lengths vary between years\n * depending on these calculations.\n * Learn more about the available Islamic calendars [here](https://cldr.unicode.org/development/development-process/design-proposals/islamic-calendar-types).\n */\nexport class IslamicUmalquraCalendar extends IslamicCivilCalendar {\n identifier = 'islamic-umalqura';\n\n constructor() {\n super();\n if (!UMALQURA_MONTHLENGTH) {\n UMALQURA_MONTHLENGTH = new Uint16Array(Uint8Array.from(atob(UMALQURA_DATA), c => c.charCodeAt(0)).buffer);\n }\n\n if (!UMALQURA_YEAR_START_TABLE) {\n UMALQURA_YEAR_START_TABLE = new Uint32Array(UMALQURA_YEAR_END - UMALQURA_YEAR_START + 1);\n\n let yearStart = 0;\n for (let year = UMALQURA_YEAR_START; year <= UMALQURA_YEAR_END; year++) {\n UMALQURA_YEAR_START_TABLE[year - UMALQURA_YEAR_START] = yearStart;\n for (let i = 1; i <= 12; i++) {\n yearStart += umalquraMonthLength(year, i);\n }\n }\n }\n }\n\n fromJulianDay(jd: number): CalendarDate {\n let days = jd - CIVIL_EPOC;\n let startDays = umalquraYearStart(UMALQURA_YEAR_START);\n let endDays = umalquraYearStart(UMALQURA_YEAR_END);\n if (days < startDays || days > endDays) {\n return super.fromJulianDay(jd);\n } else {\n let y = UMALQURA_YEAR_START - 1;\n let m = 1;\n let d = 1;\n while (d > 0) {\n y++;\n d = days - umalquraYearStart(y) + 1;\n let yearLength = umalquraYearLength(y);\n if (d === yearLength) {\n m = 12;\n break;\n } else if (d < yearLength) {\n let monthLength = umalquraMonthLength(y, m);\n m = 1;\n while (d > monthLength) {\n d -= monthLength;\n m++;\n monthLength = umalquraMonthLength(y, m);\n }\n break;\n }\n }\n\n return new CalendarDate(this, y, m, (days - umalquraMonthStart(y, m) + 1));\n }\n }\n\n toJulianDay(date: AnyCalendarDate): number {\n if (date.year < UMALQURA_YEAR_START || date.year > UMALQURA_YEAR_END) {\n return super.toJulianDay(date);\n }\n\n return CIVIL_EPOC + umalquraMonthStart(date.year, date.month) + (date.day - 1);\n }\n\n getDaysInMonth(date: AnyCalendarDate): number {\n if (date.year < UMALQURA_YEAR_START || date.year > UMALQURA_YEAR_END) {\n return super.getDaysInMonth(date);\n }\n\n return umalquraMonthLength(date.year, date.month);\n }\n\n getDaysInYear(date: AnyCalendarDate): number {\n if (date.year < UMALQURA_YEAR_START || date.year > UMALQURA_YEAR_END) {\n return super.getDaysInYear(date);\n }\n\n return umalquraYearLength(date.year);\n }\n}\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Portions of the code in this file are based on code from ICU.\n// Original licensing can be found in the NOTICE file in the root directory of this source tree.\n\nimport {AnyCalendarDate, Calendar} from '../types';\nimport {CalendarDate} from '../CalendarDate';\nimport {mod, Mutable} from '../utils';\n\nconst HEBREW_EPOCH = 347997;\n\n// Hebrew date calculations are performed in terms of days, hours, and\n// \"parts\" (or halakim), which are 1/1080 of an hour, or 3 1/3 seconds.\nconst HOUR_PARTS = 1080;\nconst DAY_PARTS = 24 * HOUR_PARTS;\n\n// An approximate value for the length of a lunar month.\n// It is used to calculate the approximate year and month of a given\n// absolute date.\nconst MONTH_DAYS = 29;\nconst MONTH_FRACT = 12 * HOUR_PARTS + 793;\nconst MONTH_PARTS = MONTH_DAYS * DAY_PARTS + MONTH_FRACT;\n\nfunction isLeapYear(year: number) {\n return mod(year * 7 + 1, 19) < 7;\n}\n\n// Test for delay of start of new year and to avoid\n// Sunday, Wednesday, and Friday as start of the new year.\nfunction hebrewDelay1(year: number) {\n let months = Math.floor((235 * year - 234) / 19);\n let parts = 12084 + 13753 * months;\n let day = months * 29 + Math.floor(parts / 25920);\n\n if (mod(3 * (day + 1), 7) < 3) {\n day += 1;\n }\n\n return day;\n}\n\n// Check for delay in start of new year due to length of adjacent years\nfunction hebrewDelay2(year: number) {\n let last = hebrewDelay1(year - 1);\n let present = hebrewDelay1(year);\n let next = hebrewDelay1(year + 1);\n\n if (next - present === 356) {\n return 2;\n }\n\n if (present - last === 382) {\n return 1;\n }\n\n return 0;\n}\n\nfunction startOfYear(year: number) {\n return hebrewDelay1(year) + hebrewDelay2(year);\n}\n\nfunction getDaysInYear(year: number) {\n return startOfYear(year + 1) - startOfYear(year);\n}\n\nfunction getYearType(year: number) {\n let yearLength = getDaysInYear(year);\n\n if (yearLength > 380) {\n yearLength -= 30; // Subtract length of leap month.\n }\n\n switch (yearLength) {\n case 353:\n return 0; // deficient\n case 354:\n return 1; // normal\n case 355:\n return 2; // complete\n }\n}\n\nfunction getDaysInMonth(year: number, month: number): number {\n // Normalize month numbers from 1 - 13, even on non-leap years\n if (month >= 6 && !isLeapYear(year)) {\n month++;\n }\n\n // First of all, dispose of fixed-length 29 day months\n if (month === 4 || month === 7 || month === 9 || month === 11 || month === 13) {\n return 29;\n }\n\n let yearType = getYearType(year);\n\n // If it's Heshvan, days depend on length of year\n if (month === 2) {\n return yearType === 2 ? 30 : 29;\n }\n\n // Similarly, Kislev varies with the length of year\n if (month === 3) {\n return yearType === 0 ? 29 : 30;\n }\n\n // Adar I only exists in leap years\n if (month === 6) {\n return isLeapYear(year) ? 30 : 0;\n }\n\n return 30;\n}\n\n/**\n * The Hebrew calendar is used in Israel and around the world by the Jewish faith.\n * Years include either 12 or 13 months depending on whether it is a leap year.\n * In leap years, an extra month is inserted at month 6.\n */\nexport class HebrewCalendar implements Calendar {\n identifier = 'hebrew';\n\n fromJulianDay(jd: number): CalendarDate {\n let d = jd - HEBREW_EPOCH;\n let m = (d * DAY_PARTS) / MONTH_PARTS; // Months (approx)\n let year = Math.floor((19 * m + 234) / 235) + 1; // Years (approx)\n let ys = startOfYear(year); // 1st day of year\n let dayOfYear = Math.floor(d - ys);\n\n // Because of the postponement rules, it's possible to guess wrong. Fix it.\n while (dayOfYear < 1) {\n year--;\n ys = startOfYear(year);\n dayOfYear = Math.floor(d - ys);\n }\n\n // Now figure out which month we're in, and the date within that month\n let month = 1;\n let monthStart = 0;\n while (monthStart < dayOfYear) {\n monthStart += getDaysInMonth(year, month);\n month++;\n }\n\n month--;\n monthStart -= getDaysInMonth(year, month);\n\n let day = dayOfYear - monthStart;\n return new CalendarDate(this, year, month, day);\n }\n\n toJulianDay(date: AnyCalendarDate) {\n let jd = startOfYear(date.year);\n for (let month = 1; month < date.month; month++) {\n jd += getDaysInMonth(date.year, month);\n }\n\n return jd + date.day + HEBREW_EPOCH;\n }\n\n getDaysInMonth(date: AnyCalendarDate): number {\n return getDaysInMonth(date.year, date.month);\n }\n\n getMonthsInYear(date: AnyCalendarDate): number {\n return isLeapYear(date.year) ? 13 : 12;\n }\n\n getDaysInYear(date: AnyCalendarDate): number {\n return getDaysInYear(date.year);\n }\n\n getYearsInEra(): number {\n // 6239 gregorian\n return 9999;\n }\n\n getEras() {\n return ['AM'];\n }\n\n balanceYearMonth(date: Mutable<AnyCalendarDate>, previousDate: AnyCalendarDate) {\n // Keep date in the same month when switching between leap years and non leap years\n if (previousDate.year !== date.year) {\n if (isLeapYear(previousDate.year) && !isLeapYear(date.year) && previousDate.month > 6) {\n date.month--;\n } else if (!isLeapYear(previousDate.year) && isLeapYear(date.year) && previousDate.month > 6) {\n date.month++;\n }\n }\n }\n}\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Portions of the code in this file are based on code from ICU.\n// Original licensing can be found in the NOTICE file in the root directory of this source tree.\n\nimport {AnyCalendarDate, Calendar} from '../types';\nimport {CalendarDate} from '../CalendarDate';\nimport {Mutable} from '../utils';\n\nconst ETHIOPIC_EPOCH = 1723856;\nconst COPTIC_EPOCH = 1824665;\n\n// The delta between Amete Alem 1 and Amete Mihret 1\n// AA 5501 = AM 1\nconst AMETE_MIHRET_DELTA = 5500;\n\nfunction ceToJulianDay(epoch: number, year: number, month: number, day: number): number {\n return (\n epoch // difference from Julian epoch to 1,1,1\n + 365 * year // number of days from years\n + Math.floor(year / 4) // extra day of leap year\n + 30 * (month - 1) // number of days from months (1 based)\n + day - 1 // number of days for present month (1 based)\n );\n}\n\nfunction julianDayToCE(epoch: number, jd: number) {\n let year = Math.floor((4 * (jd - epoch)) / 1461);\n let month = 1 + Math.floor((jd - ceToJulianDay(epoch, year, 1, 1)) / 30);\n let day = jd + 1 - ceToJulianDay(epoch, year, month, 1);\n return [year, month, day];\n}\n\nfunction getLeapDay(year: number) {\n return Math.floor((year % 4) / 3);\n}\n\nfunction getDaysInMonth(year: number, month: number) {\n // The Ethiopian and Coptic calendars have 13 months, 12 of 30 days each and\n // an intercalary month at the end of the year of 5 or 6 days, depending whether\n // the year is a leap year or not. The Leap Year follows the same rules as the\n // Julian Calendar so that the extra month always has six days in the year before\n // a Julian Leap Year.\n if (month % 13 !== 0) {\n // not intercalary month\n return 30;\n } else {\n // intercalary month 5 days + possible leap day\n return getLeapDay(year) + 5;\n }\n}\n\n/**\n * The Ethiopic calendar system is the official calendar used in Ethiopia.\n * It includes 12 months of 30 days each, plus 5 or 6 intercalary days depending\n * on whether it is a leap year. Two eras are supported: 'AA' and 'AM'.\n */\nexport class EthiopicCalendar implements Calendar {\n identifier = 'ethiopic';\n\n fromJulianDay(jd: number): CalendarDate {\n let [year, month, day] = julianDayToCE(ETHIOPIC_EPOCH, jd);\n let era = 'AM';\n if (year <= 0) {\n era = 'AA';\n year += AMETE_MIHRET_DELTA;\n }\n\n return new CalendarDate(this, era, year, month, day);\n }\n\n toJulianDay(date: AnyCalendarDate) {\n let year = date.year;\n if (date.era === 'AA') {\n year -= AMETE_MIHRET_DELTA;\n }\n\n return ceToJulianDay(ETHIOPIC_EPOCH, year, date.month, date.day);\n }\n\n getDaysInMonth(date: AnyCalendarDate): number {\n return getDaysInMonth(date.year, date.month);\n }\n\n getMonthsInYear(): number {\n return 13;\n }\n\n getDaysInYear(date: AnyCalendarDate): number {\n return 365 + getLeapDay(date.year);\n }\n\n getYearsInEra(date: AnyCalendarDate): number {\n // 9999-12-31 gregorian is 9992-20-02 ethiopic.\n // Round down to 9991 for the last full year.\n // AA 9999-01-01 ethiopic is 4506-09-30 gregorian.\n return date.era === 'AA' ? 9999 : 9991;\n }\n\n getEras() {\n return ['AA', 'AM'];\n }\n}\n\n/**\n * The Ethiopic (Amete Alem) calendar is the same as the modern Ethiopic calendar,\n * except years were measured from a different epoch. Only one era is supported: 'AA'.\n */\nexport class EthiopicAmeteAlemCalendar extends EthiopicCalendar {\n identifier = 'ethioaa'; // also known as 'ethiopic-amete-alem' in ICU\n\n fromJulianDay(jd: number): CalendarDate {\n let [year, month, day] = julianDayToCE(ETHIOPIC_EPOCH, jd);\n year += AMETE_MIHRET_DELTA;\n return new CalendarDate(this, 'AA', year, month, day);\n }\n\n getEras() {\n return ['AA'];\n }\n\n getYearsInEra(): number {\n // 9999-13-04 ethioaa is the maximum date, which is equivalent to 4506-09-29 gregorian.\n return 9999;\n }\n}\n\n/**\n * The Coptic calendar is similar to the Ethiopic calendar.\n * It includes 12 months of 30 days each, plus 5 or 6 intercalary days depending\n * on whether it is a leap year. Two eras are supported: 'BCE' and 'CE'.\n */\nexport class CopticCalendar extends EthiopicCalendar {\n identifier = 'coptic';\n\n fromJulianDay(jd: number): CalendarDate {\n let [year, month, day] = julianDayToCE(COPTIC_EPOCH, jd);\n let era = 'CE';\n if (year <= 0) {\n era = 'BCE';\n year = 1 - year;\n }\n\n return new CalendarDate(this, era, year, month, day);\n }\n\n toJulianDay(date: AnyCalendarDate) {\n let year = date.year;\n if (date.era === 'BCE') {\n year = 1 - year;\n }\n\n return ceToJulianDay(COPTIC_EPOCH, year, date.month, date.day);\n }\n\n getDaysInMonth(date: AnyCalendarDate): number {\n let year = date.year;\n if (date.era === 'BCE') {\n year = 1 - year;\n }\n\n return getDaysInMonth(year, date.month);\n }\n\n isInverseEra(date: AnyCalendarDate): boolean {\n return date.era === 'BCE';\n }\n\n balanceDate(date: Mutable<AnyCalendarDate>) {\n if (date.year <= 0) {\n date.era = date.era === 'BCE' ? 'CE' : 'BCE';\n date.year = 1 - date.year;\n }\n }\n\n getEras() {\n return ['BCE', 'CE'];\n }\n\n getYearsInEra(date: AnyCalendarDate): number {\n // 9999-12-30 gregorian is 9716-02-20 coptic.\n // Round down to 9715 for the last full year.\n // BCE 9999-01-01 coptic is BC 9716-06-15 gregorian.\n return date.era === 'BCE' ? 9999 : 9715;\n }\n}\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {BuddhistCalendar} from './calendars/BuddhistCalendar';\nimport {Calendar} from './types';\nimport {CopticCalendar, EthiopicAmeteAlemCalendar, EthiopicCalendar} from './calendars/EthiopicCalendar';\nimport {GregorianCalendar} from './calendars/GregorianCalendar';\nimport {HebrewCalendar} from './calendars/HebrewCalendar';\nimport {IndianCalendar} from './calendars/IndianCalendar';\nimport {IslamicCivilCalendar, IslamicTabularCalendar, IslamicUmalquraCalendar} from './calendars/IslamicCalendar';\nimport {JapaneseCalendar} from './calendars/JapaneseCalendar';\nimport {PersianCalendar} from './calendars/PersianCalendar';\nimport {TaiwanCalendar} from './calendars/TaiwanCalendar';\n\n/** Creates a `Calendar` instance from a Unicode calendar identifier string. */\nexport function createCalendar(name: string): Calendar {\n switch (name) {\n case 'buddhist':\n return new BuddhistCalendar();\n case 'ethiopic':\n return new EthiopicCalendar();\n case 'ethioaa':\n return new EthiopicAmeteAlemCalendar();\n case 'coptic':\n return new CopticCalendar();\n case 'hebrew':\n return new HebrewCalendar();\n case 'indian':\n return new IndianCalendar();\n case 'islamic-civil':\n return new IslamicCivilCalendar();\n case 'islamic-tbla':\n return new IslamicTabularCalendar();\n case 'islamic-umalqura':\n return new IslamicUmalquraCalendar();\n case 'japanese':\n return new JapaneseCalendar();\n case 'persian':\n return new PersianCalendar();\n case 'roc':\n return new TaiwanCalendar();\n case 'gregory':\n default:\n return new GregorianCalendar();\n }\n}\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nlet formatterCache = new Map<string, Intl.DateTimeFormat>();\n\ninterface ResolvedDateTimeFormatOptions extends Intl.ResolvedDateTimeFormatOptions {\n hourCycle?: Intl.DateTimeFormatOptions['hourCycle']\n}\n\ninterface DateRangeFormatPart extends Intl.DateTimeFormatPart {\n source: 'startRange' | 'endRange' | 'shared'\n}\n\n/** A wrapper around Intl.DateTimeFormat that fixes various browser bugs, and polyfills new features. */\nexport class DateFormatter implements Intl.DateTimeFormat {\n private formatter: Intl.DateTimeFormat;\n private options: Intl.DateTimeFormatOptions;\n private resolvedHourCycle: Intl.DateTimeFormatOptions['hourCycle'];\n\n constructor(locale: string, options: Intl.DateTimeFormatOptions = {}) {\n this.formatter = getCachedDateFormatter(locale, options);\n this.options = options;\n }\n\n /** Formats a date as a string according to the locale and format options passed to the constructor. */\n format(value: Date): string {\n return this.formatter.format(value);\n }\n\n /** Formats a date to an array of parts such as separators, numbers, punctuation, and more. */\n formatToParts(value: Date): Intl.DateTimeFormatPart[] {\n return this.formatter.formatToParts(value);\n }\n\n /** Formats a date range as a string. */\n formatRange(start: Date, end: Date): string {\n // @ts-ignore\n if (typeof this.formatter.formatRange === 'function') {\n // @ts-ignore\n return this.formatter.formatRange(start, end);\n }\n\n if (end < start) {\n throw new RangeError('End date must be >= start date');\n }\n\n // Very basic fallback for old browsers.\n return `${this.formatter.format(start)} – ${this.formatter.format(end)}`;\n }\n\n /** Formats a date range as an array of parts. */\n formatRangeToParts(start: Date, end: Date): DateRangeFormatPart[] {\n // @ts-ignore\n if (typeof this.formatter.formatRangeToParts === 'function') {\n // @ts-ignore\n return this.formatter.formatRangeToParts(start, end);\n }\n\n if (end < start) {\n throw new RangeError('End date must be >= start date');\n }\n\n let startParts = this.formatter.formatToParts(start);\n let endParts = this.formatter.formatToParts(end);\n return [\n ...startParts.map(p => ({...p, source: 'startRange'} as DateRangeFormatPart)),\n {type: 'literal', value: ' – ', source: 'shared'},\n ...endParts.map(p => ({...p, source: 'endRange'} as DateRangeFormatPart))\n ];\n }\n\n /** Returns the resolved formatting options based on the values passed to the constructor. */\n resolvedOptions(): ResolvedDateTimeFormatOptions {\n let resolvedOptions = this.formatter.resolvedOptions() as ResolvedDateTimeFormatOptions;\n if (hasBuggyResolvedHourCycle()) {\n if (!this.resolvedHourCycle) {\n this.resolvedHourCycle = getResolvedHourCycle(resolvedOptions.locale, this.options);\n }\n resolvedOptions.hourCycle = this.resolvedHourCycle;\n resolvedOptions.hour12 = this.resolvedHourCycle === 'h11' || this.resolvedHourCycle === 'h12';\n }\n\n // Safari uses a different name for the Ethiopic (Amete Alem) calendar.\n // https://bugs.webkit.org/show_bug.cgi?id=241564\n if (resolvedOptions.calendar === 'ethiopic-amete-alem') {\n resolvedOptions.calendar = 'ethioaa';\n }\n\n return resolvedOptions;\n }\n}\n\n// There are multiple bugs involving the hour12 and hourCycle options in various browser engines.\n// - Chrome [1] (and the ECMA 402 spec [2]) resolve hour12: false in English and other locales to h24 (24:00 - 23:59)\n// rather than h23 (00:00 - 23:59). Same can happen with hour12: true in French, which Chrome resolves to h11 (00:00 - 11:59)\n// rather than h12 (12:00 - 11:59).\n// - WebKit returns an incorrect hourCycle resolved option in the French locale due to incorrect parsing of 'h' literal\n// in the resolved pattern. It also formats incorrectly when specifying the hourCycle option for the same reason. [3]\n// [1] https://bugs.chromium.org/p/chromium/issues/detail?id=1045791\n// [2] https://github.com/tc39/ecma402/issues/402\n// [3] https://bugs.webkit.org/show_bug.cgi?id=229313\n\n// https://github.com/unicode-org/cldr/blob/018b55eff7ceb389c7e3fc44e2f657eae3b10b38/common/supplemental/supplementalData.xml#L4774-L4802\nconst hour12Preferences = {\n true: {\n // Only Japanese uses the h11 style for 12 hour time. All others use h12.\n ja: 'h11'\n },\n false: {\n // All locales use h23 for 24 hour time. None use h24.\n }\n};\n\nfunction getCachedDateFormatter(locale: string, options: Intl.DateTimeFormatOptions = {}): Intl.DateTimeFormat {\n // Work around buggy hour12 behavior in Chrome / ECMA 402 spec by using hourCycle instead.\n // Only apply the workaround if the issue is detected, because the hourCycle option is buggy in Safari.\n if (typeof options.hour12 === 'boolean' && hasBuggyHour12Behavior()) {\n options = {...options};\n let pref = hour12Preferences[String(options.hour12)][locale.split('-')[0]];\n let defaultHourCycle = options.hour12 ? 'h12' : 'h23';\n options.hourCycle = pref ?? defaultHourCycle;\n delete options.hour12;\n }\n\n let cacheKey = locale + (options ? Object.entries(options).sort((a, b) => a[0] < b[0] ? -1 : 1).join() : '');\n if (formatterCache.has(cacheKey)) {\n return formatterCache.get(cacheKey);\n }\n\n let numberFormatter = new Intl.DateTimeFormat(locale, options);\n formatterCache.set(cacheKey, numberFormatter);\n return numberFormatter;\n}\n\nlet _hasBuggyHour12Behavior: boolean = null;\nfunction hasBuggyHour12Behavior() {\n if (_hasBuggyHour12Behavior == null) {\n _hasBuggyHour12Behavior = new Intl.DateTimeFormat('en-US', {\n hour: 'numeric',\n hour12: false\n }).format(new Date(2020, 2, 3, 0)) === '24';\n }\n\n return _hasBuggyHour12Behavior;\n}\n\nlet _hasBuggyResolvedHourCycle: boolean = null;\nfunction hasBuggyResolvedHourCycle() {\n if (_hasBuggyResolvedHourCycle == null) {\n _hasBuggyResolvedHourCycle = (new Intl.DateTimeFormat('fr', {\n hour: 'numeric',\n hour12: false\n }).resolvedOptions() as ResolvedDateTimeFormatOptions).hourCycle === 'h12';\n }\n\n return _hasBuggyResolvedHourCycle;\n}\n\nfunction getResolvedHourCycle(locale: string, options: Intl.DateTimeFormatOptions) {\n if (!options.timeStyle && !options.hour) {\n return undefined;\n }\n\n // Work around buggy results in resolved hourCycle and hour12 options in WebKit.\n // Format the minimum possible hour and maximum possible hour in a day and parse the results.\n locale = locale.replace(/(-u-)?-nu-[a-zA-Z0-9]+/, '');\n locale += (locale.includes('-u-') ? '' : '-u') + '-nu-latn';\n let formatter = getCachedDateFormatter(locale, {\n ...options,\n timeZone: undefined // use local timezone\n });\n\n let min = parseInt(formatter.formatToParts(new Date(2020, 2, 3, 0)).find(p => p.type === 'hour').value, 10);\n let max = parseInt(formatter.formatToParts(new Date(2020, 2, 3, 23)).find(p => p.type === 'hour').value, 10);\n\n if (min === 0 && max === 23) {\n return 'h23';\n }\n\n if (min === 24 && max === 23) {\n return 'h24';\n }\n\n if (min === 0 && max === 11) {\n return 'h11';\n }\n\n if (min === 12 && max === 11) {\n return 'h12';\n }\n\n throw new Error('Unexpected hour cycle result');\n}\n", "import {\n ColumnDescriptorsByName,\n FilterClause,\n FilterClauseOp,\n} from \"@vuu-ui/vuu-filter-types\";\nimport { ColumnDescriptor } from \"@vuu-ui/vuu-table-types\";\nimport {\n isMultiValueFilter,\n isSingleValueFilter,\n isValidFilterClauseOp,\n} from \"@vuu-ui/vuu-utils\";\n\nimport { SingleSelectionHandler } from \"@vuu-ui/vuu-ui-controls\";\nimport {\n KeyboardEvent,\n KeyboardEventHandler,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\n\nconst cursorAtTextStart = (input: HTMLInputElement) =>\n input.selectionStart === 0;\n\nconst cursorAtTextEnd = (input: HTMLInputElement) =>\n input.selectionStart === input.value.length;\n\nconst getFieldName = (field: HTMLElement) =>\n field?.classList.contains(\"vuuFilterClauseColumn\")\n ? \"column\"\n : field?.classList.contains(\"vuuFilterClauseOperator\")\n ? \"operator\"\n : \"value\";\n\nconst getFocusedField = () => {\n const activeElement = document.activeElement;\n if (activeElement?.classList.contains(\"vuuFilterClause-clearButton\")) {\n return activeElement;\n } else {\n return activeElement?.closest(\".vuuFilterClauseField\") as HTMLElement;\n }\n};\n\nconst focusNextFocusableElement = (direction: \"fwd\" | \"bwd\" = \"fwd\") => {\n const activeField = getFocusedField();\n const filterClause = activeField?.closest(\".vuuFilterClause\");\n if (direction === \"fwd\" && filterClause?.lastChild === activeField) {\n requestAnimationFrame(() => {\n focusNextFocusableElement();\n });\n } else {\n const nextField =\n direction === \"fwd\"\n ? (activeField?.nextElementSibling as HTMLElement)\n : (activeField?.previousElementSibling as HTMLElement);\n\n nextField?.querySelector(\"input\")?.focus();\n }\n};\n\nconst clauseIsNotFirst = (el: HTMLElement) => {\n const clause = el.closest(\"[data-index]\") as HTMLElement;\n if (clause) {\n const index = clause.dataset.index;\n const previousClause = clause?.parentElement?.querySelector(\n `[data-index]:has(.vuuFilterClause):has(+[data-index=\"${index}\"])`\n );\n return previousClause !== null;\n }\n};\n\nconst focusNextElement = () => {\n const filterClauseField = getFocusedField();\n const filterClause = filterClauseField?.closest(\".vuuFilterClause\");\n if (filterClause && filterClauseField) {\n if (filterClauseField.classList.contains(\"vuuFilterClauseValue\")) {\n const clearButton = filterClause.querySelector(\n \".vuuFilterClause-clearButton\"\n ) as HTMLButtonElement;\n clearButton?.focus();\n } else {\n focusNextFocusableElement();\n }\n }\n};\n\n// The logic around preventDefault/stopPragagation is important\n// in this function\nconst navigateToNextInputIfAtBoundary = (\n evt: KeyboardEvent<HTMLInputElement>\n) => {\n const input = evt.target as HTMLInputElement;\n const cursorAtStart = cursorAtTextStart(input);\n const cursorAtEnd = cursorAtTextEnd(input);\n const field = input.closest(\".vuuFilterClauseField\") as HTMLElement;\n if (evt.key === \"ArrowLeft\") {\n if (cursorAtStart) {\n const fieldName = getFieldName(field);\n if (fieldName === \"column\") {\n // Do not preventDefault, stopPropagation\n return;\n } else {\n const nextField = field.previousSibling as HTMLElement;\n const nextInput = nextField?.querySelector(\"input\");\n evt.preventDefault();\n\n nextInput?.focus();\n requestAnimationFrame(() => {\n nextInput?.select();\n });\n }\n }\n // stopPropagation, even if cursor is not at start. We want the arrowLeft to move the cursor\n evt.stopPropagation();\n } else if (evt.key === \"ArrowRight\") {\n if (cursorAtEnd) {\n const fieldName = getFieldName(field);\n if (fieldName === \"value\") {\n // Do not preventDefault, stopPropagation\n return;\n } else {\n const nextField = field.nextSibling as HTMLElement;\n const nextInput = nextField?.querySelector(\"input\");\n evt.preventDefault();\n nextInput?.focus();\n requestAnimationFrame(() => {\n nextInput?.select();\n });\n }\n }\n // stopPropagation, even if cursor is not at end. We want the arrowRight to move the cursor\n evt.stopPropagation();\n }\n};\n\n// TODO boolean[] makes no sense\ntype FilterClauseValue =\n | boolean\n | boolean[]\n | string\n | string[]\n | number\n | number[];\n\nconst getFilterClauseValue = (\n filterClause: Partial<FilterClause>\n): FilterClauseValue | undefined => {\n if (isMultiValueFilter(filterClause)) {\n return filterClause.values;\n } else if (isSingleValueFilter(filterClause)) {\n return filterClause.value;\n } else {\n return undefined;\n }\n};\n\nexport type FilterClauseCancelType = \"Backspace\";\nexport type FilterClauseCancelHandler = (\n reason: FilterClauseCancelType\n) => void;\nexport interface FilterClauseEditorHookProps {\n columnsByName: ColumnDescriptorsByName;\n filterClause: Partial<FilterClause>;\n onCancel?: FilterClauseCancelHandler;\n onChange: (filterClause: Partial<FilterClause>) => void;\n}\n\nexport const useFilterClauseEditor = ({\n filterClause,\n onCancel,\n onChange,\n columnsByName,\n}: FilterClauseEditorHookProps) => {\n const columnRef = useRef<HTMLDivElement>(null);\n const operatorRef = useRef<HTMLDivElement>(null);\n\n const [selectedColumn, setSelectedColumn] = useState<\n ColumnDescriptor | undefined\n >(filterClause.column ? columnsByName[filterClause.column] : undefined);\n const [operator, _setOperator] = useState<FilterClauseOp | undefined>(\n filterClause.op\n );\n\n const setOperator = useCallback((op) => {\n _setOperator(op);\n }, []);\n\n const [value, setValue] = useState<FilterClauseValue | undefined>(\n getFilterClauseValue(filterClause)\n );\n\n const handleColumnSelect = useCallback<\n SingleSelectionHandler<ColumnDescriptor>\n >(\n (_, column) => {\n setSelectedColumn(column ?? undefined);\n setOperator(undefined);\n setValue(undefined);\n setTimeout(() => {\n focusNextElement();\n }, 100);\n },\n [setOperator]\n );\n\n const removeAndNavigateToNextInputIfAtBoundary = useCallback(\n (evt) => {\n const input = evt.target as HTMLInputElement;\n if (input.value === \"\") {\n const field = input.closest(\n \".vuuFilterClauseField,[data-field]\"\n ) as HTMLElement;\n switch (field?.dataset?.field) {\n case \"operator\": {\n setOperator(undefined);\n setSelectedColumn(undefined);\n focusNextFocusableElement(\"bwd\");\n break;\n }\n case \"value\": {\n setOperator(undefined);\n focusNextFocusableElement(\"bwd\");\n break;\n }\n case \"column\": {\n if (clauseIsNotFirst(input)) {\n console.log(\"This is NOT the first clause\");\n onCancel?.(\"Backspace\");\n }\n }\n }\n }\n },\n [onCancel, setOperator]\n );\n\n const handleOperatorSelect = useCallback<SingleSelectionHandler>(\n (_, selected) => {\n const op = selected;\n if (op === undefined || isValidFilterClauseOp(op)) {\n setOperator(op);\n focusNextElement();\n } else {\n throw Error(\n `FilterClauseEditor, invalid value ${op} for filter clause`\n );\n }\n },\n [setOperator]\n );\n\n const handleChangeValue = useCallback(\n (value: string | string[] | number | number[]) => {\n setValue(value);\n if (value !== null && value !== \"\") {\n if (Array.isArray(value)) {\n onChange({\n column: selectedColumn?.name,\n op: operator,\n values: value,\n });\n } else {\n onChange({\n column: selectedColumn?.name,\n op: operator,\n value,\n });\n }\n }\n },\n [onChange, operator, selectedColumn?.name]\n );\n\n const handleDeselectValue = useCallback(() => {\n setValue(undefined);\n }, []);\n\n const handleKeyDownCaptureInput = useCallback(\n (evt: KeyboardEvent<HTMLInputElement>) => {\n if ([\"ArrowLeft\", \"ArrowRight\"].includes(evt.key)) {\n navigateToNextInputIfAtBoundary(evt);\n } else if (evt.key === \"Backspace\") {\n removeAndNavigateToNextInputIfAtBoundary(evt);\n }\n },\n [removeAndNavigateToNextInputIfAtBoundary]\n );\n\n const handleClear = useCallback(\n (e) => {\n const button = e.target as HTMLButtonElement;\n const firstInput = button\n .closest(\".vuuFilterClause\")\n ?.querySelector(\"input\") as HTMLInputElement;\n\n setSelectedColumn(undefined);\n setOperator(undefined);\n setValue(undefined);\n\n setTimeout(() => {\n firstInput.select();\n firstInput?.focus();\n }, 100);\n },\n [setOperator]\n );\n\n const handleClearKeyDown = useCallback<KeyboardEventHandler>((e) => {\n e.stopPropagation();\n if (e.key === \"Backspace\") {\n focusNextFocusableElement(\"bwd\");\n }\n }, []);\n\n const InputProps = useMemo(\n () => ({\n inputProps: {\n onKeyDownCapture: handleKeyDownCaptureInput,\n },\n }),\n [handleKeyDownCaptureInput]\n );\n\n useEffect(() => {\n const columnInput = columnRef.current?.querySelector(\"input\");\n columnInput?.focus();\n }, []);\n\n return {\n InputProps,\n columnRef,\n onChangeValue: handleChangeValue,\n onClear: handleClear,\n onClearKeyDown: handleClearKeyDown,\n onDeselectValue: handleDeselectValue,\n onColumnSelect: handleColumnSelect,\n onOperatorSelect: handleOperatorSelect,\n operator,\n operatorRef,\n selectedColumn,\n value,\n };\n};\n", "import { MenuActionHandler } from \"@vuu-ui/vuu-data-types\";\nimport { ColumnDescriptorsByName, Filter } from \"@vuu-ui/vuu-filter-types\";\nimport { PopupCloseCallback, Tooltip, useTooltip } from \"@vuu-ui/vuu-popups\";\nimport { EditableLabel, EditableLabelProps } from \"@vuu-ui/vuu-ui-controls\";\nimport { useId } from \"@vuu-ui/vuu-utils\";\nimport cx from \"clsx\";\nimport { HTMLAttributes, useCallback, useMemo, useRef } from \"react\";\nimport { FilterPillMenu } from \"../filter-pill-menu\";\nimport { filterAsReactNode } from \"./filterAsReactNode\";\n\nimport \"./FilterPill.css\";\nimport { getFilterLabel } from \"./getFilterLabel\";\n\nconst classBase = \"vuuFilterPill\";\n\nexport interface FilterPillProps\n extends Pick<Partial<EditableLabelProps>, \"onExitEditMode\">,\n HTMLAttributes<HTMLDivElement> {\n columnsByName?: ColumnDescriptorsByName;\n editable?: boolean;\n filter: Filter;\n index?: number;\n onBeginEdit?: (filter: Filter) => void;\n onMenuAction?: MenuActionHandler;\n showMenu?: boolean;\n}\n\nexport const FilterPill = ({\n className: classNameProp,\n columnsByName,\n editable = true,\n filter,\n id: idProp,\n onBeginEdit,\n onExitEditMode,\n onMenuAction,\n showMenu = true,\n ...htmlAttributes\n}: FilterPillProps) => {\n const rootRef = useRef<HTMLDivElement>(null);\n const handleEnterEditMode: EditableLabelProps[\"onEnterEditMode\"] =\n useCallback(() => {\n onBeginEdit?.(filter);\n }, [filter, onBeginEdit]);\n\n const getLabel = getFilterLabel(columnsByName);\n const label = useMemo(\n () => filter.name ?? getLabel(filter),\n [getLabel, filter]\n );\n\n const id = useId(idProp);\n\n const handleMenuClose = useCallback<PopupCloseCallback>((reason) => {\n if (reason?.type === \"escape\") {\n requestAnimationFrame(() => {\n if (rootRef.current) {\n rootRef.current.focus();\n }\n });\n }\n }, []);\n\n // Experiment, to be revisited\n // const tooltipBackground = useRef<string | undefined>();\n // useLayoutEffect(() => {\n // if (rootRef.current) {\n // tooltipBackground.current = getComputedStyle(\n // rootRef.current\n // ).getPropertyValue(\"--vuuTooltip-background\");\n // }\n // }, []);\n\n const { anchorProps, tooltipProps } = useTooltip({\n id,\n placement: \"below\",\n tooltipContent: filterAsReactNode(filter, getLabel),\n });\n\n return (\n <div\n {...anchorProps}\n {...htmlAttributes}\n className={cx(classBase, classNameProp)}\n data-text={label}\n ref={rootRef}\n >\n {editable && onExitEditMode ? (\n <EditableLabel\n defaultValue={label}\n key={label}\n onEnterEditMode={handleEnterEditMode}\n onExitEditMode={onExitEditMode}\n />\n ) : (\n <span className={`${classBase}-label`}>{label}</span>\n )}\n {showMenu && onMenuAction ? (\n <FilterPillMenu\n filter={filter}\n onMenuAction={onMenuAction}\n onMenuClose={handleMenuClose}\n />\n ) : null}\n {tooltipProps && <Tooltip {...tooltipProps} />}\n </div>\n );\n};\n", "import { PopupMenu } from \"@vuu-ui/vuu-popups\";\nimport {\n ContextMenuItemDescriptor,\n MenuActionHandler,\n MenuBuilder,\n} from \"@vuu-ui/vuu-data-types\";\nimport { useMemo } from \"react\";\nimport cx from \"clsx\";\n\nimport \"./FilterPillMenu.css\";\nimport {\n closeCommand,\n deleteCommand,\n editCommand,\n MenuOptions,\n renameCommand,\n} from \"./FilterPillMenuOptions\";\nimport { Filter } from \"@vuu-ui/vuu-filter-types\";\n\nconst classBase = \"vuuFilterPillMenu\";\n\nexport interface FilterMenuOptions extends MenuOptions {\n filter: Filter;\n}\n\nexport interface FilterPillMenuProps {\n allowClose?: boolean;\n allowDelete?: boolean;\n allowEdit?: boolean;\n allowRename?: boolean;\n filter: Filter;\n location?: string;\n onMenuAction: MenuActionHandler;\n onMenuClose?: () => void;\n}\n\nexport const FilterPillMenu = ({\n allowClose = true,\n allowDelete = true,\n allowEdit = true,\n allowRename = true,\n filter,\n location,\n onMenuAction,\n onMenuClose,\n}: FilterPillMenuProps) => {\n const [menuBuilder, menuOptions] = useMemo(\n (): [MenuBuilder, FilterMenuOptions] => [\n (_location, options) => {\n const menuItems: ContextMenuItemDescriptor[] = [];\n if (allowRename) {\n menuItems.push(renameCommand(options as MenuOptions));\n }\n if (allowEdit) {\n menuItems.push(editCommand(options as MenuOptions));\n }\n if (allowClose) {\n menuItems.push(closeCommand(options as MenuOptions));\n }\n if (allowDelete) {\n menuItems.push(deleteCommand(options as MenuOptions));\n }\n return menuItems;\n },\n {\n filter,\n },\n ],\n [allowClose, allowDelete, allowEdit, allowRename, filter]\n );\n\n return (\n <PopupMenu\n className={classBase}\n menuBuilder={menuBuilder}\n menuActionHandler={onMenuAction}\n menuLocation={cx(\"filter\", location)}\n menuOptions={menuOptions}\n onMenuClose={onMenuClose}\n tabIndex={-1}\n />\n );\n};\n", "import { ContextMenuItemDescriptor } from \"@vuu-ui/vuu-data-types\";\n\nexport type MenuOptions = { [key: string]: unknown };\n\nexport interface FilterPillMenuOptions {\n tabIndex: number;\n}\n\nexport const isFilterPillMenuOptions = (\n options: unknown\n): options is FilterPillMenuOptions =>\n typeof options === \"object\" && options !== null && \"filter\" in options;\n\nexport const closeCommand = (options?: MenuOptions) =>\n ({\n label: `Close`,\n location: \"filter\",\n action: `close-filter`,\n options,\n } as ContextMenuItemDescriptor);\n\nexport const deleteCommand = (options?: MenuOptions) =>\n ({\n label: `Delete`,\n location: \"filter\",\n action: `delete-filter`,\n options,\n } as ContextMenuItemDescriptor);\n\nexport const renameCommand = (options?: MenuOptions) =>\n ({\n label: `Rename`,\n location: \"filter\",\n action: `rename-filter`,\n options,\n } as ContextMenuItemDescriptor);\n\nexport const editCommand = (options?: MenuOptions) =>\n ({\n label: `Edit`,\n location: \"filter\",\n action: \"edit-filter\",\n options,\n } as ContextMenuItemDescriptor);\n", "import { isMultiClauseFilter, isMultiValueFilter } from \"@vuu-ui/vuu-utils\";\nimport { Filter } from \"@vuu-ui/vuu-filter-types\";\nimport { ReactNode } from \"react\";\nimport { getFilterLabel } from \"./getFilterLabel\";\n\nexport const filterAsReactNode = (\n f: Filter,\n getLabel: (f: Filter) => string = getFilterLabel()\n): ReactNode => {\n if (isMultiClauseFilter(f)) {\n const heading = f.op === \"and\" ? \"Match all ...\" : \"Match any ...\";\n return (\n <ul>\n <span>{heading}</span>\n {f.filters.map((f, i) => (\n <li key={i}>{filterAsReactNode(f, getLabel)}</li>\n ))}\n </ul>\n );\n } else if (isMultiValueFilter(f)) {\n if (f.values.length > 3) {\n const values = f.values.slice(0, 3);\n return `${getLabel({ ...f, values }).slice(0, -1)},...]`;\n } else {\n return getLabel(f);\n }\n } else {\n return getLabel(f);\n }\n};\n", "import {\n ColumnDescriptorsByName,\n Filter,\n FilterClause,\n MultiValueFilterClause,\n SingleValueFilterClause,\n} from \"@vuu-ui/vuu-filter-types\";\nimport {\n filterAsQuery,\n formatDate,\n isDateTimeColumn,\n isMultiClauseFilter,\n dateTimePattern,\n defaultPatternsByType,\n} from \"@vuu-ui/vuu-utils\";\nimport { filterClauses } from \"../filter-utils\";\n\nfunction applyFormatter<T>(\n filter: SingleValueFilterClause<T> | MultiValueFilterClause<T[]>,\n formatter: (t: T) => string\n): FilterClause {\n if (\"value\" in filter) {\n return { ...filter, value: formatter(filter.value) };\n } else {\n return { ...filter, values: filter.values.map(formatter) };\n }\n}\n\nfunction formatFilterValue(\n filter: FilterClause,\n columnsByName?: ColumnDescriptorsByName\n): FilterClause {\n const column = columnsByName?.[filter.column];\n if (column && isDateTimeColumn(column)) {\n const pattern = dateTimePattern(column.type);\n const formatter = (n: number) =>\n formatDate({ date: pattern.date ?? defaultPatternsByType.date })(\n new Date(n)\n );\n return applyFormatter(\n filter as\n | SingleValueFilterClause<number>\n | MultiValueFilterClause<number[]>,\n formatter\n );\n }\n\n return filter;\n}\n\nexport const getFilterLabel =\n (columnsByName?: ColumnDescriptorsByName) => (filter: Filter) => {\n if (isMultiClauseFilter(filter)) {\n const [firstClause] = filterClauses(filter);\n const formattedFilter = formatFilterValue(\n firstClause as FilterClause,\n columnsByName\n );\n return `${filterAsQuery(formattedFilter)} ${filter.op} ...`;\n } else {\n return filterAsQuery(formatFilterValue(filter, columnsByName));\n }\n };\n", "import { ColumnDescriptor } from \"@vuu-ui/vuu-table-types\";\nimport {\n AndFilter,\n Filter,\n FilterClause,\n FilterCombinatorOp,\n FilterWithPartialClause,\n MultiClauseFilter,\n NumericFilterClauseOp,\n} from \"@vuu-ui/vuu-filter-types\";\nimport {\n extractFilterForColumn,\n isAndFilter,\n isInFilter,\n isMultiClauseFilter,\n isMultiValueFilter,\n isNotNullOrUndefined,\n isOrFilter,\n isSingleValueFilter,\n partition,\n} from \"@vuu-ui/vuu-utils\";\n\nexport const AND = \"and\";\nexport const EQUALS = \"=\";\nexport const GREATER_THAN = \">\";\nexport const LESS_THAN = \"<\";\nexport const OR = \"or\";\nexport const STARTS_WITH = \"starts\";\nexport const ENDS_WITH = \"ends\";\nexport const IN = \"in\";\n\nexport type FilterType =\n | \"and\"\n | \"=\"\n | \">\"\n | \">=\"\n | \"in\"\n | \"<=\"\n | \"<\"\n | \"NOT_IN\"\n | \"NOT_SW\"\n | \"or\"\n | \"SW\";\n\nexport const filterClauses = (\n filter: Partial<Filter> | FilterWithPartialClause | null,\n clauses: Partial<FilterClause>[] = []\n): Partial<FilterClause>[] => {\n if (filter) {\n if (isMultiClauseFilter(filter)) {\n filter.filters.forEach((f) => clauses.push(...filterClauses(f)));\n } else {\n clauses.push(filter as Partial<FilterClause>);\n }\n }\n return clauses;\n};\n\ntype AddFilterOptions = {\n combineWith: FilterCombinatorOp;\n};\n\nconst DEFAULT_ADD_FILTER_OPTS: AddFilterOptions = {\n combineWith: \"and\",\n};\n\nexport const removeLastClause = (filter: MultiClauseFilter) => {\n const { filters } = filter;\n if (filters.length > 2) {\n return {\n ...filter,\n filters: filter.filters.slice(0, -1),\n };\n } else {\n // must be 2, we never have 1\n return filter.filters[0];\n }\n};\n\n/**\n Allows an empty FilterClause to be appended to an existing filter - for use\n in filter editing UI only.\n*/\nexport const addClause = (\n existingFilter: Filter,\n clause: Partial<Filter>,\n { combineWith = AND }: AddFilterOptions = DEFAULT_ADD_FILTER_OPTS\n): FilterWithPartialClause => {\n if (\n isMultiClauseFilter(existingFilter) &&\n existingFilter.op === combineWith\n ) {\n // if (isCompleteFilter(clause)) {\n return {\n ...existingFilter,\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n filters: existingFilter.filters.concat(clause),\n };\n // } else {\n // throw Error(\n // \"filter-utils, replaceFilter, only a valid clause can be added to a filter\"\n // );\n // }\n } else {\n return {\n op: combineWith,\n filters: [existingFilter, clause],\n };\n }\n};\n\nexport const replaceClause = (\n existingFilter: FilterWithPartialClause | Partial<Filter> | undefined,\n clause: Partial<FilterClause>,\n idx: number\n): Filter | Partial<Filter> => {\n if (existingFilter === undefined) return clause;\n return findAndReplaceClauseAtGivenIndex(existingFilter, clause, idx).filter;\n};\n\n/**\n * Given an existing filter and a filter clause, this function replaces the filter\n * clause at the given index `idx`.\n *\n * Indices are defined based on DepthFirstSearch.\n * (reason is that's what we use in `clauseFilters` when converting filter clauses into a flat list)\n *\n * Given a filter the indices are as follows [INDEX]:\n * {\n * op: and,\n * filters: [\n * {\n * op: or,\n * filters: [{op: =, column: currency, value: CAD} [0], {op: =, column: currency, value: USD} [1]]\n * },\n * {op: !=, column: bbg, value: AABC} [2]\n * ]\n * }\n *\n *\n * @param existingFilter - The existing filter\n * @param clause - Filter clause to replace with\n * @param idx - Index of filter clause to replace\n * @returns an object containing resulting filter\n */\nfunction findAndReplaceClauseAtGivenIndex(\n existingFilter: FilterWithPartialClause | Partial<Filter>,\n clause: Partial<FilterClause>,\n idx: number,\n currIdx = 0\n): { filter: Partial<Filter>; nextIdx: number } {\n if (isMultiClauseFilter(existingFilter)) {\n let i = currIdx;\n const filters = existingFilter.filters.map((f) => {\n const res = findAndReplaceClauseAtGivenIndex(f, clause, idx, i);\n i = res.nextIdx;\n return res.filter;\n }) as Filter[];\n return { filter: { ...existingFilter, filters }, nextIdx: i };\n } else if (idx !== currIdx) {\n return { filter: existingFilter as Partial<Filter>, nextIdx: currIdx + 1 };\n } else {\n const { name } = existingFilter;\n return {\n filter: { ...(isNotNullOrUndefined(name) ? { name } : {}), ...clause },\n nextIdx: currIdx + 1,\n };\n }\n}\n\nexport const addFilter = (\n existingFilter: Filter | undefined,\n filter: Filter,\n { combineWith = AND }: AddFilterOptions = DEFAULT_ADD_FILTER_OPTS\n): Filter | undefined => {\n if (includesNoValues(filter)) {\n if (isMultiClauseFilter(filter)) {\n // TODO identify the column that is contributing the no-values filter\n } else {\n existingFilter = removeFilterForColumn(existingFilter, {\n name: filter.column,\n });\n }\n } else if (includesAllValues(filter)) {\n if (isMultiClauseFilter(filter)) {\n // TODO identify the column that is contributing the all-values filter\n }\n return removeFilterForColumn(existingFilter, { name: filter.column ?? \"\" });\n }\n\n if (!existingFilter) {\n return filter;\n }\n if (!filter) {\n return existingFilter;\n }\n if (existingFilter.op === AND && filter.op === AND) {\n return {\n op: AND,\n filters: combine(existingFilter.filters, filter.filters),\n };\n }\n if (existingFilter.op === AND) {\n const filters = replaceOrInsert(existingFilter.filters, filter);\n return filters.length > 1 ? { op: AND, filters } : filters[0];\n }\n if (filter.op === AND) {\n return { op: AND, filters: filter.filters.concat(existingFilter) };\n }\n\n if (filterEquals(existingFilter, filter, true)) {\n return filter;\n }\n\n if (canMerge(existingFilter, filter)) {\n return merge(existingFilter, filter);\n }\n\n return { op: combineWith, filters: [existingFilter, filter] };\n};\n\nconst includesNoValues = (filter?: Filter | null): boolean => {\n if (!filter) {\n return false;\n }\n if (isInFilter(filter) && filter.values.length === 0) {\n return true;\n }\n return isAndFilter(filter) && filter.filters.some((f) => includesNoValues(f));\n};\n\ninterface CommonFilter {\n colName?: string;\n otherColFilters?: Filter[];\n mode?: any;\n value?: any;\n values?: any;\n op?: \"or\" | \"and\";\n column?: string;\n filters?: Filter[];\n}\n\nexport interface OtherFilter extends CommonFilter {\n type: FilterType;\n values?: any[];\n}\n\nconst includesAllValues = (filter?: Filter | null): boolean => {\n if (!filter) {\n return false;\n }\n if (filter.op === STARTS_WITH && filter.value === \"\") {\n return true;\n }\n return filter.op === STARTS_WITH && filter.value === \"\";\n};\n\nconst replaceOrInsert = (filters: Filter[], filter: Filter) => {\n return filters.concat(filter);\n};\n\nconst merge = (f1: Filter, f2: Filter): Filter | undefined => {\n if (includesNoValues(f2)) {\n return f2;\n }\n if (isInFilter(f1) && isInFilter(f2)) {\n return {\n ...f1,\n values: [\n ...f1.values,\n ...(f2.values as any[]).filter(\n (v: string | number) => !(f1.values as any[]).includes(v)\n ),\n ],\n };\n } else if (isInFilter(f1) && f2.op === EQUALS) {\n return {\n ...f1,\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n values: f1.values.concat([f2.value]),\n };\n } else if (f1.op === EQUALS && f2.op === EQUALS) {\n return {\n column: f1.column,\n op: IN,\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n values: [f1.value, f2.value],\n };\n }\n return f2;\n};\n\nconst combine = (existingFilters: Filter[], replacementFilters: Filter[]) => {\n const equivalentType = ({ op: op1 }: Filter, { op: op2 }: Filter) => {\n return (\n op1 === op2 ||\n (op1[0] === \">\" && op2[0] === \">\") ||\n (op1[0] === \"<\" && op2[0] === \"<\")\n );\n };\n const replaces = (existingFilter: Filter, replacementFilter: Filter) => {\n return (\n existingFilter.column === replacementFilter.column &&\n equivalentType(existingFilter, replacementFilter)\n );\n };\n const stillApplicable = (existingFilter: Filter) =>\n replacementFilters.some((replacementFilter) =>\n replaces(existingFilter, replacementFilter)\n ) === false;\n return existingFilters.filter(stillApplicable).concat(replacementFilters);\n};\n\nexport const removeFilter = (sourceFilter: Filter, filterToRemove: Filter) => {\n if (filterEquals(sourceFilter, filterToRemove, true)) {\n return null;\n }\n if (sourceFilter.op !== AND) {\n throw Error(\n `removeFilter cannot remove ${JSON.stringify(\n filterToRemove\n )} from ${JSON.stringify(sourceFilter)}`\n );\n }\n const filters = sourceFilter.filters.filter(\n (f) => !filterEquals(f, filterToRemove)\n );\n return filters.length > 0 ? { type: AND, filters } : null;\n};\n\nexport const splitFilterOnColumn = (\n columnName: string,\n filter?: Filter\n): [Filter | undefined, Filter | undefined] => {\n if (!filter) {\n return [undefined, undefined];\n }\n if (filter.column === columnName) {\n return [filter, undefined];\n }\n if (filter.op !== AND) {\n return [undefined, filter];\n }\n const [[columnFilter = undefined], filters] = partition(\n (filter as AndFilter).filters,\n (f) => f.column === columnName\n );\n return filters.length === 1\n ? [columnFilter, filters[0]]\n : [columnFilter, { op: AND, filters }];\n};\n\nexport const overrideColName = (filter: Filter, column: string): Filter => {\n if (isMultiClauseFilter(filter)) {\n return {\n op: filter.op,\n filters: filter.filters.map((f) => overrideColName(f, column)),\n };\n }\n return { ...filter, column };\n};\n\nexport const filterIncludesColumn = (\n filter: Filter,\n column: ColumnDescriptor\n): boolean => {\n if (!filter) {\n return false;\n }\n const { op, column: filterColName } = filter;\n switch (op) {\n case AND:\n case OR:\n return (\n filter.filters != null &&\n filter.filters.some((f) => filterIncludesColumn(f, column))\n );\n default:\n return filterColName === column.name;\n }\n};\n\nconst removeFilterForColumn = (\n sourceFilter: Filter | undefined,\n column: ColumnDescriptor\n): Filter | undefined => {\n const colName = column.name;\n if (!sourceFilter) {\n return undefined;\n }\n if (sourceFilter.column === colName) {\n return undefined;\n }\n if (isAndFilter(sourceFilter) || isOrFilter(sourceFilter)) {\n const { op } = sourceFilter;\n const filters = sourceFilter.filters;\n const otherColFilters = filters.filter((f) => f.column !== colName);\n switch (otherColFilters.length) {\n case 0:\n return undefined;\n case 1:\n return otherColFilters[0];\n default:\n return { op, filters: otherColFilters };\n }\n }\n return sourceFilter;\n};\n\nconst canMerge = (f1: Filter, f2: Filter) =>\n f1.column === f2.column &&\n (f1.op === \"=\" || f1.op === \"in\") &&\n (f2.op === \"=\" || f2.op === \"in\");\n\nconst sameValues = <T>(arr1: T[], arr2: T[]) => {\n if (arr1 === arr2) {\n return true;\n }\n if (arr1.length === arr2.length) {\n const a = arr1.slice().sort();\n const b = arr2.slice().sort();\n return a.join(\"|\") === b.join(\"|\");\n }\n return false;\n};\n\nexport const filterEquals = (f1?: Filter, f2?: Filter, strict = false) => {\n if (!strict) {\n return true;\n }\n if (f1 && f2 && canMerge(f1, f2)) {\n return (\n f1.op === f2.op &&\n ((isSingleValueFilter(f1) &&\n isSingleValueFilter(f2) &&\n f1.value === f2.value) ||\n (isMultiValueFilter(f1) &&\n isMultiValueFilter(f2) &&\n sameValues(f1.values as any[], f2.values)))\n );\n }\n return false;\n};\n\nexport const updateFilter = (\n filter: Filter | undefined,\n newFilter: Filter | undefined,\n mode: \"add\" | \"replace\"\n): Filter | undefined => {\n if (filter && newFilter) {\n if (mode === \"replace\") {\n return newFilter;\n }\n if (filter.op === \"and\") {\n return {\n ...filter,\n filters: filter.filters.concat(newFilter),\n };\n }\n const { column: columnName } = newFilter;\n if (columnName) {\n const existingClause = newFilter.column\n ? extractFilterForColumn(filter, columnName)\n : undefined;\n if (existingClause && columnName) {\n // The filter already contains a clause for this column, replace\n // with the new clause\n const result = removeFilterForColumn(filter, { name: columnName });\n return updateFilter(result, newFilter, \"add\");\n }\n }\n return {\n op: \"and\",\n filters: [filter, newFilter],\n };\n }\n if (newFilter) {\n return newFilter;\n }\n return filter;\n};\n\nexport const getTypeaheadFilter = (\n column: string,\n filterValues: string[],\n isStartsWithFilter?: boolean\n): Filter | undefined => {\n if (filterValues.length === 0) {\n return undefined;\n }\n\n if (isStartsWithFilter) {\n // multiple starts with filters not currently supported\n const startsWith = filterValues[0].substring(0, filterValues[0].length - 3);\n return {\n column,\n op: \"starts\",\n value: `\"${startsWith}\"`,\n };\n }\n\n return {\n column,\n op: \"in\",\n values: filterValues.map((value) => `\"${value}\"`),\n };\n};\n\nexport const getNumericFilter = (\n column: string,\n op?: NumericFilterClauseOp,\n value?: number\n): FilterClause | undefined => {\n if (op === undefined) return undefined;\n if (value === undefined || isNaN(value)) return undefined;\n return { column, op, value };\n};\n", "import { PopupMenu } from \"@vuu-ui/vuu-popups\";\n\nexport const FilterBarMenu = () => {\n const classBase = \"vuuFilterBarMenu\";\n return (\n <div className={classBase}>\n <PopupMenu icon=\"tune\" menuLocation=\"filter-bar-menu\" tabIndex={-1} />\n </div>\n );\n};\n", "import { MenuActionHandler } from \"@vuu-ui/vuu-data-types\";\nimport { ColumnDescriptor } from \"@vuu-ui/vuu-table-types\";\nimport {\n ColumnDescriptorsByName,\n Filter,\n FilterClause,\n FilterWithPartialClause,\n} from \"@vuu-ui/vuu-filter-types\";\nimport { PromptProps } from \"@vuu-ui/vuu-popups\";\nimport {\n EditableLabelProps,\n NavigationOutOfBoundsHandler,\n} from \"@vuu-ui/vuu-ui-controls\";\nimport { dispatchMouseEvent, isMultiClauseFilter } from \"@vuu-ui/vuu-utils\";\nimport {\n FocusEventHandler,\n KeyboardEvent,\n KeyboardEventHandler,\n RefObject,\n useCallback,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { FilterClauseCancelHandler } from \"../filter-clause/useFilterClauseEditor\";\nimport { FilterPillProps } from \"../filter-pill\";\nimport { FilterMenuOptions } from \"../filter-pill-menu\";\nimport { addClause, removeLastClause, replaceClause } from \"../filter-utils\";\nimport { FilterBarProps } from \"./FilterBar\";\nimport { useFilterState } from \"./useFilterState\";\nimport { useApplyFilterOnChange } from \"./useApplyFilterOnChange\";\n\nexport interface FilterBarHookProps\n extends Pick<\n FilterBarProps,\n | \"columnDescriptors\"\n | \"defaultFilterState\"\n | \"filterState\"\n | \"onApplyFilter\"\n | \"onFilterDeleted\"\n | \"onFilterRenamed\"\n | \"onFilterStateChanged\"\n | \"showMenu\"\n > {\n containerRef: RefObject<HTMLDivElement>;\n}\n\nconst EMPTY_FILTER_CLAUSE: Partial<Filter> = {};\n\nexport const useFilterBar = ({\n columnDescriptors,\n containerRef,\n defaultFilterState,\n filterState,\n onApplyFilter,\n onFilterDeleted,\n onFilterRenamed,\n onFilterStateChanged,\n showMenu: showMenuProp,\n}: FilterBarHookProps) => {\n const addButtonRef = useRef<HTMLButtonElement>(null);\n const editingFilter = useRef<Filter | undefined>();\n const [showMenu, setShowMenu] = useState(showMenuProp);\n const [editFilter, setEditFilter] = useState<\n Partial<Filter> | FilterWithPartialClause | undefined\n >();\n const [promptProps, setPromptProps] = useState<PromptProps | null>(null);\n\n const columnsByName = useMemo(\n () => columnDescriptorsByName(columnDescriptors),\n [columnDescriptors]\n );\n\n const {\n activeFilterIndex,\n filters,\n onAddFilter,\n onChangeFilter,\n onDeleteFilter,\n onRenameFilter,\n onChangeActiveFilterIndex,\n } = useFilterState({\n defaultFilterState,\n filterState,\n onFilterDeleted,\n onFilterRenamed,\n onFilterStateChanged,\n });\n\n useApplyFilterOnChange({\n activeFilterIndex,\n columnsByName,\n filters,\n onApplyFilter,\n });\n\n const editPillLabel = useCallback(\n (index: number) => {\n requestAnimationFrame(() => {\n const pills = containerRef.current?.querySelectorAll(\n \".vuuFilterPill\"\n ) as undefined | HTMLElement[];\n if (pills?.[index]) {\n const editableLabel = pills[index].querySelector(\n \".vuuEditableLabel\"\n ) as HTMLElement;\n if (editableLabel) {\n dispatchMouseEvent(editableLabel, \"dblclick\");\n }\n }\n });\n },\n [containerRef]\n );\n\n const focusFilterClause = useCallback(\n (_ = 0) => {\n requestAnimationFrame(() => {\n const input = containerRef.current?.querySelector(\n \".vuuFilterClause .saltInput-input\"\n ) as undefined | HTMLInputElement;\n if (input) {\n input.focus();\n }\n });\n },\n [containerRef]\n );\n\n const focusFilterPill = useCallback(\n (index?: number) => {\n requestAnimationFrame(() => {\n const target =\n typeof index === \"number\"\n ? (containerRef.current?.querySelector(\n `.vuuOverflowContainer-item[data-index=\"${index}\"] .vuuFilterPill`\n ) as undefined | HTMLInputElement)\n : (containerRef.current?.querySelector(\n \".vuuFilterPill[tabindex]\"\n ) as undefined | HTMLInputElement);\n if (target) {\n target.focus();\n }\n });\n },\n [containerRef]\n );\n\n const deleteConfirmed = useCallback(\n (filter: Filter) => {\n onDeleteFilter(filter);\n\n // TODO move focus to next/previous filter\n requestAnimationFrame(() => {\n if (filters.length) {\n focusFilterPill(0);\n }\n });\n },\n [filters.length, focusFilterPill, onDeleteFilter]\n );\n\n const getDeletePrompt = useMemo(\n () => (filter: Filter) => {\n const close = () => {\n setPromptProps(null);\n focusFilterPill();\n };\n return {\n confirmButtonLabel: \"Remove\",\n icon: \"warn-triangle\",\n onCancel: close,\n onClose: close,\n onConfirm: () => {\n setPromptProps(null);\n deleteConfirmed(filter);\n },\n text: `Are you sure you want to delete ${filter.name}`,\n title: \"Remove Filter\",\n variant: \"warn\",\n } as PromptProps;\n },\n [deleteConfirmed, focusFilterPill]\n );\n\n const deleteFilter = useCallback(\n (filter: Filter, withPrompt: boolean) => {\n if (withPrompt) {\n setPromptProps(getDeletePrompt(filter));\n } else {\n deleteConfirmed(filter);\n }\n },\n [deleteConfirmed, getDeletePrompt]\n );\n\n const handleBeginEditFilterName = useCallback((filter: Filter) => {\n editingFilter.current = filter;\n }, []);\n\n // TODO handle cancel edit name\n const handleExitEditFilterName: EditableLabelProps[\"onExitEditMode\"] =\n useCallback(\n (_, editedValue = \"\") => {\n if (editingFilter.current) {\n const indexOfEditedFilter = onRenameFilter(\n editingFilter.current,\n editedValue\n );\n editingFilter.current = undefined;\n focusFilterPill(indexOfEditedFilter);\n }\n },\n [focusFilterPill, onRenameFilter]\n );\n\n const handlePillMenuAction = useCallback<MenuActionHandler>(\n ({ menuId, options }) => {\n switch (menuId) {\n case \"delete-filter\": {\n const { filter } = options as FilterMenuOptions;\n deleteFilter(filter, true);\n return true;\n }\n case \"rename-filter\": {\n const { filter } = options as FilterMenuOptions;\n const index = filters.indexOf(filter);\n editPillLabel(index);\n return true;\n }\n case \"edit-filter\": {\n const { filter } = options as FilterMenuOptions;\n editingFilter.current = filter;\n setEditFilter(filter);\n focusFilterClause();\n return true;\n }\n default:\n return false;\n }\n },\n [deleteFilter, editPillLabel, filters, focusFilterClause]\n );\n\n const addIfNewElseUpdate = useCallback(\n (edited: Filter, existing: Filter | undefined) => {\n if (existing === undefined) {\n const idx = onAddFilter(edited);\n editPillLabel(idx);\n } else {\n onChangeFilter(existing, edited);\n }\n },\n [editPillLabel, onAddFilter, onChangeFilter]\n );\n\n const handleMenuAction = useCallback<MenuActionHandler>(\n ({ menuId }) => {\n switch (menuId) {\n case \"apply-save\": {\n const editedFilter = editFilter as Filter;\n addIfNewElseUpdate(editedFilter, editingFilter.current);\n setEditFilter(undefined);\n editingFilter.current = undefined;\n setShowMenu(false);\n return true;\n }\n case \"and-clause\": {\n const newFilter = addClause(\n editFilter as Filter,\n EMPTY_FILTER_CLAUSE\n );\n setEditFilter(newFilter);\n setShowMenu(false);\n return true;\n }\n case \"or-clause\":\n setEditFilter((filter) =>\n addClause(filter as Filter, EMPTY_FILTER_CLAUSE, {\n combineWith: \"or\",\n })\n );\n setShowMenu(false);\n return true;\n default:\n return false;\n }\n },\n [editFilter, addIfNewElseUpdate]\n );\n\n const handleClickAddFilter = useCallback(() => {\n setEditFilter({});\n }, [setEditFilter]);\n\n const handleClickRemoveFilter = useCallback(() => {\n setEditFilter(undefined);\n }, []);\n\n const pillProps: Partial<FilterPillProps> = {\n onBeginEdit: handleBeginEditFilterName,\n onMenuAction: handlePillMenuAction,\n onExitEditMode: handleExitEditFilterName,\n };\n\n const handleChangeFilterClause = useCallback(\n (idx: number) => (filterClause: Partial<FilterClause>) => {\n if (filterClause !== undefined) {\n setEditFilter((ef) => replaceClause(ef, filterClause, idx));\n setShowMenu(true);\n }\n },\n []\n );\n\n const handleCancelFilterClause = useCallback<FilterClauseCancelHandler>(\n (reason) => {\n if (reason === \"Backspace\" && isMultiClauseFilter(editFilter)) {\n setEditFilter(removeLastClause(editFilter));\n }\n },\n [editFilter]\n );\n\n const handleBlurFilterClause = useCallback<FocusEventHandler>((e) => {\n const target = e.target as HTMLElement;\n const relatedTarget = e.relatedTarget as HTMLElement;\n const filterClause = target.closest(\".vuuFilterClause\");\n if (filterClause?.contains(relatedTarget)) {\n // do nothing\n } else {\n const dropdownId = target.getAttribute(\"aria-owns\");\n const dropDown = dropdownId ? document.getElementById(dropdownId) : null;\n if (dropDown?.contains(relatedTarget)) {\n // do nothing\n } else {\n // if clause is complete\n setShowMenu(true);\n }\n }\n }, []);\n\n const handleFocusFilterClause = useCallback(() => {\n setShowMenu(false);\n }, []);\n\n const handleKeyDownFilterbar = useCallback(\n (evt: KeyboardEvent) => {\n if (evt.key === \"Escape\" && editFilter !== undefined) {\n // TODO confirm if edits applied ?\n setEditFilter(undefined);\n requestAnimationFrame(() => {\n // focus edited pill\n });\n }\n },\n [editFilter]\n );\n\n const handleKeyDownMenu = useCallback<KeyboardEventHandler>(\n (evt) => {\n const { current: container } = containerRef;\n if (evt.key === \"Backspace\" && container) {\n evt.preventDefault();\n const fields = Array.from(\n container.querySelectorAll(\".vuuFilterClauseField\")\n );\n if (fields.length > 0) {\n const field = fields.at(-1) as HTMLElement;\n field?.querySelector(\"input\")?.focus();\n }\n setShowMenu(false);\n } else if (evt.key === \"Tab\") {\n if (evt.shiftKey && container) {\n const clearButtons = Array.from(\n container.querySelectorAll(\".vuuFilterClause-clearButton\")\n ) as HTMLButtonElement[];\n if (clearButtons.length > 0) {\n const clearButton = clearButtons.at(-1) as HTMLButtonElement;\n setTimeout(() => {\n clearButton.focus();\n }, 100);\n }\n } else {\n console.log(\"apply current selection\");\n }\n }\n },\n [containerRef]\n );\n\n const handleAddButtonKeyDown = useCallback<KeyboardEventHandler>((evt) => {\n if (evt.key === \"ArrowLeft\") {\n console.log(\"navgiate to the Toolbar\");\n }\n }, []);\n\n const handlePillNavigationOutOfBounds =\n useCallback<NavigationOutOfBoundsHandler>((direction) => {\n if (direction === \"end\") {\n addButtonRef.current?.focus();\n }\n }, []);\n\n const addButtonProps = {\n ref: addButtonRef,\n onKeyDown: handleAddButtonKeyDown,\n };\n\n return {\n activeFilterIndex,\n addButtonProps,\n columnsByName,\n editFilter,\n filters,\n onBlurFilterClause: handleBlurFilterClause,\n onCancelFilterClause: handleCancelFilterClause,\n onChangeActiveFilterIndex,\n onClickAddFilter: handleClickAddFilter,\n onClickRemoveFilter: handleClickRemoveFilter,\n onChangeFilterClause: handleChangeFilterClause,\n onFocusFilterClause: handleFocusFilterClause,\n onKeyDownFilterbar: handleKeyDownFilterbar,\n onKeyDownMenu: handleKeyDownMenu,\n onMenuAction: handleMenuAction,\n onNavigateOutOfBounds: handlePillNavigationOutOfBounds,\n pillProps,\n promptProps,\n showMenu,\n };\n};\n\nfunction columnDescriptorsByName(\n columns: ColumnDescriptor[]\n): ColumnDescriptorsByName {\n return columns.reduce((m, col) => ({ ...m, [col.name]: col }), {});\n}\n", "import { useCallback } from \"react\";\nimport { Filter, FilterState } from \"@vuu-ui/vuu-filter-types\";\nimport { useControlled } from \"@vuu-ui/vuu-ui-controls\";\n\nexport interface FiltersHookProps {\n defaultFilterState?: FilterState;\n filterState?: FilterState;\n onFilterDeleted?: (filter: Filter) => void;\n onFilterRenamed?: (filter: Filter, name: string) => void;\n onFilterStateChanged?: (s: FilterState) => void;\n}\n\nexport const useFilterState = ({\n defaultFilterState,\n onFilterDeleted,\n onFilterRenamed,\n onFilterStateChanged,\n filterState: filterStateProp,\n}: FiltersHookProps) => {\n const [filterState, setFilterState] = useControlled<FilterState>({\n controlled: filterStateProp,\n default: defaultFilterState ?? { filters: [], activeIndices: [] },\n name: \"useFilterState\",\n state: \"FilterState\",\n });\n\n const handleFilterStateChange = useCallback(\n (s: FilterState) => {\n setFilterState(s);\n onFilterStateChanged?.(s);\n },\n [onFilterStateChanged, setFilterState]\n );\n\n const handleAddFilter = useCallback(\n (filter: Filter) => {\n const index = filterState.filters.length;\n const newFilters = filterState.filters.concat(filter);\n const newIndices = appendIfNotPresent(filterState.activeIndices, index);\n handleFilterStateChange({\n filters: newFilters,\n activeIndices: newIndices,\n });\n return index;\n },\n [filterState, handleFilterStateChange]\n );\n\n const handleDeleteFilter = useCallback(\n (filter: Filter) => {\n let index = -1;\n const newFilters = filterState.filters.filter((f, i) => {\n if (f !== filter) {\n return true;\n } else {\n index = i;\n return false;\n }\n });\n\n const newIndices = removeIndexAndDecrementLarger(\n filterState.activeIndices,\n index\n );\n\n handleFilterStateChange({\n filters: newFilters,\n activeIndices: newIndices,\n });\n onFilterDeleted?.(filter);\n return index;\n },\n [\n filterState.filters,\n filterState.activeIndices,\n handleFilterStateChange,\n onFilterDeleted,\n ]\n );\n\n const handleRenameFilter = useCallback(\n (filter: Filter, name: string) => {\n let index = -1;\n const newFilters = filterState.filters.map((f, i) => {\n if (f === filter) {\n index = i;\n return { ...filter, name };\n } else {\n return f;\n }\n });\n handleFilterStateChange({ ...filterState, filters: newFilters });\n onFilterRenamed?.(filter, name);\n\n return index;\n },\n [filterState, handleFilterStateChange, onFilterRenamed]\n );\n\n const handleChangeFilter = useCallback(\n (oldFilter: Filter, newFilter: Filter) => {\n let index = -1;\n const newFilters = filterState.filters.map((f, i) => {\n if (f === oldFilter) {\n index = i;\n return newFilter;\n } else {\n return f;\n }\n });\n handleFilterStateChange({ ...filterState, filters: newFilters });\n\n return index;\n },\n [filterState, handleFilterStateChange]\n );\n\n const handleActiveIndicesChange = useCallback(\n (indices: number[]) =>\n handleFilterStateChange({ ...filterState, activeIndices: indices }),\n [filterState, handleFilterStateChange]\n );\n\n return {\n activeFilterIndex: filterState.activeIndices,\n filters: filterState.filters,\n onChangeActiveFilterIndex: handleActiveIndicesChange,\n onAddFilter: handleAddFilter,\n onChangeFilter: handleChangeFilter,\n onDeleteFilter: handleDeleteFilter,\n onRenameFilter: handleRenameFilter,\n };\n};\n\nconst appendIfNotPresent = (ns: number[], n: number) =>\n ns.includes(n) ? ns : ns.concat(n);\n\nconst removeIndexAndDecrementLarger = (\n indices: number[],\n idxToRemove: number\n) => {\n return indices.reduce<number[]>((res, i) => {\n if (i === idxToRemove) return res;\n return res.concat(i > idxToRemove ? i - 1 : i);\n }, []);\n};\n", "import { useCallback, useEffect } from \"react\";\nimport {\n ColumnDescriptorsByName,\n Filter,\n FilterState,\n} from \"@vuu-ui/vuu-filter-types\";\nimport { DataSourceFilter } from \"@vuu-ui/vuu-data-types\";\nimport { filterAsQuery } from \"@vuu-ui/vuu-utils\";\n\ninterface ApplyFilterHookProps {\n activeFilterIndex: FilterState[\"activeIndices\"];\n columnsByName: ColumnDescriptorsByName;\n filters: FilterState[\"filters\"];\n onApplyFilter: (f: DataSourceFilter) => void;\n}\n\nexport function useApplyFilterOnChange({\n activeFilterIndex,\n columnsByName,\n filters,\n onApplyFilter,\n}: ApplyFilterHookProps) {\n const applyFilter = useCallback(\n (filter?: Filter) => {\n const query = filter ? filterAsQuery(filter, { columnsByName }) : \"\";\n onApplyFilter({ filter: query, filterStruct: filter });\n },\n [columnsByName, onApplyFilter]\n );\n\n useEffect(() => {\n const activeFilters = activeFilterIndex.map((i) => filters[i]);\n if (activeFilters.length === 0) {\n applyFilter();\n } else if (activeFilters.length === 1) {\n const [filter] = activeFilters;\n applyFilter(filter);\n } else {\n applyFilter({ op: \"and\", filters: activeFilters });\n }\n }, [activeFilterIndex, applyFilter, filters]);\n}\n", "import { Filter } from \"@vuu-ui/vuu-filter-types\";\nimport { Button } from \"@salt-ds/core\";\nimport { HTMLAttributes } from \"react\";\nimport {\n filterSubmissionHandler,\n SuggestionConsumer,\n useCodeMirrorEditor,\n} from \"./useCodeMirrorEditor\";\n\nimport \"./FilterInput.css\";\n\nconst classBase = \"vuuFilterInput\";\n\nexport interface FilterInputProps\n extends SuggestionConsumer,\n HTMLAttributes<HTMLDivElement> {\n iconName?: string;\n existingFilter?: Filter;\n namedFilters?: Map<string, string>;\n onSubmitFilter?: filterSubmissionHandler;\n}\n\nexport const FilterInput = ({\n existingFilter,\n iconName = \"filter\",\n namedFilters,\n onSubmitFilter,\n suggestionProvider,\n ...props\n}: FilterInputProps) => {\n const { editorRef, clearInput } = useCodeMirrorEditor({\n existingFilter,\n onSubmitFilter,\n suggestionProvider,\n });\n\n return (\n <div {...props} className={classBase}>\n <Button\n className={`${classBase}-FilterButton`}\n data-icon={iconName}\n tabIndex={-1}\n />\n <div className={`${classBase}-Editor`} ref={editorRef} />\n <Button\n className={`${classBase}-ClearButton`}\n data-icon=\"close-circle\"\n onClick={clearInput}\n />\n </div>\n );\n};\n", "import {\n autocompletion,\n Completion,\n defaultKeymap,\n EditorState,\n EditorView,\n ensureSyntaxTree,\n keymap,\n minimalSetup,\n startCompletion,\n VuuCompletion,\n} from \"@vuu-ui/vuu-codemirror\";\nimport { walkTree } from \"@vuu-ui/vuu-filter-parser\";\nimport { Filter } from \"@vuu-ui/vuu-filter-types\";\nimport cx from \"clsx\";\nimport { MutableRefObject, useEffect, useMemo, useRef } from \"react\";\nimport { filterLanguageSupport } from \"./FilterLanguage\";\nimport { vuuHighlighting } from \"./highlighting\";\nimport { vuuTheme } from \"./theme\";\nimport {\n ApplyCompletion,\n FilterSubmissionMode,\n useAutoComplete,\n} from \"./useFilterAutoComplete\";\nimport { FilterSaveOptions } from \"./useFilterSuggestionProvider\";\n\nexport type SuggestionType =\n | \"column\"\n | \"columnValue\"\n | \"operator\"\n | \"save\"\n | \"name\";\n\nexport interface FilterSuggestionOptions {\n quoted?: boolean;\n columnName?: string;\n existingFilter?: Filter;\n filterName?: string;\n onSubmit?: () => void;\n operator?: string;\n startsWith?: string;\n selection?: string[];\n}\n\nexport type getFilterSuggestionsType = (\n suggestionType: SuggestionType,\n options?: FilterSuggestionOptions\n) => Promise<Completion[]>;\n\nexport interface IFilterSuggestionProvider {\n getSuggestions: getFilterSuggestionsType;\n isPartialMatch: (\n valueType: SuggestionType,\n columnName?: string,\n text?: string | undefined\n ) => Promise<boolean>;\n}\n\nexport interface SuggestionConsumer {\n suggestionProvider: IFilterSuggestionProvider;\n}\n\nconst getView = (ref: MutableRefObject<EditorView | undefined>): EditorView => {\n if (ref.current == undefined) {\n throw Error(\"EditorView not defined\");\n }\n return ref.current;\n};\n\nconst getOptionClass = (completion: VuuCompletion) => {\n return cx(\"vuuSuggestion\", {\n vuuIllustration: completion.isIllustration,\n });\n};\n\nconst stripName = (filterQuery: string) => {\n const pos = filterQuery.lastIndexOf(\" as \");\n if (pos !== -1) {\n return filterQuery.slice(0, pos);\n } else {\n return filterQuery;\n }\n};\n\nconst noop = () => console.log(\"noooop\");\n\nexport type filterSubmissionHandler = (\n filter: Filter | undefined,\n filterQuery: string,\n mode?: FilterSubmissionMode,\n filterName?: string\n) => void;\n\nexport interface CodeMirrorEditorProps {\n existingFilter?: Filter;\n onSubmitFilter?: filterSubmissionHandler;\n saveOptions?: FilterSaveOptions;\n suggestionProvider: IFilterSuggestionProvider;\n}\n\nexport const useCodeMirrorEditor = ({\n existingFilter,\n onSubmitFilter,\n suggestionProvider,\n}: CodeMirrorEditorProps) => {\n const editorRef = useRef<HTMLDivElement>(null);\n const onSubmit = useRef<ApplyCompletion>(noop);\n const viewRef = useRef<EditorView>();\n const completionFn = useAutoComplete(\n suggestionProvider,\n onSubmit,\n existingFilter\n );\n\n const [createState, clearInput] = useMemo(() => {\n const parseFilter = ():\n | [Filter, string, string | undefined]\n | [undefined, \"\", undefined] => {\n const view = getView(viewRef);\n const source = view.state.doc.toString();\n const tree = ensureSyntaxTree(view.state, view.state.doc.length, 5000);\n if (tree) {\n const filter = walkTree(tree, source) as Filter;\n return [filter, stripName(source), filter.name];\n } else {\n return [undefined, \"\", undefined];\n }\n };\n\n const clearInput = () => {\n getView(viewRef).setState(createState());\n };\n\n const submitFilterAndClearInput = (mode?: FilterSubmissionMode) => {\n const [filter, filterQuery, filterName] = parseFilter();\n onSubmitFilter?.(filter, filterQuery, mode, filterName);\n clearInput();\n };\n\n const submitFilter = (key: string) => {\n return keymap.of([\n {\n key,\n run() {\n submitFilterAndClearInput();\n return true;\n },\n },\n ]);\n };\n\n const showSuggestions = (key: string) => {\n return keymap.of([\n {\n key,\n run() {\n startCompletion(getView(viewRef));\n return true;\n },\n },\n ]);\n };\n\n const createState = (): EditorState =>\n EditorState.create({\n doc: \"\",\n extensions: [\n minimalSetup,\n autocompletion({\n override: [completionFn],\n optionClass: getOptionClass,\n }),\n filterLanguageSupport(),\n keymap.of(defaultKeymap),\n submitFilter(\"Ctrl-Enter\"),\n showSuggestions(\"ArrowDown\"),\n EditorView.updateListener.of((v) => {\n const view = getView(viewRef);\n if (v.docChanged) {\n startCompletion(view);\n }\n }),\n EditorState.transactionFilter.of((tr) =>\n tr.newDoc.lines > 1 ? [] : tr\n ),\n vuuTheme,\n vuuHighlighting,\n ],\n });\n\n onSubmit.current = (mode?: FilterSubmissionMode) => {\n submitFilterAndClearInput(mode);\n // TODO refocu sthe editor\n setTimeout(() => {\n getView(viewRef).focus();\n }, 100);\n };\n\n return [createState, clearInput];\n }, [completionFn, onSubmitFilter]);\n\n useEffect(() => {\n if (!editorRef.current) {\n throw Error(\"editor not in dom\");\n }\n\n viewRef.current = new EditorView({\n state: createState(),\n parent: editorRef.current,\n });\n\n return () => {\n viewRef.current?.destroy();\n };\n }, [completionFn, createState]);\n\n return { editorRef, clearInput };\n};\n", "// FIXME profile adding a per-Tree TreeNode cache, validating it by\n// parent pointer\n/// The default maximum length of a `TreeBuffer` node.\nconst DefaultBufferLength = 1024;\nlet nextPropID = 0;\nclass Range {\n constructor(from, to) {\n this.from = from;\n this.to = to;\n }\n}\n/// Each [node type](#common.NodeType) or [individual tree](#common.Tree)\n/// can have metadata associated with it in props. Instances of this\n/// class represent prop names.\nclass NodeProp {\n /// Create a new node prop type.\n constructor(config = {}) {\n this.id = nextPropID++;\n this.perNode = !!config.perNode;\n this.deserialize = config.deserialize || (() => {\n throw new Error(\"This node type doesn't define a deserialize function\");\n });\n }\n /// This is meant to be used with\n /// [`NodeSet.extend`](#common.NodeSet.extend) or\n /// [`LRParser.configure`](#lr.ParserConfig.props) to compute\n /// prop values for each node type in the set. Takes a [match\n /// object](#common.NodeType^match) or function that returns undefined\n /// if the node type doesn't get this prop, and the prop's value if\n /// it does.\n add(match) {\n if (this.perNode)\n throw new RangeError(\"Can't add per-node props to node types\");\n if (typeof match != \"function\")\n match = NodeType.match(match);\n return (type) => {\n let result = match(type);\n return result === undefined ? null : [this, result];\n };\n }\n}\n/// Prop that is used to describe matching delimiters. For opening\n/// delimiters, this holds an array of node names (written as a\n/// space-separated string when declaring this prop in a grammar)\n/// for the node types of closing delimiters that match it.\nNodeProp.closedBy = new NodeProp({ deserialize: str => str.split(\" \") });\n/// The inverse of [`closedBy`](#common.NodeProp^closedBy). This is\n/// attached to closing delimiters, holding an array of node names\n/// of types of matching opening delimiters.\nNodeProp.openedBy = new NodeProp({ deserialize: str => str.split(\" \") });\n/// Used to assign node types to groups (for example, all node\n/// types that represent an expression could be tagged with an\n/// `\"Expression\"` group).\nNodeProp.group = new NodeProp({ deserialize: str => str.split(\" \") });\n/// The hash of the [context](#lr.ContextTracker.constructor)\n/// that the node was parsed in, if any. Used to limit reuse of\n/// contextual nodes.\nNodeProp.contextHash = new NodeProp({ perNode: true });\n/// The distance beyond the end of the node that the tokenizer\n/// looked ahead for any of the tokens inside the node. (The LR\n/// parser only stores this when it is larger than 25, for\n/// efficiency reasons.)\nNodeProp.lookAhead = new NodeProp({ perNode: true });\n/// This per-node prop is used to replace a given node, or part of a\n/// node, with another tree. This is useful to include trees from\n/// different languages in mixed-language parsers.\nNodeProp.mounted = new NodeProp({ perNode: true });\n/// A mounted tree, which can be [stored](#common.NodeProp^mounted) on\n/// a tree node to indicate that parts of its content are\n/// represented by another tree.\nclass MountedTree {\n constructor(\n /// The inner tree.\n tree, \n /// If this is null, this tree replaces the entire node (it will\n /// be included in the regular iteration instead of its host\n /// node). If not, only the given ranges are considered to be\n /// covered by this tree. This is used for trees that are mixed in\n /// a way that isn't strictly hierarchical. Such mounted trees are\n /// only entered by [`resolveInner`](#common.Tree.resolveInner)\n /// and [`enter`](#common.SyntaxNode.enter).\n overlay, \n /// The parser used to create this subtree.\n parser) {\n this.tree = tree;\n this.overlay = overlay;\n this.parser = parser;\n }\n}\nconst noProps = Object.create(null);\n/// Each node in a syntax tree has a node type associated with it.\nclass NodeType {\n /// @internal\n constructor(\n /// The name of the node type. Not necessarily unique, but if the\n /// grammar was written properly, different node types with the\n /// same name within a node set should play the same semantic\n /// role.\n name, \n /// @internal\n props, \n /// The id of this node in its set. Corresponds to the term ids\n /// used in the parser.\n id, \n /// @internal\n flags = 0) {\n this.name = name;\n this.props = props;\n this.id = id;\n this.flags = flags;\n }\n /// Define a node type.\n static define(spec) {\n let props = spec.props && spec.props.length ? Object.create(null) : noProps;\n let flags = (spec.top ? 1 /* NodeFlag.Top */ : 0) | (spec.skipped ? 2 /* NodeFlag.Skipped */ : 0) |\n (spec.error ? 4 /* NodeFlag.Error */ : 0) | (spec.name == null ? 8 /* NodeFlag.Anonymous */ : 0);\n let type = new NodeType(spec.name || \"\", props, spec.id, flags);\n if (spec.props)\n for (let src of spec.props) {\n if (!Array.isArray(src))\n src = src(type);\n if (src) {\n if (src[0].perNode)\n throw new RangeError(\"Can't store a per-node prop on a node type\");\n props[src[0].id] = src[1];\n }\n }\n return type;\n }\n /// Retrieves a node prop for this type. Will return `undefined` if\n /// the prop isn't present on this node.\n prop(prop) { return this.props[prop.id]; }\n /// True when this is the top node of a grammar.\n get isTop() { return (this.flags & 1 /* NodeFlag.Top */) > 0; }\n /// True when this node is produced by a skip rule.\n get isSkipped() { return (this.flags & 2 /* NodeFlag.Skipped */) > 0; }\n /// Indicates whether this is an error node.\n get isError() { return (this.flags & 4 /* NodeFlag.Error */) > 0; }\n /// When true, this node type doesn't correspond to a user-declared\n /// named node, for example because it is used to cache repetition.\n get isAnonymous() { return (this.flags & 8 /* NodeFlag.Anonymous */) > 0; }\n /// Returns true when this node's name or one of its\n /// [groups](#common.NodeProp^group) matches the given string.\n is(name) {\n if (typeof name == 'string') {\n if (this.name == name)\n return true;\n let group = this.prop(NodeProp.group);\n return group ? group.indexOf(name) > -1 : false;\n }\n return this.id == name;\n }\n /// Create a function from node types to arbitrary values by\n /// specifying an object whose property names are node or\n /// [group](#common.NodeProp^group) names. Often useful with\n /// [`NodeProp.add`](#common.NodeProp.add). You can put multiple\n /// names, separated by spaces, in a single property name to map\n /// multiple node names to a single value.\n static match(map) {\n let direct = Object.create(null);\n for (let prop in map)\n for (let name of prop.split(\" \"))\n direct[name] = map[prop];\n return (node) => {\n for (let groups = node.prop(NodeProp.group), i = -1; i < (groups ? groups.length : 0); i++) {\n let found = direct[i < 0 ? node.name : groups[i]];\n if (found)\n return found;\n }\n };\n }\n}\n/// An empty dummy node type to use when no actual type is available.\nNodeType.none = new NodeType(\"\", Object.create(null), 0, 8 /* NodeFlag.Anonymous */);\n/// A node set holds a collection of node types. It is used to\n/// compactly represent trees by storing their type ids, rather than a\n/// full pointer to the type object, in a numeric array. Each parser\n/// [has](#lr.LRParser.nodeSet) a node set, and [tree\n/// buffers](#common.TreeBuffer) can only store collections of nodes\n/// from the same set. A set can have a maximum of 2**16 (65536) node\n/// types in it, so that the ids fit into 16-bit typed array slots.\nclass NodeSet {\n /// Create a set with the given types. The `id` property of each\n /// type should correspond to its position within the array.\n constructor(\n /// The node types in this set, by id.\n types) {\n this.types = types;\n for (let i = 0; i < types.length; i++)\n if (types[i].id != i)\n throw new RangeError(\"Node type ids should correspond to array positions when creating a node set\");\n }\n /// Create a copy of this set with some node properties added. The\n /// arguments to this method can be created with\n /// [`NodeProp.add`](#common.NodeProp.add).\n extend(...props) {\n let newTypes = [];\n for (let type of this.types) {\n let newProps = null;\n for (let source of props) {\n let add = source(type);\n if (add) {\n if (!newProps)\n newProps = Object.assign({}, type.props);\n newProps[add[0].id] = add[1];\n }\n }\n newTypes.push(newProps ? new NodeType(type.name, newProps, type.id, type.flags) : type);\n }\n return new NodeSet(newTypes);\n }\n}\nconst CachedNode = new WeakMap(), CachedInnerNode = new WeakMap();\n/// Options that control iteration. Can be combined with the `|`\n/// operator to enable multiple ones.\nvar IterMode;\n(function (IterMode) {\n /// When enabled, iteration will only visit [`Tree`](#common.Tree)\n /// objects, not nodes packed into\n /// [`TreeBuffer`](#common.TreeBuffer)s.\n IterMode[IterMode[\"ExcludeBuffers\"] = 1] = \"ExcludeBuffers\";\n /// Enable this to make iteration include anonymous nodes (such as\n /// the nodes that wrap repeated grammar constructs into a balanced\n /// tree).\n IterMode[IterMode[\"IncludeAnonymous\"] = 2] = \"IncludeAnonymous\";\n /// By default, regular [mounted](#common.NodeProp^mounted) nodes\n /// replace their base node in iteration. Enable this to ignore them\n /// instead.\n IterMode[IterMode[\"IgnoreMounts\"] = 4] = \"IgnoreMounts\";\n /// This option only applies in\n /// [`enter`](#common.SyntaxNode.enter)-style methods. It tells the\n /// library to not enter mounted overlays if one covers the given\n /// position.\n IterMode[IterMode[\"IgnoreOverlays\"] = 8] = \"IgnoreOverlays\";\n})(IterMode || (IterMode = {}));\n/// A piece of syntax tree. There are two ways to approach these\n/// trees: the way they are actually stored in memory, and the\n/// convenient way.\n///\n/// Syntax trees are stored as a tree of `Tree` and `TreeBuffer`\n/// objects. By packing detail information into `TreeBuffer` leaf\n/// nodes, the representation is made a lot more memory-efficient.\n///\n/// However, when you want to actually work with tree nodes, this\n/// representation is very awkward, so most client code will want to\n/// use the [`TreeCursor`](#common.TreeCursor) or\n/// [`SyntaxNode`](#common.SyntaxNode) interface instead, which provides\n/// a view on some part of this data structure, and can be used to\n/// move around to adjacent nodes.\nclass Tree {\n /// Construct a new tree. See also [`Tree.build`](#common.Tree^build).\n constructor(\n /// The type of the top node.\n type, \n /// This node's child nodes.\n children, \n /// The positions (offsets relative to the start of this tree) of\n /// the children.\n positions, \n /// The total length of this tree\n length, \n /// Per-node [node props](#common.NodeProp) to associate with this node.\n props) {\n this.type = type;\n this.children = children;\n this.positions = positions;\n this.length = length;\n /// @internal\n this.props = null;\n if (props && props.length) {\n this.props = Object.create(null);\n for (let [prop, value] of props)\n this.props[typeof prop == \"number\" ? prop : prop.id] = value;\n }\n }\n /// @internal\n toString() {\n let mounted = this.prop(NodeProp.mounted);\n if (mounted && !mounted.overlay)\n return mounted.tree.toString();\n let children = \"\";\n for (let ch of this.children) {\n let str = ch.toString();\n if (str) {\n if (children)\n children += \",\";\n children += str;\n }\n }\n return !this.type.name ? children :\n (/\\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) +\n (children.length ? \"(\" + children + \")\" : \"\");\n }\n /// Get a [tree cursor](#common.TreeCursor) positioned at the top of\n /// the tree. Mode can be used to [control](#common.IterMode) which\n /// nodes the cursor visits.\n cursor(mode = 0) {\n return new TreeCursor(this.topNode, mode);\n }\n /// Get a [tree cursor](#common.TreeCursor) pointing into this tree\n /// at the given position and side (see\n /// [`moveTo`](#common.TreeCursor.moveTo).\n cursorAt(pos, side = 0, mode = 0) {\n let scope = CachedNode.get(this) || this.topNode;\n let cursor = new TreeCursor(scope);\n cursor.moveTo(pos, side);\n CachedNode.set(this, cursor._tree);\n return cursor;\n }\n /// Get a [syntax node](#common.SyntaxNode) object for the top of the\n /// tree.\n get topNode() {\n return new TreeNode(this, 0, 0, null);\n }\n /// Get the [syntax node](#common.SyntaxNode) at the given position.\n /// If `side` is -1, this will move into nodes that end at the\n /// position. If 1, it'll move into nodes that start at the\n /// position. With 0, it'll only enter nodes that cover the position\n /// from both sides.\n ///\n /// Note that this will not enter\n /// [overlays](#common.MountedTree.overlay), and you often want\n /// [`resolveInner`](#common.Tree.resolveInner) instead.\n resolve(pos, side = 0) {\n let node = resolveNode(CachedNode.get(this) || this.topNode, pos, side, false);\n CachedNode.set(this, node);\n return node;\n }\n /// Like [`resolve`](#common.Tree.resolve), but will enter\n /// [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node\n /// pointing into the innermost overlaid tree at the given position\n /// (with parent links going through all parent structure, including\n /// the host trees).\n resolveInner(pos, side = 0) {\n let node = resolveNode(CachedInnerNode.get(this) || this.topNode, pos, side, true);\n CachedInnerNode.set(this, node);\n return node;\n }\n /// Iterate over the tree and its children, calling `enter` for any\n /// node that touches the `from`/`to` region (if given) before\n /// running over such a node's children, and `leave` (if given) when\n /// leaving the node. When `enter` returns `false`, that node will\n /// not have its children iterated over (or `leave` called).\n iterate(spec) {\n let { enter, leave, from = 0, to = this.length } = spec;\n let mode = spec.mode || 0, anon = (mode & IterMode.IncludeAnonymous) > 0;\n for (let c = this.cursor(mode | IterMode.IncludeAnonymous);;) {\n let entered = false;\n if (c.from <= to && c.to >= from && (!anon && c.type.isAnonymous || enter(c) !== false)) {\n if (c.firstChild())\n continue;\n entered = true;\n }\n for (;;) {\n if (entered && leave && (anon || !c.type.isAnonymous))\n leave(c);\n if (c.nextSibling())\n break;\n if (!c.parent())\n return;\n entered = true;\n }\n }\n }\n /// Get the value of the given [node prop](#common.NodeProp) for this\n /// node. Works with both per-node and per-type props.\n prop(prop) {\n return !prop.perNode ? this.type.prop(prop) : this.props ? this.props[prop.id] : undefined;\n }\n /// Returns the node's [per-node props](#common.NodeProp.perNode) in a\n /// format that can be passed to the [`Tree`](#common.Tree)\n /// constructor.\n get propValues() {\n let result = [];\n if (this.props)\n for (let id in this.props)\n result.push([+id, this.props[id]]);\n return result;\n }\n /// Balance the direct children of this tree, producing a copy of\n /// which may have children grouped into subtrees with type\n /// [`NodeType.none`](#common.NodeType^none).\n balance(config = {}) {\n return this.children.length <= 8 /* Balance.BranchFactor */ ? this :\n balanceRange(NodeType.none, this.children, this.positions, 0, this.children.length, 0, this.length, (children, positions, length) => new Tree(this.type, children, positions, length, this.propValues), config.makeTree || ((children, positions, length) => new Tree(NodeType.none, children, positions, length)));\n }\n /// Build a tree from a postfix-ordered buffer of node information,\n /// or a cursor over such a buffer.\n static build(data) { return buildTree(data); }\n}\n/// The empty tree\nTree.empty = new Tree(NodeType.none, [], [], 0);\nclass FlatBufferCursor {\n constructor(buffer, index) {\n this.buffer = buffer;\n this.index = index;\n }\n get id() { return this.buffer[this.index - 4]; }\n get start() { return this.buffer[this.index - 3]; }\n get end() { return this.buffer[this.index - 2]; }\n get size() { return this.buffer[this.index - 1]; }\n get pos() { return this.index; }\n next() { this.index -= 4; }\n fork() { return new FlatBufferCursor(this.buffer, this.index); }\n}\n/// Tree buffers contain (type, start, end, endIndex) quads for each\n/// node. In such a buffer, nodes are stored in prefix order (parents\n/// before children, with the endIndex of the parent indicating which\n/// children belong to it).\nclass TreeBuffer {\n /// Create a tree buffer.\n constructor(\n /// The buffer's content.\n buffer, \n /// The total length of the group of nodes in the buffer.\n length, \n /// The node set used in this buffer.\n set) {\n this.buffer = buffer;\n this.length = length;\n this.set = set;\n }\n /// @internal\n get type() { return NodeType.none; }\n /// @internal\n toString() {\n let result = [];\n for (let index = 0; index < this.buffer.length;) {\n result.push(this.childString(index));\n index = this.buffer[index + 3];\n }\n return result.join(\",\");\n }\n /// @internal\n childString(index) {\n let id = this.buffer[index], endIndex = this.buffer[index + 3];\n let type = this.set.types[id], result = type.name;\n if (/\\W/.test(result) && !type.isError)\n result = JSON.stringify(result);\n index += 4;\n if (endIndex == index)\n return result;\n let children = [];\n while (index < endIndex) {\n children.push(this.childString(index));\n index = this.buffer[index + 3];\n }\n return result + \"(\" + children.join(\",\") + \")\";\n }\n /// @internal\n findChild(startIndex, endIndex, dir, pos, side) {\n let { buffer } = this, pick = -1;\n for (let i = startIndex; i != endIndex; i = buffer[i + 3]) {\n if (checkSide(side, pos, buffer[i + 1], buffer[i + 2])) {\n pick = i;\n if (dir > 0)\n break;\n }\n }\n return pick;\n }\n /// @internal\n slice(startI, endI, from) {\n let b = this.buffer;\n let copy = new Uint16Array(endI - startI), len = 0;\n for (let i = startI, j = 0; i < endI;) {\n copy[j++] = b[i++];\n copy[j++] = b[i++] - from;\n let to = copy[j++] = b[i++] - from;\n copy[j++] = b[i++] - startI;\n len = Math.max(len, to);\n }\n return new TreeBuffer(copy, len, this.set);\n }\n}\nfunction checkSide(side, pos, from, to) {\n switch (side) {\n case -2 /* Side.Before */: return from < pos;\n case -1 /* Side.AtOrBefore */: return to >= pos && from < pos;\n case 0 /* Side.Around */: return from < pos && to > pos;\n case 1 /* Side.AtOrAfter */: return from <= pos && to > pos;\n case 2 /* Side.After */: return to > pos;\n case 4 /* Side.DontCare */: return true;\n }\n}\nfunction enterUnfinishedNodesBefore(node, pos) {\n let scan = node.childBefore(pos);\n while (scan) {\n let last = scan.lastChild;\n if (!last || last.to != scan.to)\n break;\n if (last.type.isError && last.from == last.to) {\n node = scan;\n scan = last.prevSibling;\n }\n else {\n scan = last;\n }\n }\n return node;\n}\nfunction resolveNode(node, pos, side, overlays) {\n var _a;\n // Move up to a node that actually holds the position, if possible\n while (node.from == node.to ||\n (side < 1 ? node.from >= pos : node.from > pos) ||\n (side > -1 ? node.to <= pos : node.to < pos)) {\n let parent = !overlays && node instanceof TreeNode && node.index < 0 ? null : node.parent;\n if (!parent)\n return node;\n node = parent;\n }\n let mode = overlays ? 0 : IterMode.IgnoreOverlays;\n // Must go up out of overlays when those do not overlap with pos\n if (overlays)\n for (let scan = node, parent = scan.parent; parent; scan = parent, parent = scan.parent) {\n if (scan instanceof TreeNode && scan.index < 0 && ((_a = parent.enter(pos, side, mode)) === null || _a === void 0 ? void 0 : _a.from) != scan.from)\n node = parent;\n }\n for (;;) {\n let inner = node.enter(pos, side, mode);\n if (!inner)\n return node;\n node = inner;\n }\n}\nclass TreeNode {\n constructor(_tree, from, \n // Index in parent node, set to -1 if the node is not a direct child of _parent.node (overlay)\n index, _parent) {\n this._tree = _tree;\n this.from = from;\n this.index = index;\n this._parent = _parent;\n }\n get type() { return this._tree.type; }\n get name() { return this._tree.type.name; }\n get to() { return this.from + this._tree.length; }\n nextChild(i, dir, pos, side, mode = 0) {\n for (let parent = this;;) {\n for (let { children, positions } = parent._tree, e = dir > 0 ? children.length : -1; i != e; i += dir) {\n let next = children[i], start = positions[i] + parent.from;\n if (!checkSide(side, pos, start, start + next.length))\n continue;\n if (next instanceof TreeBuffer) {\n if (mode & IterMode.ExcludeBuffers)\n continue;\n let index = next.findChild(0, next.buffer.length, dir, pos - start, side);\n if (index > -1)\n return new BufferNode(new BufferContext(parent, next, i, start), null, index);\n }\n else if ((mode & IterMode.IncludeAnonymous) || (!next.type.isAnonymous || hasChild(next))) {\n let mounted;\n if (!(mode & IterMode.IgnoreMounts) &&\n next.props && (mounted = next.prop(NodeProp.mounted)) && !mounted.overlay)\n return new TreeNode(mounted.tree, start, i, parent);\n let inner = new TreeNode(next, start, i, parent);\n return (mode & IterMode.IncludeAnonymous) || !inner.type.isAnonymous ? inner\n : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side);\n }\n }\n if ((mode & IterMode.IncludeAnonymous) || !parent.type.isAnonymous)\n return null;\n if (parent.index >= 0)\n i = parent.index + dir;\n else\n i = dir < 0 ? -1 : parent._parent._tree.children.length;\n parent = parent._parent;\n if (!parent)\n return null;\n }\n }\n get firstChild() { return this.nextChild(0, 1, 0, 4 /* Side.DontCare */); }\n get lastChild() { return this.nextChild(this._tree.children.length - 1, -1, 0, 4 /* Side.DontCare */); }\n childAfter(pos) { return this.nextChild(0, 1, pos, 2 /* Side.After */); }\n childBefore(pos) { return this.nextChild(this._tree.children.length - 1, -1, pos, -2 /* Side.Before */); }\n enter(pos, side, mode = 0) {\n let mounted;\n if (!(mode & IterMode.IgnoreOverlays) && (mounted = this._tree.prop(NodeProp.mounted)) && mounted.overlay) {\n let rPos = pos - this.from;\n for (let { from, to } of mounted.overlay) {\n if ((side > 0 ? from <= rPos : from < rPos) &&\n (side < 0 ? to >= rPos : to > rPos))\n return new TreeNode(mounted.tree, mounted.overlay[0].from + this.from, -1, this);\n }\n }\n return this.nextChild(0, 1, pos, side, mode);\n }\n nextSignificantParent() {\n let val = this;\n while (val.type.isAnonymous && val._parent)\n val = val._parent;\n return val;\n }\n get parent() {\n return this._parent ? this._parent.nextSignificantParent() : null;\n }\n get nextSibling() {\n return this._parent && this.index >= 0 ? this._parent.nextChild(this.index + 1, 1, 0, 4 /* Side.DontCare */) : null;\n }\n get prevSibling() {\n return this._parent && this.index >= 0 ? this._parent.nextChild(this.index - 1, -1, 0, 4 /* Side.DontCare */) : null;\n }\n cursor(mode = 0) { return new TreeCursor(this, mode); }\n get tree() { return this._tree; }\n toTree() { return this._tree; }\n resolve(pos, side = 0) {\n return resolveNode(this, pos, side, false);\n }\n resolveInner(pos, side = 0) {\n return resolveNode(this, pos, side, true);\n }\n enterUnfinishedNodesBefore(pos) { return enterUnfinishedNodesBefore(this, pos); }\n getChild(type, before = null, after = null) {\n let r = getChildren(this, type, before, after);\n return r.length ? r[0] : null;\n }\n getChildren(type, before = null, after = null) {\n return getChildren(this, type, before, after);\n }\n /// @internal\n toString() { return this._tree.toString(); }\n get node() { return this; }\n matchContext(context) { return matchNodeContext(this, context); }\n}\nfunction getChildren(node, type, before, after) {\n let cur = node.cursor(), result = [];\n if (!cur.firstChild())\n return result;\n if (before != null)\n while (!cur.type.is(before))\n if (!cur.nextSibling())\n return result;\n for (;;) {\n if (after != null && cur.type.is(after))\n return result;\n if (cur.type.is(type))\n result.push(cur.node);\n if (!cur.nextSibling())\n return after == null ? result : [];\n }\n}\nfunction matchNodeContext(node, context, i = context.length - 1) {\n for (let p = node.parent; i >= 0; p = p.parent) {\n if (!p)\n return false;\n if (!p.type.isAnonymous) {\n if (context[i] && context[i] != p.name)\n return false;\n i--;\n }\n }\n return true;\n}\nclass BufferContext {\n constructor(parent, buffer, index, start) {\n this.parent = parent;\n this.buffer = buffer;\n this.index = index;\n this.start = start;\n }\n}\nclass BufferNode {\n get name() { return this.type.name; }\n get from() { return this.context.start + this.context.buffer.buffer[this.index + 1]; }\n get to() { return this.context.start + this.context.buffer.buffer[this.index + 2]; }\n constructor(context, _parent, index) {\n this.context = context;\n this._parent = _parent;\n this.index = index;\n this.type = context.buffer.set.types[context.buffer.buffer[index]];\n }\n child(dir, pos, side) {\n let { buffer } = this.context;\n let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side);\n return index < 0 ? null : new BufferNode(this.context, this, index);\n }\n get firstChild() { return this.child(1, 0, 4 /* Side.DontCare */); }\n get lastChild() { return this.child(-1, 0, 4 /* Side.DontCare */); }\n childAfter(pos) { return this.child(1, pos, 2 /* Side.After */); }\n childBefore(pos) { return this.child(-1, pos, -2 /* Side.Before */); }\n enter(pos, side, mode = 0) {\n if (mode & IterMode.ExcludeBuffers)\n return null;\n let { buffer } = this.context;\n let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side);\n return index < 0 ? null : new BufferNode(this.context, this, index);\n }\n get parent() {\n return this._parent || this.context.parent.nextSignificantParent();\n }\n externalSibling(dir) {\n return this._parent ? null : this.context.parent.nextChild(this.context.index + dir, dir, 0, 4 /* Side.DontCare */);\n }\n get nextSibling() {\n let { buffer } = this.context;\n let after = buffer.buffer[this.index + 3];\n if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length))\n return new BufferNode(this.context, this._parent, after);\n return this.externalSibling(1);\n }\n get prevSibling() {\n let { buffer } = this.context;\n let parentStart = this._parent ? this._parent.index + 4 : 0;\n if (this.index == parentStart)\n return this.externalSibling(-1);\n return new BufferNode(this.context, this._parent, buffer.findChild(parentStart, this.index, -1, 0, 4 /* Side.DontCare */));\n }\n cursor(mode = 0) { return new TreeCursor(this, mode); }\n get tree() { return null; }\n toTree() {\n let children = [], positions = [];\n let { buffer } = this.context;\n let startI = this.index + 4, endI = buffer.buffer[this.index + 3];\n if (endI > startI) {\n let from = buffer.buffer[this.index + 1];\n children.push(buffer.slice(startI, endI, from));\n positions.push(0);\n }\n return new Tree(this.type, children, positions, this.to - this.from);\n }\n resolve(pos, side = 0) {\n return resolveNode(this, pos, side, false);\n }\n resolveInner(pos, side = 0) {\n return resolveNode(this, pos, side, true);\n }\n enterUnfinishedNodesBefore(pos) { return enterUnfinishedNodesBefore(this, pos); }\n /// @internal\n toString() { return this.context.buffer.childString(this.index); }\n getChild(type, before = null, after = null) {\n let r = getChildren(this, type, before, after);\n return r.length ? r[0] : null;\n }\n getChildren(type, before = null, after = null) {\n return getChildren(this, type, before, after);\n }\n get node() { return this; }\n matchContext(context) { return matchNodeContext(this, context); }\n}\n/// A tree cursor object focuses on a given node in a syntax tree, and\n/// allows you to move to adjacent nodes.\nclass TreeCursor {\n /// Shorthand for `.type.name`.\n get name() { return this.type.name; }\n /// @internal\n constructor(node, \n /// @internal\n mode = 0) {\n this.mode = mode;\n /// @internal\n this.buffer = null;\n this.stack = [];\n /// @internal\n this.index = 0;\n this.bufferNode = null;\n if (node instanceof TreeNode) {\n this.yieldNode(node);\n }\n else {\n this._tree = node.context.parent;\n this.buffer = node.context;\n for (let n = node._parent; n; n = n._parent)\n this.stack.unshift(n.index);\n this.bufferNode = node;\n this.yieldBuf(node.index);\n }\n }\n yieldNode(node) {\n if (!node)\n return false;\n this._tree = node;\n this.type = node.type;\n this.from = node.from;\n this.to = node.to;\n return true;\n }\n yieldBuf(index, type) {\n this.index = index;\n let { start, buffer } = this.buffer;\n this.type = type || buffer.set.types[buffer.buffer[index]];\n this.from = start + buffer.buffer[index + 1];\n this.to = start + buffer.buffer[index + 2];\n return true;\n }\n yield(node) {\n if (!node)\n return false;\n if (node instanceof TreeNode) {\n this.buffer = null;\n return this.yieldNode(node);\n }\n this.buffer = node.context;\n return this.yieldBuf(node.index, node.type);\n }\n /// @internal\n toString() {\n return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString();\n }\n /// @internal\n enterChild(dir, pos, side) {\n if (!this.buffer)\n return this.yield(this._tree.nextChild(dir < 0 ? this._tree._tree.children.length - 1 : 0, dir, pos, side, this.mode));\n let { buffer } = this.buffer;\n let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side);\n if (index < 0)\n return false;\n this.stack.push(this.index);\n return this.yieldBuf(index);\n }\n /// Move the cursor to this node's first child. When this returns\n /// false, the node has no child, and the cursor has not been moved.\n firstChild() { return this.enterChild(1, 0, 4 /* Side.DontCare */); }\n /// Move the cursor to this node's last child.\n lastChild() { return this.enterChild(-1, 0, 4 /* Side.DontCare */); }\n /// Move the cursor to the first child that ends after `pos`.\n childAfter(pos) { return this.enterChild(1, pos, 2 /* Side.After */); }\n /// Move to the last child that starts before `pos`.\n childBefore(pos) { return this.enterChild(-1, pos, -2 /* Side.Before */); }\n /// Move the cursor to the child around `pos`. If side is -1 the\n /// child may end at that position, when 1 it may start there. This\n /// will also enter [overlaid](#common.MountedTree.overlay)\n /// [mounted](#common.NodeProp^mounted) trees unless `overlays` is\n /// set to false.\n enter(pos, side, mode = this.mode) {\n if (!this.buffer)\n return this.yield(this._tree.enter(pos, side, mode));\n return mode & IterMode.ExcludeBuffers ? false : this.enterChild(1, pos, side);\n }\n /// Move to the node's parent node, if this isn't the top node.\n parent() {\n if (!this.buffer)\n return this.yieldNode((this.mode & IterMode.IncludeAnonymous) ? this._tree._parent : this._tree.parent);\n if (this.stack.length)\n return this.yieldBuf(this.stack.pop());\n let parent = (this.mode & IterMode.IncludeAnonymous) ? this.buffer.parent : this.buffer.parent.nextSignificantParent();\n this.buffer = null;\n return this.yieldNode(parent);\n }\n /// @internal\n sibling(dir) {\n if (!this.buffer)\n return !this._tree._parent ? false\n : this.yield(this._tree.index < 0 ? null\n : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4 /* Side.DontCare */, this.mode));\n let { buffer } = this.buffer, d = this.stack.length - 1;\n if (dir < 0) {\n let parentStart = d < 0 ? 0 : this.stack[d] + 4;\n if (this.index != parentStart)\n return this.yieldBuf(buffer.findChild(parentStart, this.index, -1, 0, 4 /* Side.DontCare */));\n }\n else {\n let after = buffer.buffer[this.index + 3];\n if (after < (d < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d] + 3]))\n return this.yieldBuf(after);\n }\n return d < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4 /* Side.DontCare */, this.mode)) : false;\n }\n /// Move to this node's next sibling, if any.\n nextSibling() { return this.sibling(1); }\n /// Move to this node's previous sibling, if any.\n prevSibling() { return this.sibling(-1); }\n atLastNode(dir) {\n let index, parent, { buffer } = this;\n if (buffer) {\n if (dir > 0) {\n if (this.index < buffer.buffer.buffer.length)\n return false;\n }\n else {\n for (let i = 0; i < this.index; i++)\n if (buffer.buffer.buffer[i + 3] < this.index)\n return false;\n }\n ({ index, parent } = buffer);\n }\n else {\n ({ index, _parent: parent } = this._tree);\n }\n for (; parent; { index, _parent: parent } = parent) {\n if (index > -1)\n for (let i = index + dir, e = dir < 0 ? -1 : parent._tree.children.length; i != e; i += dir) {\n let child = parent._tree.children[i];\n if ((this.mode & IterMode.IncludeAnonymous) ||\n child instanceof TreeBuffer ||\n !child.type.isAnonymous ||\n hasChild(child))\n return false;\n }\n }\n return true;\n }\n move(dir, enter) {\n if (enter && this.enterChild(dir, 0, 4 /* Side.DontCare */))\n return true;\n for (;;) {\n if (this.sibling(dir))\n return true;\n if (this.atLastNode(dir) || !this.parent())\n return false;\n }\n }\n /// Move to the next node in a\n /// [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR)\n /// traversal, going from a node to its first child or, if the\n /// current node is empty or `enter` is false, its next sibling or\n /// the next sibling of the first parent node that has one.\n next(enter = true) { return this.move(1, enter); }\n /// Move to the next node in a last-to-first pre-order traveral. A\n /// node is followed by its last child or, if it has none, its\n /// previous sibling or the previous sibling of the first parent\n /// node that has one.\n prev(enter = true) { return this.move(-1, enter); }\n /// Move the cursor to the innermost node that covers `pos`. If\n /// `side` is -1, it will enter nodes that end at `pos`. If it is 1,\n /// it will enter nodes that start at `pos`.\n moveTo(pos, side = 0) {\n // Move up to a node that actually holds the position, if possible\n while (this.from == this.to ||\n (side < 1 ? this.from >= pos : this.from > pos) ||\n (side > -1 ? this.to <= pos : this.to < pos))\n if (!this.parent())\n break;\n // Then scan down into child nodes as far as possible\n while (this.enterChild(1, pos, side)) { }\n return this;\n }\n /// Get a [syntax node](#common.SyntaxNode) at the cursor's current\n /// position.\n get node() {\n if (!this.buffer)\n return this._tree;\n let cache = this.bufferNode, result = null, depth = 0;\n if (cache && cache.context == this.buffer) {\n scan: for (let index = this.index, d = this.stack.length; d >= 0;) {\n for (let c = cache; c; c = c._parent)\n if (c.index == index) {\n if (index == this.index)\n return c;\n result = c;\n depth = d + 1;\n break scan;\n }\n index = this.stack[--d];\n }\n }\n for (let i = depth; i < this.stack.length; i++)\n result = new BufferNode(this.buffer, result, this.stack[i]);\n return this.bufferNode = new BufferNode(this.buffer, result, this.index);\n }\n /// Get the [tree](#common.Tree) that represents the current node, if\n /// any. Will return null when the node is in a [tree\n /// buffer](#common.TreeBuffer).\n get tree() {\n return this.buffer ? null : this._tree._tree;\n }\n /// Iterate over the current node and all its descendants, calling\n /// `enter` when entering a node and `leave`, if given, when leaving\n /// one. When `enter` returns `false`, any children of that node are\n /// skipped, and `leave` isn't called for it.\n iterate(enter, leave) {\n for (let depth = 0;;) {\n let mustLeave = false;\n if (this.type.isAnonymous || enter(this) !== false) {\n if (this.firstChild()) {\n depth++;\n continue;\n }\n if (!this.type.isAnonymous)\n mustLeave = true;\n }\n for (;;) {\n if (mustLeave && leave)\n leave(this);\n mustLeave = this.type.isAnonymous;\n if (this.nextSibling())\n break;\n if (!depth)\n return;\n this.parent();\n depth--;\n mustLeave = true;\n }\n }\n }\n /// Test whether the current node matches a given context\u2014a sequence\n /// of direct parent node names. Empty strings in the context array\n /// are treated as wildcards.\n matchContext(context) {\n if (!this.buffer)\n return matchNodeContext(this.node, context);\n let { buffer } = this.buffer, { types } = buffer.set;\n for (let i = context.length - 1, d = this.stack.length - 1; i >= 0; d--) {\n if (d < 0)\n return matchNodeContext(this.node, context, i);\n let type = types[buffer.buffer[this.stack[d]]];\n if (!type.isAnonymous) {\n if (context[i] && context[i] != type.name)\n return false;\n i--;\n }\n }\n return true;\n }\n}\nfunction hasChild(tree) {\n return tree.children.some(ch => ch instanceof TreeBuffer || !ch.type.isAnonymous || hasChild(ch));\n}\nfunction buildTree(data) {\n var _a;\n let { buffer, nodeSet, maxBufferLength = DefaultBufferLength, reused = [], minRepeatType = nodeSet.types.length } = data;\n let cursor = Array.isArray(buffer) ? new FlatBufferCursor(buffer, buffer.length) : buffer;\n let types = nodeSet.types;\n let contextHash = 0, lookAhead = 0;\n function takeNode(parentStart, minPos, children, positions, inRepeat) {\n let { id, start, end, size } = cursor;\n let lookAheadAtStart = lookAhead;\n while (size < 0) {\n cursor.next();\n if (size == -1 /* SpecialRecord.Reuse */) {\n let node = reused[id];\n children.push(node);\n positions.push(start - parentStart);\n return;\n }\n else if (size == -3 /* SpecialRecord.ContextChange */) { // Context change\n contextHash = id;\n return;\n }\n else if (size == -4 /* SpecialRecord.LookAhead */) {\n lookAhead = id;\n return;\n }\n else {\n throw new RangeError(`Unrecognized record size: ${size}`);\n }\n }\n let type = types[id], node, buffer;\n let startPos = start - parentStart;\n if (end - start <= maxBufferLength && (buffer = findBufferSize(cursor.pos - minPos, inRepeat))) {\n // Small enough for a buffer, and no reused nodes inside\n let data = new Uint16Array(buffer.size - buffer.skip);\n let endPos = cursor.pos - buffer.size, index = data.length;\n while (cursor.pos > endPos)\n index = copyToBuffer(buffer.start, data, index);\n node = new TreeBuffer(data, end - buffer.start, nodeSet);\n startPos = buffer.start - parentStart;\n }\n else { // Make it a node\n let endPos = cursor.pos - size;\n cursor.next();\n let localChildren = [], localPositions = [];\n let localInRepeat = id >= minRepeatType ? id : -1;\n let lastGroup = 0, lastEnd = end;\n while (cursor.pos > endPos) {\n if (localInRepeat >= 0 && cursor.id == localInRepeat && cursor.size >= 0) {\n if (cursor.end <= lastEnd - maxBufferLength) {\n makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor.end, lastEnd, localInRepeat, lookAheadAtStart);\n lastGroup = localChildren.length;\n lastEnd = cursor.end;\n }\n cursor.next();\n }\n else {\n takeNode(start, endPos, localChildren, localPositions, localInRepeat);\n }\n }\n if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length)\n makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart);\n localChildren.reverse();\n localPositions.reverse();\n if (localInRepeat > -1 && lastGroup > 0) {\n let make = makeBalanced(type);\n node = balanceRange(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make);\n }\n else {\n node = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end);\n }\n }\n children.push(node);\n positions.push(startPos);\n }\n function makeBalanced(type) {\n return (children, positions, length) => {\n let lookAhead = 0, lastI = children.length - 1, last, lookAheadProp;\n if (lastI >= 0 && (last = children[lastI]) instanceof Tree) {\n if (!lastI && last.type == type && last.length == length)\n return last;\n if (lookAheadProp = last.prop(NodeProp.lookAhead))\n lookAhead = positions[lastI] + last.length + lookAheadProp;\n }\n return makeTree(type, children, positions, length, lookAhead);\n };\n }\n function makeRepeatLeaf(children, positions, base, i, from, to, type, lookAhead) {\n let localChildren = [], localPositions = [];\n while (children.length > i) {\n localChildren.push(children.pop());\n localPositions.push(positions.pop() + base - from);\n }\n children.push(makeTree(nodeSet.types[type], localChildren, localPositions, to - from, lookAhead - to));\n positions.push(from - base);\n }\n function makeTree(type, children, positions, length, lookAhead = 0, props) {\n if (contextHash) {\n let pair = [NodeProp.contextHash, contextHash];\n props = props ? [pair].concat(props) : [pair];\n }\n if (lookAhead > 25) {\n let pair = [NodeProp.lookAhead, lookAhead];\n props = props ? [pair].concat(props) : [pair];\n }\n return new Tree(type, children, positions, length, props);\n }\n function findBufferSize(maxSize, inRepeat) {\n // Scan through the buffer to find previous siblings that fit\n // together in a TreeBuffer, and don't contain any reused nodes\n // (which can't be stored in a buffer).\n // If `inRepeat` is > -1, ignore node boundaries of that type for\n // nesting, but make sure the end falls either at the start\n // (`maxSize`) or before such a node.\n let fork = cursor.fork();\n let size = 0, start = 0, skip = 0, minStart = fork.end - maxBufferLength;\n let result = { size: 0, start: 0, skip: 0 };\n scan: for (let minPos = fork.pos - maxSize; fork.pos > minPos;) {\n let nodeSize = fork.size;\n // Pretend nested repeat nodes of the same type don't exist\n if (fork.id == inRepeat && nodeSize >= 0) {\n // Except that we store the current state as a valid return\n // value.\n result.size = size;\n result.start = start;\n result.skip = skip;\n skip += 4;\n size += 4;\n fork.next();\n continue;\n }\n let startPos = fork.pos - nodeSize;\n if (nodeSize < 0 || startPos < minPos || fork.start < minStart)\n break;\n let localSkipped = fork.id >= minRepeatType ? 4 : 0;\n let nodeStart = fork.start;\n fork.next();\n while (fork.pos > startPos) {\n if (fork.size < 0) {\n if (fork.size == -3 /* SpecialRecord.ContextChange */)\n localSkipped += 4;\n else\n break scan;\n }\n else if (fork.id >= minRepeatType) {\n localSkipped += 4;\n }\n fork.next();\n }\n start = nodeStart;\n size += nodeSize;\n skip += localSkipped;\n }\n if (inRepeat < 0 || size == maxSize) {\n result.size = size;\n result.start = start;\n result.skip = skip;\n }\n return result.size > 4 ? result : undefined;\n }\n function copyToBuffer(bufferStart, buffer, index) {\n let { id, start, end, size } = cursor;\n cursor.next();\n if (size >= 0 && id < minRepeatType) {\n let startIndex = index;\n if (size > 4) {\n let endPos = cursor.pos - (size - 4);\n while (cursor.pos > endPos)\n index = copyToBuffer(bufferStart, buffer, index);\n }\n buffer[--index] = startIndex;\n buffer[--index] = end - bufferStart;\n buffer[--index] = start - bufferStart;\n buffer[--index] = id;\n }\n else if (size == -3 /* SpecialRecord.ContextChange */) {\n contextHash = id;\n }\n else if (size == -4 /* SpecialRecord.LookAhead */) {\n lookAhead = id;\n }\n return index;\n }\n let children = [], positions = [];\n while (cursor.pos > 0)\n takeNode(data.start || 0, data.bufferStart || 0, children, positions, -1);\n let length = (_a = data.length) !== null && _a !== void 0 ? _a : (children.length ? positions[0] + children[0].length : 0);\n return new Tree(types[data.topID], children.reverse(), positions.reverse(), length);\n}\nconst nodeSizeCache = new WeakMap;\nfunction nodeSize(balanceType, node) {\n if (!balanceType.isAnonymous || node instanceof TreeBuffer || node.type != balanceType)\n return 1;\n let size = nodeSizeCache.get(node);\n if (size == null) {\n size = 1;\n for (let child of node.children) {\n if (child.type != balanceType || !(child instanceof Tree)) {\n size = 1;\n break;\n }\n size += nodeSize(balanceType, child);\n }\n nodeSizeCache.set(node, size);\n }\n return size;\n}\nfunction balanceRange(\n// The type the balanced tree's inner nodes.\nbalanceType, \n// The direct children and their positions\nchildren, positions, \n// The index range in children/positions to use\nfrom, to, \n// The start position of the nodes, relative to their parent.\nstart, \n// Length of the outer node\nlength, \n// Function to build the top node of the balanced tree\nmkTop, \n// Function to build internal nodes for the balanced tree\nmkTree) {\n let total = 0;\n for (let i = from; i < to; i++)\n total += nodeSize(balanceType, children[i]);\n let maxChild = Math.ceil((total * 1.5) / 8 /* Balance.BranchFactor */);\n let localChildren = [], localPositions = [];\n function divide(children, positions, from, to, offset) {\n for (let i = from; i < to;) {\n let groupFrom = i, groupStart = positions[i], groupSize = nodeSize(balanceType, children[i]);\n i++;\n for (; i < to; i++) {\n let nextSize = nodeSize(balanceType, children[i]);\n if (groupSize + nextSize >= maxChild)\n break;\n groupSize += nextSize;\n }\n if (i == groupFrom + 1) {\n if (groupSize > maxChild) {\n let only = children[groupFrom]; // Only trees can have a size > 1\n divide(only.children, only.positions, 0, only.children.length, positions[groupFrom] + offset);\n continue;\n }\n localChildren.push(children[groupFrom]);\n }\n else {\n let length = positions[i - 1] + children[i - 1].length - groupStart;\n localChildren.push(balanceRange(balanceType, children, positions, groupFrom, i, groupStart, length, null, mkTree));\n }\n localPositions.push(groupStart + offset - start);\n }\n }\n divide(children, positions, from, to, 0);\n return (mkTop || mkTree)(localChildren, localPositions, length);\n}\n/// Provides a way to associate values with pieces of trees. As long\n/// as that part of the tree is reused, the associated values can be\n/// retrieved from an updated tree.\nclass NodeWeakMap {\n constructor() {\n this.map = new WeakMap();\n }\n setBuffer(buffer, index, value) {\n let inner = this.map.get(buffer);\n if (!inner)\n this.map.set(buffer, inner = new Map);\n inner.set(index, value);\n }\n getBuffer(buffer, index) {\n let inner = this.map.get(buffer);\n return inner && inner.get(index);\n }\n /// Set the value for this syntax node.\n set(node, value) {\n if (node instanceof BufferNode)\n this.setBuffer(node.context.buffer, node.index, value);\n else if (node instanceof TreeNode)\n this.map.set(node.tree, value);\n }\n /// Retrieve value for this syntax node, if it exists in the map.\n get(node) {\n return node instanceof BufferNode ? this.getBuffer(node.context.buffer, node.index)\n : node instanceof TreeNode ? this.map.get(node.tree) : undefined;\n }\n /// Set the value for the node that a cursor currently points to.\n cursorSet(cursor, value) {\n if (cursor.buffer)\n this.setBuffer(cursor.buffer.buffer, cursor.index, value);\n else\n this.map.set(cursor.tree, value);\n }\n /// Retrieve the value for the node that a cursor currently points\n /// to.\n cursorGet(cursor) {\n return cursor.buffer ? this.getBuffer(cursor.buffer.buffer, cursor.index) : this.map.get(cursor.tree);\n }\n}\n\n/// Tree fragments are used during [incremental\n/// parsing](#common.Parser.startParse) to track parts of old trees\n/// that can be reused in a new parse. An array of fragments is used\n/// to track regions of an old tree whose nodes might be reused in new\n/// parses. Use the static\n/// [`applyChanges`](#common.TreeFragment^applyChanges) method to\n/// update fragments for document changes.\nclass TreeFragment {\n /// Construct a tree fragment. You'll usually want to use\n /// [`addTree`](#common.TreeFragment^addTree) and\n /// [`applyChanges`](#common.TreeFragment^applyChanges) instead of\n /// calling this directly.\n constructor(\n /// The start of the unchanged range pointed to by this fragment.\n /// This refers to an offset in the _updated_ document (as opposed\n /// to the original tree).\n from, \n /// The end of the unchanged range.\n to, \n /// The tree that this fragment is based on.\n tree, \n /// The offset between the fragment's tree and the document that\n /// this fragment can be used against. Add this when going from\n /// document to tree positions, subtract it to go from tree to\n /// document positions.\n offset, openStart = false, openEnd = false) {\n this.from = from;\n this.to = to;\n this.tree = tree;\n this.offset = offset;\n this.open = (openStart ? 1 /* Open.Start */ : 0) | (openEnd ? 2 /* Open.End */ : 0);\n }\n /// Whether the start of the fragment represents the start of a\n /// parse, or the end of a change. (In the second case, it may not\n /// be safe to reuse some nodes at the start, depending on the\n /// parsing algorithm.)\n get openStart() { return (this.open & 1 /* Open.Start */) > 0; }\n /// Whether the end of the fragment represents the end of a\n /// full-document parse, or the start of a change.\n get openEnd() { return (this.open & 2 /* Open.End */) > 0; }\n /// Create a set of fragments from a freshly parsed tree, or update\n /// an existing set of fragments by replacing the ones that overlap\n /// with a tree with content from the new tree. When `partial` is\n /// true, the parse is treated as incomplete, and the resulting\n /// fragment has [`openEnd`](#common.TreeFragment.openEnd) set to\n /// true.\n static addTree(tree, fragments = [], partial = false) {\n let result = [new TreeFragment(0, tree.length, tree, 0, false, partial)];\n for (let f of fragments)\n if (f.to > tree.length)\n result.push(f);\n return result;\n }\n /// Apply a set of edits to an array of fragments, removing or\n /// splitting fragments as necessary to remove edited ranges, and\n /// adjusting offsets for fragments that moved.\n static applyChanges(fragments, changes, minGap = 128) {\n if (!changes.length)\n return fragments;\n let result = [];\n let fI = 1, nextF = fragments.length ? fragments[0] : null;\n for (let cI = 0, pos = 0, off = 0;; cI++) {\n let nextC = cI < changes.length ? changes[cI] : null;\n let nextPos = nextC ? nextC.fromA : 1e9;\n if (nextPos - pos >= minGap)\n while (nextF && nextF.from < nextPos) {\n let cut = nextF;\n if (pos >= cut.from || nextPos <= cut.to || off) {\n let fFrom = Math.max(cut.from, pos) - off, fTo = Math.min(cut.to, nextPos) - off;\n cut = fFrom >= fTo ? null : new TreeFragment(fFrom, fTo, cut.tree, cut.offset + off, cI > 0, !!nextC);\n }\n if (cut)\n result.push(cut);\n if (nextF.to > nextPos)\n break;\n nextF = fI < fragments.length ? fragments[fI++] : null;\n }\n if (!nextC)\n break;\n pos = nextC.toA;\n off = nextC.toA - nextC.toB;\n }\n return result;\n }\n}\n/// A superclass that parsers should extend.\nclass Parser {\n /// Start a parse, returning a [partial parse](#common.PartialParse)\n /// object. [`fragments`](#common.TreeFragment) can be passed in to\n /// make the parse incremental.\n ///\n /// By default, the entire input is parsed. You can pass `ranges`,\n /// which should be a sorted array of non-empty, non-overlapping\n /// ranges, to parse only those ranges. The tree returned in that\n /// case will start at `ranges[0].from`.\n startParse(input, fragments, ranges) {\n if (typeof input == \"string\")\n input = new StringInput(input);\n ranges = !ranges ? [new Range(0, input.length)] : ranges.length ? ranges.map(r => new Range(r.from, r.to)) : [new Range(0, 0)];\n return this.createParse(input, fragments || [], ranges);\n }\n /// Run a full parse, returning the resulting tree.\n parse(input, fragments, ranges) {\n let parse = this.startParse(input, fragments, ranges);\n for (;;) {\n let done = parse.advance();\n if (done)\n return done;\n }\n }\n}\nclass StringInput {\n constructor(string) {\n this.string = string;\n }\n get length() { return this.string.length; }\n chunk(from) { return this.string.slice(from); }\n get lineChunks() { return false; }\n read(from, to) { return this.string.slice(from, to); }\n}\n\n/// Create a parse wrapper that, after the inner parse completes,\n/// scans its tree for mixed language regions with the `nest`\n/// function, runs the resulting [inner parses](#common.NestedParse),\n/// and then [mounts](#common.NodeProp^mounted) their results onto the\n/// tree.\nfunction parseMixed(nest) {\n return (parse, input, fragments, ranges) => new MixedParse(parse, nest, input, fragments, ranges);\n}\nclass InnerParse {\n constructor(parser, parse, overlay, target, ranges) {\n this.parser = parser;\n this.parse = parse;\n this.overlay = overlay;\n this.target = target;\n this.ranges = ranges;\n if (!ranges.length || ranges.some(r => r.from >= r.to))\n throw new RangeError(\"Invalid inner parse ranges given: \" + JSON.stringify(ranges));\n }\n}\nclass ActiveOverlay {\n constructor(parser, predicate, mounts, index, start, target, prev) {\n this.parser = parser;\n this.predicate = predicate;\n this.mounts = mounts;\n this.index = index;\n this.start = start;\n this.target = target;\n this.prev = prev;\n this.depth = 0;\n this.ranges = [];\n }\n}\nconst stoppedInner = new NodeProp({ perNode: true });\nclass MixedParse {\n constructor(base, nest, input, fragments, ranges) {\n this.nest = nest;\n this.input = input;\n this.fragments = fragments;\n this.ranges = ranges;\n this.inner = [];\n this.innerDone = 0;\n this.baseTree = null;\n this.stoppedAt = null;\n this.baseParse = base;\n }\n advance() {\n if (this.baseParse) {\n let done = this.baseParse.advance();\n if (!done)\n return null;\n this.baseParse = null;\n this.baseTree = done;\n this.startInner();\n if (this.stoppedAt != null)\n for (let inner of this.inner)\n inner.parse.stopAt(this.stoppedAt);\n }\n if (this.innerDone == this.inner.length) {\n let result = this.baseTree;\n if (this.stoppedAt != null)\n result = new Tree(result.type, result.children, result.positions, result.length, result.propValues.concat([[stoppedInner, this.stoppedAt]]));\n return result;\n }\n let inner = this.inner[this.innerDone], done = inner.parse.advance();\n if (done) {\n this.innerDone++;\n // This is a somewhat dodgy but super helpful hack where we\n // patch up nodes created by the inner parse (and thus\n // presumably not aliased anywhere else) to hold the information\n // about the inner parse.\n let props = Object.assign(Object.create(null), inner.target.props);\n props[NodeProp.mounted.id] = new MountedTree(done, inner.overlay, inner.parser);\n inner.target.props = props;\n }\n return null;\n }\n get parsedPos() {\n if (this.baseParse)\n return 0;\n let pos = this.input.length;\n for (let i = this.innerDone; i < this.inner.length; i++) {\n if (this.inner[i].ranges[0].from < pos)\n pos = Math.min(pos, this.inner[i].parse.parsedPos);\n }\n return pos;\n }\n stopAt(pos) {\n this.stoppedAt = pos;\n if (this.baseParse)\n this.baseParse.stopAt(pos);\n else\n for (let i = this.innerDone; i < this.inner.length; i++)\n this.inner[i].parse.stopAt(pos);\n }\n startInner() {\n let fragmentCursor = new FragmentCursor(this.fragments);\n let overlay = null;\n let covered = null;\n let cursor = new TreeCursor(new TreeNode(this.baseTree, this.ranges[0].from, 0, null), IterMode.IncludeAnonymous | IterMode.IgnoreMounts);\n scan: for (let nest, isCovered; this.stoppedAt == null || cursor.from < this.stoppedAt;) {\n let enter = true, range;\n if (fragmentCursor.hasNode(cursor)) {\n if (overlay) {\n let match = overlay.mounts.find(m => m.frag.from <= cursor.from && m.frag.to >= cursor.to && m.mount.overlay);\n if (match)\n for (let r of match.mount.overlay) {\n let from = r.from + match.pos, to = r.to + match.pos;\n if (from >= cursor.from && to <= cursor.to && !overlay.ranges.some(r => r.from < to && r.to > from))\n overlay.ranges.push({ from, to });\n }\n }\n enter = false;\n }\n else if (covered && (isCovered = checkCover(covered.ranges, cursor.from, cursor.to))) {\n enter = isCovered != 2 /* Cover.Full */;\n }\n else if (!cursor.type.isAnonymous && cursor.from < cursor.to && (nest = this.nest(cursor, this.input))) {\n if (!cursor.tree)\n materialize(cursor);\n let oldMounts = fragmentCursor.findMounts(cursor.from, nest.parser);\n if (typeof nest.overlay == \"function\") {\n overlay = new ActiveOverlay(nest.parser, nest.overlay, oldMounts, this.inner.length, cursor.from, cursor.tree, overlay);\n }\n else {\n let ranges = punchRanges(this.ranges, nest.overlay || [new Range(cursor.from, cursor.to)]);\n if (ranges.length)\n this.inner.push(new InnerParse(nest.parser, nest.parser.startParse(this.input, enterFragments(oldMounts, ranges), ranges), nest.overlay ? nest.overlay.map(r => new Range(r.from - cursor.from, r.to - cursor.from)) : null, cursor.tree, ranges));\n if (!nest.overlay)\n enter = false;\n else if (ranges.length)\n covered = { ranges, depth: 0, prev: covered };\n }\n }\n else if (overlay && (range = overlay.predicate(cursor))) {\n if (range === true)\n range = new Range(cursor.from, cursor.to);\n if (range.from < range.to)\n overlay.ranges.push(range);\n }\n if (enter && cursor.firstChild()) {\n if (overlay)\n overlay.depth++;\n if (covered)\n covered.depth++;\n }\n else {\n for (;;) {\n if (cursor.nextSibling())\n break;\n if (!cursor.parent())\n break scan;\n if (overlay && !--overlay.depth) {\n let ranges = punchRanges(this.ranges, overlay.ranges);\n if (ranges.length)\n this.inner.splice(overlay.index, 0, new InnerParse(overlay.parser, overlay.parser.startParse(this.input, enterFragments(overlay.mounts, ranges), ranges), overlay.ranges.map(r => new Range(r.from - overlay.start, r.to - overlay.start)), overlay.target, ranges));\n overlay = overlay.prev;\n }\n if (covered && !--covered.depth)\n covered = covered.prev;\n }\n }\n }\n }\n}\nfunction checkCover(covered, from, to) {\n for (let range of covered) {\n if (range.from >= to)\n break;\n if (range.to > from)\n return range.from <= from && range.to >= to ? 2 /* Cover.Full */ : 1 /* Cover.Partial */;\n }\n return 0 /* Cover.None */;\n}\n// Take a piece of buffer and convert it into a stand-alone\n// TreeBuffer.\nfunction sliceBuf(buf, startI, endI, nodes, positions, off) {\n if (startI < endI) {\n let from = buf.buffer[startI + 1];\n nodes.push(buf.slice(startI, endI, from));\n positions.push(from - off);\n }\n}\n// This function takes a node that's in a buffer, and converts it, and\n// its parent buffer nodes, into a Tree. This is again acting on the\n// assumption that the trees and buffers have been constructed by the\n// parse that was ran via the mix parser, and thus aren't shared with\n// any other code, making violations of the immutability safe.\nfunction materialize(cursor) {\n let { node } = cursor, depth = 0;\n // Scan up to the nearest tree\n do {\n cursor.parent();\n depth++;\n } while (!cursor.tree);\n // Find the index of the buffer in that tree\n let i = 0, base = cursor.tree, off = 0;\n for (;; i++) {\n off = base.positions[i] + cursor.from;\n if (off <= node.from && off + base.children[i].length >= node.to)\n break;\n }\n let buf = base.children[i], b = buf.buffer;\n // Split a level in the buffer, putting the nodes before and after\n // the child that contains `node` into new buffers.\n function split(startI, endI, type, innerOffset, length) {\n let i = startI;\n while (b[i + 2] + off <= node.from)\n i = b[i + 3];\n let children = [], positions = [];\n sliceBuf(buf, startI, i, children, positions, innerOffset);\n let from = b[i + 1], to = b[i + 2];\n let isTarget = from + off == node.from && to + off == node.to && b[i] == node.type.id;\n children.push(isTarget ? node.toTree() : split(i + 4, b[i + 3], buf.set.types[b[i]], from, to - from));\n positions.push(from - innerOffset);\n sliceBuf(buf, b[i + 3], endI, children, positions, innerOffset);\n return new Tree(type, children, positions, length);\n }\n base.children[i] = split(0, b.length, NodeType.none, 0, buf.length);\n // Move the cursor back to the target node\n for (let d = 0; d <= depth; d++)\n cursor.childAfter(node.from);\n}\nclass StructureCursor {\n constructor(root, offset) {\n this.offset = offset;\n this.done = false;\n this.cursor = root.cursor(IterMode.IncludeAnonymous | IterMode.IgnoreMounts);\n }\n // Move to the first node (in pre-order) that starts at or after `pos`.\n moveTo(pos) {\n let { cursor } = this, p = pos - this.offset;\n while (!this.done && cursor.from < p) {\n if (cursor.to >= pos && cursor.enter(p, 1, IterMode.IgnoreOverlays | IterMode.ExcludeBuffers)) ;\n else if (!cursor.next(false))\n this.done = true;\n }\n }\n hasNode(cursor) {\n this.moveTo(cursor.from);\n if (!this.done && this.cursor.from + this.offset == cursor.from && this.cursor.tree) {\n for (let tree = this.cursor.tree;;) {\n if (tree == cursor.tree)\n return true;\n if (tree.children.length && tree.positions[0] == 0 && tree.children[0] instanceof Tree)\n tree = tree.children[0];\n else\n break;\n }\n }\n return false;\n }\n}\nclass FragmentCursor {\n constructor(fragments) {\n var _a;\n this.fragments = fragments;\n this.curTo = 0;\n this.fragI = 0;\n if (fragments.length) {\n let first = this.curFrag = fragments[0];\n this.curTo = (_a = first.tree.prop(stoppedInner)) !== null && _a !== void 0 ? _a : first.to;\n this.inner = new StructureCursor(first.tree, -first.offset);\n }\n else {\n this.curFrag = this.inner = null;\n }\n }\n hasNode(node) {\n while (this.curFrag && node.from >= this.curTo)\n this.nextFrag();\n return this.curFrag && this.curFrag.from <= node.from && this.curTo >= node.to && this.inner.hasNode(node);\n }\n nextFrag() {\n var _a;\n this.fragI++;\n if (this.fragI == this.fragments.length) {\n this.curFrag = this.inner = null;\n }\n else {\n let frag = this.curFrag = this.fragments[this.fragI];\n this.curTo = (_a = frag.tree.prop(stoppedInner)) !== null && _a !== void 0 ? _a : frag.to;\n this.inner = new StructureCursor(frag.tree, -frag.offset);\n }\n }\n findMounts(pos, parser) {\n var _a;\n let result = [];\n if (this.inner) {\n this.inner.cursor.moveTo(pos, 1);\n for (let pos = this.inner.cursor.node; pos; pos = pos.parent) {\n let mount = (_a = pos.tree) === null || _a === void 0 ? void 0 : _a.prop(NodeProp.mounted);\n if (mount && mount.parser == parser) {\n for (let i = this.fragI; i < this.fragments.length; i++) {\n let frag = this.fragments[i];\n if (frag.from >= pos.to)\n break;\n if (frag.tree == this.curFrag.tree)\n result.push({\n frag,\n pos: pos.from - frag.offset,\n mount\n });\n }\n }\n }\n }\n return result;\n }\n}\nfunction punchRanges(outer, ranges) {\n let copy = null, current = ranges;\n for (let i = 1, j = 0; i < outer.length; i++) {\n let gapFrom = outer[i - 1].to, gapTo = outer[i].from;\n for (; j < current.length; j++) {\n let r = current[j];\n if (r.from >= gapTo)\n break;\n if (r.to <= gapFrom)\n continue;\n if (!copy)\n current = copy = ranges.slice();\n if (r.from < gapFrom) {\n copy[j] = new Range(r.from, gapFrom);\n if (r.to > gapTo)\n copy.splice(j + 1, 0, new Range(gapTo, r.to));\n }\n else if (r.to > gapTo) {\n copy[j--] = new Range(gapTo, r.to);\n }\n else {\n copy.splice(j--, 1);\n }\n }\n }\n return current;\n}\nfunction findCoverChanges(a, b, from, to) {\n let iA = 0, iB = 0, inA = false, inB = false, pos = -1e9;\n let result = [];\n for (;;) {\n let nextA = iA == a.length ? 1e9 : inA ? a[iA].to : a[iA].from;\n let nextB = iB == b.length ? 1e9 : inB ? b[iB].to : b[iB].from;\n if (inA != inB) {\n let start = Math.max(pos, from), end = Math.min(nextA, nextB, to);\n if (start < end)\n result.push(new Range(start, end));\n }\n pos = Math.min(nextA, nextB);\n if (pos == 1e9)\n break;\n if (nextA == pos) {\n if (!inA)\n inA = true;\n else {\n inA = false;\n iA++;\n }\n }\n if (nextB == pos) {\n if (!inB)\n inB = true;\n else {\n inB = false;\n iB++;\n }\n }\n }\n return result;\n}\n// Given a number of fragments for the outer tree, and a set of ranges\n// to parse, find fragments for inner trees mounted around those\n// ranges, if any.\nfunction enterFragments(mounts, ranges) {\n let result = [];\n for (let { pos, mount, frag } of mounts) {\n let startPos = pos + (mount.overlay ? mount.overlay[0].from : 0), endPos = startPos + mount.tree.length;\n let from = Math.max(frag.from, startPos), to = Math.min(frag.to, endPos);\n if (mount.overlay) {\n let overlay = mount.overlay.map(r => new Range(r.from + pos, r.to + pos));\n let changes = findCoverChanges(ranges, overlay, from, to);\n for (let i = 0, pos = from;; i++) {\n let last = i == changes.length, end = last ? to : changes[i].from;\n if (end > pos)\n result.push(new TreeFragment(pos, end, mount.tree, -startPos, frag.from >= pos || frag.openStart, frag.to <= end || frag.openEnd));\n if (last)\n break;\n pos = changes[i].to;\n }\n }\n else {\n result.push(new TreeFragment(from, to, mount.tree, -startPos, frag.from >= startPos || frag.openStart, frag.to <= endPos || frag.openEnd));\n }\n }\n return result;\n}\n\nexport { DefaultBufferLength, IterMode, MountedTree, NodeProp, NodeSet, NodeType, NodeWeakMap, Parser, Tree, TreeBuffer, TreeCursor, TreeFragment, parseMixed };\n", "import { Parser, NodeProp, NodeSet, NodeType, DefaultBufferLength, Tree, IterMode } from '@lezer/common';\n\n/// A parse stack. These are used internally by the parser to track\n/// parsing progress. They also provide some properties and methods\n/// that external code such as a tokenizer can use to get information\n/// about the parse state.\nclass Stack {\n /// @internal\n constructor(\n /// The parse that this stack is part of @internal\n p, \n /// Holds state, input pos, buffer index triplets for all but the\n /// top state @internal\n stack, \n /// The current parse state @internal\n state, \n // The position at which the next reduce should take place. This\n // can be less than `this.pos` when skipped expressions have been\n // added to the stack (which should be moved outside of the next\n // reduction)\n /// @internal\n reducePos, \n /// The input position up to which this stack has parsed.\n pos, \n /// The dynamic score of the stack, including dynamic precedence\n /// and error-recovery penalties\n /// @internal\n score, \n // The output buffer. Holds (type, start, end, size) quads\n // representing nodes created by the parser, where `size` is\n // amount of buffer array entries covered by this node.\n /// @internal\n buffer, \n // The base offset of the buffer. When stacks are split, the split\n // instance shared the buffer history with its parent up to\n // `bufferBase`, which is the absolute offset (including the\n // offset of previous splits) into the buffer at which this stack\n // starts writing.\n /// @internal\n bufferBase, \n /// @internal\n curContext, \n /// @internal\n lookAhead = 0, \n // A parent stack from which this was split off, if any. This is\n // set up so that it always points to a stack that has some\n // additional buffer content, never to a stack with an equal\n // `bufferBase`.\n /// @internal\n parent) {\n this.p = p;\n this.stack = stack;\n this.state = state;\n this.reducePos = reducePos;\n this.pos = pos;\n this.score = score;\n this.buffer = buffer;\n this.bufferBase = bufferBase;\n this.curContext = curContext;\n this.lookAhead = lookAhead;\n this.parent = parent;\n }\n /// @internal\n toString() {\n return `[${this.stack.filter((_, i) => i % 3 == 0).concat(this.state)}]@${this.pos}${this.score ? \"!\" + this.score : \"\"}`;\n }\n // Start an empty stack\n /// @internal\n static start(p, state, pos = 0) {\n let cx = p.parser.context;\n return new Stack(p, [], state, pos, pos, 0, [], 0, cx ? new StackContext(cx, cx.start) : null, 0, null);\n }\n /// The stack's current [context](#lr.ContextTracker) value, if\n /// any. Its type will depend on the context tracker's type\n /// parameter, or it will be `null` if there is no context\n /// tracker.\n get context() { return this.curContext ? this.curContext.context : null; }\n // Push a state onto the stack, tracking its start position as well\n // as the buffer base at that point.\n /// @internal\n pushState(state, start) {\n this.stack.push(this.state, start, this.bufferBase + this.buffer.length);\n this.state = state;\n }\n // Apply a reduce action\n /// @internal\n reduce(action) {\n var _a;\n let depth = action >> 19 /* Action.ReduceDepthShift */, type = action & 65535 /* Action.ValueMask */;\n let { parser } = this.p;\n let dPrec = parser.dynamicPrecedence(type);\n if (dPrec)\n this.score += dPrec;\n if (depth == 0) {\n this.pushState(parser.getGoto(this.state, type, true), this.reducePos);\n // Zero-depth reductions are a special case\u2014they add stuff to\n // the stack without popping anything off.\n if (type < parser.minRepeatTerm)\n this.storeNode(type, this.reducePos, this.reducePos, 4, true);\n this.reduceContext(type, this.reducePos);\n return;\n }\n // Find the base index into `this.stack`, content after which will\n // be dropped. Note that with `StayFlag` reductions we need to\n // consume two extra frames (the dummy parent node for the skipped\n // expression and the state that we'll be staying in, which should\n // be moved to `this.state`).\n let base = this.stack.length - ((depth - 1) * 3) - (action & 262144 /* Action.StayFlag */ ? 6 : 0);\n let start = base ? this.stack[base - 2] : this.p.ranges[0].from, size = this.reducePos - start;\n // This is a kludge to try and detect overly deep left-associative\n // trees, which will not increase the parse stack depth and thus\n // won't be caught by the regular stack-depth limit check.\n if (size >= 2000 /* Recover.MinBigReduction */ && !((_a = this.p.parser.nodeSet.types[type]) === null || _a === void 0 ? void 0 : _a.isAnonymous)) {\n if (start == this.p.lastBigReductionStart) {\n this.p.bigReductionCount++;\n this.p.lastBigReductionSize = size;\n }\n else if (this.p.lastBigReductionSize < size) {\n this.p.bigReductionCount = 1;\n this.p.lastBigReductionStart = start;\n this.p.lastBigReductionSize = size;\n }\n }\n let bufferBase = base ? this.stack[base - 1] : 0, count = this.bufferBase + this.buffer.length - bufferBase;\n // Store normal terms or `R -> R R` repeat reductions\n if (type < parser.minRepeatTerm || (action & 131072 /* Action.RepeatFlag */)) {\n let pos = parser.stateFlag(this.state, 1 /* StateFlag.Skipped */) ? this.pos : this.reducePos;\n this.storeNode(type, start, pos, count + 4, true);\n }\n if (action & 262144 /* Action.StayFlag */) {\n this.state = this.stack[base];\n }\n else {\n let baseStateID = this.stack[base - 3];\n this.state = parser.getGoto(baseStateID, type, true);\n }\n while (this.stack.length > base)\n this.stack.pop();\n this.reduceContext(type, start);\n }\n // Shift a value into the buffer\n /// @internal\n storeNode(term, start, end, size = 4, isReduce = false) {\n if (term == 0 /* Term.Err */ &&\n (!this.stack.length || this.stack[this.stack.length - 1] < this.buffer.length + this.bufferBase)) {\n // Try to omit/merge adjacent error nodes\n let cur = this, top = this.buffer.length;\n if (top == 0 && cur.parent) {\n top = cur.bufferBase - cur.parent.bufferBase;\n cur = cur.parent;\n }\n if (top > 0 && cur.buffer[top - 4] == 0 /* Term.Err */ && cur.buffer[top - 1] > -1) {\n if (start == end)\n return;\n if (cur.buffer[top - 2] >= start) {\n cur.buffer[top - 2] = end;\n return;\n }\n }\n }\n if (!isReduce || this.pos == end) { // Simple case, just append\n this.buffer.push(term, start, end, size);\n }\n else { // There may be skipped nodes that have to be moved forward\n let index = this.buffer.length;\n if (index > 0 && this.buffer[index - 4] != 0 /* Term.Err */)\n while (index > 0 && this.buffer[index - 2] > end) {\n // Move this record forward\n this.buffer[index] = this.buffer[index - 4];\n this.buffer[index + 1] = this.buffer[index - 3];\n this.buffer[index + 2] = this.buffer[index - 2];\n this.buffer[index + 3] = this.buffer[index - 1];\n index -= 4;\n if (size > 4)\n size -= 4;\n }\n this.buffer[index] = term;\n this.buffer[index + 1] = start;\n this.buffer[index + 2] = end;\n this.buffer[index + 3] = size;\n }\n }\n // Apply a shift action\n /// @internal\n shift(action, next, nextEnd) {\n let start = this.pos;\n if (action & 131072 /* Action.GotoFlag */) {\n this.pushState(action & 65535 /* Action.ValueMask */, this.pos);\n }\n else if ((action & 262144 /* Action.StayFlag */) == 0) { // Regular shift\n let nextState = action, { parser } = this.p;\n if (nextEnd > this.pos || next <= parser.maxNode) {\n this.pos = nextEnd;\n if (!parser.stateFlag(nextState, 1 /* StateFlag.Skipped */))\n this.reducePos = nextEnd;\n }\n this.pushState(nextState, start);\n this.shiftContext(next, start);\n if (next <= parser.maxNode)\n this.buffer.push(next, start, nextEnd, 4);\n }\n else { // Shift-and-stay, which means this is a skipped token\n this.pos = nextEnd;\n this.shiftContext(next, start);\n if (next <= this.p.parser.maxNode)\n this.buffer.push(next, start, nextEnd, 4);\n }\n }\n // Apply an action\n /// @internal\n apply(action, next, nextEnd) {\n if (action & 65536 /* Action.ReduceFlag */)\n this.reduce(action);\n else\n this.shift(action, next, nextEnd);\n }\n // Add a prebuilt (reused) node into the buffer.\n /// @internal\n useNode(value, next) {\n let index = this.p.reused.length - 1;\n if (index < 0 || this.p.reused[index] != value) {\n this.p.reused.push(value);\n index++;\n }\n let start = this.pos;\n this.reducePos = this.pos = start + value.length;\n this.pushState(next, start);\n this.buffer.push(index, start, this.reducePos, -1 /* size == -1 means this is a reused value */);\n if (this.curContext)\n this.updateContext(this.curContext.tracker.reuse(this.curContext.context, value, this, this.p.stream.reset(this.pos - value.length)));\n }\n // Split the stack. Due to the buffer sharing and the fact\n // that `this.stack` tends to stay quite shallow, this isn't very\n // expensive.\n /// @internal\n split() {\n let parent = this;\n let off = parent.buffer.length;\n // Because the top of the buffer (after this.pos) may be mutated\n // to reorder reductions and skipped tokens, and shared buffers\n // should be immutable, this copies any outstanding skipped tokens\n // to the new buffer, and puts the base pointer before them.\n while (off > 0 && parent.buffer[off - 2] > parent.reducePos)\n off -= 4;\n let buffer = parent.buffer.slice(off), base = parent.bufferBase + off;\n // Make sure parent points to an actual parent with content, if there is such a parent.\n while (parent && base == parent.bufferBase)\n parent = parent.parent;\n return new Stack(this.p, this.stack.slice(), this.state, this.reducePos, this.pos, this.score, buffer, base, this.curContext, this.lookAhead, parent);\n }\n // Try to recover from an error by 'deleting' (ignoring) one token.\n /// @internal\n recoverByDelete(next, nextEnd) {\n let isNode = next <= this.p.parser.maxNode;\n if (isNode)\n this.storeNode(next, this.pos, nextEnd, 4);\n this.storeNode(0 /* Term.Err */, this.pos, nextEnd, isNode ? 8 : 4);\n this.pos = this.reducePos = nextEnd;\n this.score -= 190 /* Recover.Delete */;\n }\n /// Check if the given term would be able to be shifted (optionally\n /// after some reductions) on this stack. This can be useful for\n /// external tokenizers that want to make sure they only provide a\n /// given token when it applies.\n canShift(term) {\n for (let sim = new SimulatedStack(this);;) {\n let action = this.p.parser.stateSlot(sim.state, 4 /* ParseState.DefaultReduce */) || this.p.parser.hasAction(sim.state, term);\n if (action == 0)\n return false;\n if ((action & 65536 /* Action.ReduceFlag */) == 0)\n return true;\n sim.reduce(action);\n }\n }\n // Apply up to Recover.MaxNext recovery actions that conceptually\n // inserts some missing token or rule.\n /// @internal\n recoverByInsert(next) {\n if (this.stack.length >= 300 /* Recover.MaxInsertStackDepth */)\n return [];\n let nextStates = this.p.parser.nextStates(this.state);\n if (nextStates.length > 4 /* Recover.MaxNext */ << 1 || this.stack.length >= 120 /* Recover.DampenInsertStackDepth */) {\n let best = [];\n for (let i = 0, s; i < nextStates.length; i += 2) {\n if ((s = nextStates[i + 1]) != this.state && this.p.parser.hasAction(s, next))\n best.push(nextStates[i], s);\n }\n if (this.stack.length < 120 /* Recover.DampenInsertStackDepth */)\n for (let i = 0; best.length < 4 /* Recover.MaxNext */ << 1 && i < nextStates.length; i += 2) {\n let s = nextStates[i + 1];\n if (!best.some((v, i) => (i & 1) && v == s))\n best.push(nextStates[i], s);\n }\n nextStates = best;\n }\n let result = [];\n for (let i = 0; i < nextStates.length && result.length < 4 /* Recover.MaxNext */; i += 2) {\n let s = nextStates[i + 1];\n if (s == this.state)\n continue;\n let stack = this.split();\n stack.pushState(s, this.pos);\n stack.storeNode(0 /* Term.Err */, stack.pos, stack.pos, 4, true);\n stack.shiftContext(nextStates[i], this.pos);\n stack.score -= 200 /* Recover.Insert */;\n result.push(stack);\n }\n return result;\n }\n // Force a reduce, if possible. Return false if that can't\n // be done.\n /// @internal\n forceReduce() {\n let { parser } = this.p;\n let reduce = parser.stateSlot(this.state, 5 /* ParseState.ForcedReduce */);\n if ((reduce & 65536 /* Action.ReduceFlag */) == 0)\n return false;\n if (!parser.validAction(this.state, reduce)) {\n let depth = reduce >> 19 /* Action.ReduceDepthShift */, term = reduce & 65535 /* Action.ValueMask */;\n let target = this.stack.length - depth * 3;\n if (target < 0 || parser.getGoto(this.stack[target], term, false) < 0) {\n let backup = this.findForcedReduction();\n if (backup == null)\n return false;\n reduce = backup;\n }\n this.storeNode(0 /* Term.Err */, this.pos, this.pos, 4, true);\n this.score -= 100 /* Recover.Reduce */;\n }\n this.reducePos = this.pos;\n this.reduce(reduce);\n return true;\n }\n /// Try to scan through the automaton to find some kind of reduction\n /// that can be applied. Used when the regular ForcedReduce field\n /// isn't a valid action. @internal\n findForcedReduction() {\n let { parser } = this.p, seen = [];\n let explore = (state, depth) => {\n if (seen.includes(state))\n return;\n seen.push(state);\n return parser.allActions(state, (action) => {\n if (action & (262144 /* Action.StayFlag */ | 131072 /* Action.GotoFlag */)) ;\n else if (action & 65536 /* Action.ReduceFlag */) {\n let rDepth = (action >> 19 /* Action.ReduceDepthShift */) - depth;\n if (rDepth > 1) {\n let term = action & 65535 /* Action.ValueMask */, target = this.stack.length - rDepth * 3;\n if (target >= 0 && parser.getGoto(this.stack[target], term, false) >= 0)\n return (rDepth << 19 /* Action.ReduceDepthShift */) | 65536 /* Action.ReduceFlag */ | term;\n }\n }\n else {\n let found = explore(action, depth + 1);\n if (found != null)\n return found;\n }\n });\n };\n return explore(this.state, 0);\n }\n /// @internal\n forceAll() {\n while (!this.p.parser.stateFlag(this.state, 2 /* StateFlag.Accepting */)) {\n if (!this.forceReduce()) {\n this.storeNode(0 /* Term.Err */, this.pos, this.pos, 4, true);\n break;\n }\n }\n return this;\n }\n /// Check whether this state has no further actions (assumed to be a direct descendant of the\n /// top state, since any other states must be able to continue\n /// somehow). @internal\n get deadEnd() {\n if (this.stack.length != 3)\n return false;\n let { parser } = this.p;\n return parser.data[parser.stateSlot(this.state, 1 /* ParseState.Actions */)] == 65535 /* Seq.End */ &&\n !parser.stateSlot(this.state, 4 /* ParseState.DefaultReduce */);\n }\n /// Restart the stack (put it back in its start state). Only safe\n /// when this.stack.length == 3 (state is directly below the top\n /// state). @internal\n restart() {\n this.state = this.stack[0];\n this.stack.length = 0;\n }\n /// @internal\n sameState(other) {\n if (this.state != other.state || this.stack.length != other.stack.length)\n return false;\n for (let i = 0; i < this.stack.length; i += 3)\n if (this.stack[i] != other.stack[i])\n return false;\n return true;\n }\n /// Get the parser used by this stack.\n get parser() { return this.p.parser; }\n /// Test whether a given dialect (by numeric ID, as exported from\n /// the terms file) is enabled.\n dialectEnabled(dialectID) { return this.p.parser.dialect.flags[dialectID]; }\n shiftContext(term, start) {\n if (this.curContext)\n this.updateContext(this.curContext.tracker.shift(this.curContext.context, term, this, this.p.stream.reset(start)));\n }\n reduceContext(term, start) {\n if (this.curContext)\n this.updateContext(this.curContext.tracker.reduce(this.curContext.context, term, this, this.p.stream.reset(start)));\n }\n /// @internal\n emitContext() {\n let last = this.buffer.length - 1;\n if (last < 0 || this.buffer[last] != -3)\n this.buffer.push(this.curContext.hash, this.pos, this.pos, -3);\n }\n /// @internal\n emitLookAhead() {\n let last = this.buffer.length - 1;\n if (last < 0 || this.buffer[last] != -4)\n this.buffer.push(this.lookAhead, this.pos, this.pos, -4);\n }\n updateContext(context) {\n if (context != this.curContext.context) {\n let newCx = new StackContext(this.curContext.tracker, context);\n if (newCx.hash != this.curContext.hash)\n this.emitContext();\n this.curContext = newCx;\n }\n }\n /// @internal\n setLookAhead(lookAhead) {\n if (lookAhead > this.lookAhead) {\n this.emitLookAhead();\n this.lookAhead = lookAhead;\n }\n }\n /// @internal\n close() {\n if (this.curContext && this.curContext.tracker.strict)\n this.emitContext();\n if (this.lookAhead > 0)\n this.emitLookAhead();\n }\n}\nclass StackContext {\n constructor(tracker, context) {\n this.tracker = tracker;\n this.context = context;\n this.hash = tracker.strict ? tracker.hash(context) : 0;\n }\n}\nvar Recover;\n(function (Recover) {\n Recover[Recover[\"Insert\"] = 200] = \"Insert\";\n Recover[Recover[\"Delete\"] = 190] = \"Delete\";\n Recover[Recover[\"Reduce\"] = 100] = \"Reduce\";\n Recover[Recover[\"MaxNext\"] = 4] = \"MaxNext\";\n Recover[Recover[\"MaxInsertStackDepth\"] = 300] = \"MaxInsertStackDepth\";\n Recover[Recover[\"DampenInsertStackDepth\"] = 120] = \"DampenInsertStackDepth\";\n Recover[Recover[\"MinBigReduction\"] = 2000] = \"MinBigReduction\";\n})(Recover || (Recover = {}));\n// Used to cheaply run some reductions to scan ahead without mutating\n// an entire stack\nclass SimulatedStack {\n constructor(start) {\n this.start = start;\n this.state = start.state;\n this.stack = start.stack;\n this.base = this.stack.length;\n }\n reduce(action) {\n let term = action & 65535 /* Action.ValueMask */, depth = action >> 19 /* Action.ReduceDepthShift */;\n if (depth == 0) {\n if (this.stack == this.start.stack)\n this.stack = this.stack.slice();\n this.stack.push(this.state, 0, 0);\n this.base += 3;\n }\n else {\n this.base -= (depth - 1) * 3;\n }\n let goto = this.start.p.parser.getGoto(this.stack[this.base - 3], term, true);\n this.state = goto;\n }\n}\n// This is given to `Tree.build` to build a buffer, and encapsulates\n// the parent-stack-walking necessary to read the nodes.\nclass StackBufferCursor {\n constructor(stack, pos, index) {\n this.stack = stack;\n this.pos = pos;\n this.index = index;\n this.buffer = stack.buffer;\n if (this.index == 0)\n this.maybeNext();\n }\n static create(stack, pos = stack.bufferBase + stack.buffer.length) {\n return new StackBufferCursor(stack, pos, pos - stack.bufferBase);\n }\n maybeNext() {\n let next = this.stack.parent;\n if (next != null) {\n this.index = this.stack.bufferBase - next.bufferBase;\n this.stack = next;\n this.buffer = next.buffer;\n }\n }\n get id() { return this.buffer[this.index - 4]; }\n get start() { return this.buffer[this.index - 3]; }\n get end() { return this.buffer[this.index - 2]; }\n get size() { return this.buffer[this.index - 1]; }\n next() {\n this.index -= 4;\n this.pos -= 4;\n if (this.index == 0)\n this.maybeNext();\n }\n fork() {\n return new StackBufferCursor(this.stack, this.pos, this.index);\n }\n}\n\n// See lezer-generator/src/encode.ts for comments about the encoding\n// used here\nfunction decodeArray(input, Type = Uint16Array) {\n if (typeof input != \"string\")\n return input;\n let array = null;\n for (let pos = 0, out = 0; pos < input.length;) {\n let value = 0;\n for (;;) {\n let next = input.charCodeAt(pos++), stop = false;\n if (next == 126 /* Encode.BigValCode */) {\n value = 65535 /* Encode.BigVal */;\n break;\n }\n if (next >= 92 /* Encode.Gap2 */)\n next--;\n if (next >= 34 /* Encode.Gap1 */)\n next--;\n let digit = next - 32 /* Encode.Start */;\n if (digit >= 46 /* Encode.Base */) {\n digit -= 46 /* Encode.Base */;\n stop = true;\n }\n value += digit;\n if (stop)\n break;\n value *= 46 /* Encode.Base */;\n }\n if (array)\n array[out++] = value;\n else\n array = new Type(value);\n }\n return array;\n}\n\nclass CachedToken {\n constructor() {\n this.start = -1;\n this.value = -1;\n this.end = -1;\n this.extended = -1;\n this.lookAhead = 0;\n this.mask = 0;\n this.context = 0;\n }\n}\nconst nullToken = new CachedToken;\n/// [Tokenizers](#lr.ExternalTokenizer) interact with the input\n/// through this interface. It presents the input as a stream of\n/// characters, tracking lookahead and hiding the complexity of\n/// [ranges](#common.Parser.parse^ranges) from tokenizer code.\nclass InputStream {\n /// @internal\n constructor(\n /// @internal\n input, \n /// @internal\n ranges) {\n this.input = input;\n this.ranges = ranges;\n /// @internal\n this.chunk = \"\";\n /// @internal\n this.chunkOff = 0;\n /// Backup chunk\n this.chunk2 = \"\";\n this.chunk2Pos = 0;\n /// The character code of the next code unit in the input, or -1\n /// when the stream is at the end of the input.\n this.next = -1;\n /// @internal\n this.token = nullToken;\n this.rangeIndex = 0;\n this.pos = this.chunkPos = ranges[0].from;\n this.range = ranges[0];\n this.end = ranges[ranges.length - 1].to;\n this.readNext();\n }\n /// @internal\n resolveOffset(offset, assoc) {\n let range = this.range, index = this.rangeIndex;\n let pos = this.pos + offset;\n while (pos < range.from) {\n if (!index)\n return null;\n let next = this.ranges[--index];\n pos -= range.from - next.to;\n range = next;\n }\n while (assoc < 0 ? pos > range.to : pos >= range.to) {\n if (index == this.ranges.length - 1)\n return null;\n let next = this.ranges[++index];\n pos += next.from - range.to;\n range = next;\n }\n return pos;\n }\n /// @internal\n clipPos(pos) {\n if (pos >= this.range.from && pos < this.range.to)\n return pos;\n for (let range of this.ranges)\n if (range.to > pos)\n return Math.max(pos, range.from);\n return this.end;\n }\n /// Look at a code unit near the stream position. `.peek(0)` equals\n /// `.next`, `.peek(-1)` gives you the previous character, and so\n /// on.\n ///\n /// Note that looking around during tokenizing creates dependencies\n /// on potentially far-away content, which may reduce the\n /// effectiveness incremental parsing\u2014when looking forward\u2014or even\n /// cause invalid reparses when looking backward more than 25 code\n /// units, since the library does not track lookbehind.\n peek(offset) {\n let idx = this.chunkOff + offset, pos, result;\n if (idx >= 0 && idx < this.chunk.length) {\n pos = this.pos + offset;\n result = this.chunk.charCodeAt(idx);\n }\n else {\n let resolved = this.resolveOffset(offset, 1);\n if (resolved == null)\n return -1;\n pos = resolved;\n if (pos >= this.chunk2Pos && pos < this.chunk2Pos + this.chunk2.length) {\n result = this.chunk2.charCodeAt(pos - this.chunk2Pos);\n }\n else {\n let i = this.rangeIndex, range = this.range;\n while (range.to <= pos)\n range = this.ranges[++i];\n this.chunk2 = this.input.chunk(this.chunk2Pos = pos);\n if (pos + this.chunk2.length > range.to)\n this.chunk2 = this.chunk2.slice(0, range.to - pos);\n result = this.chunk2.charCodeAt(0);\n }\n }\n if (pos >= this.token.lookAhead)\n this.token.lookAhead = pos + 1;\n return result;\n }\n /// Accept a token. By default, the end of the token is set to the\n /// current stream position, but you can pass an offset (relative to\n /// the stream position) to change that.\n acceptToken(token, endOffset = 0) {\n let end = endOffset ? this.resolveOffset(endOffset, -1) : this.pos;\n if (end == null || end < this.token.start)\n throw new RangeError(\"Token end out of bounds\");\n this.token.value = token;\n this.token.end = end;\n }\n getChunk() {\n if (this.pos >= this.chunk2Pos && this.pos < this.chunk2Pos + this.chunk2.length) {\n let { chunk, chunkPos } = this;\n this.chunk = this.chunk2;\n this.chunkPos = this.chunk2Pos;\n this.chunk2 = chunk;\n this.chunk2Pos = chunkPos;\n this.chunkOff = this.pos - this.chunkPos;\n }\n else {\n this.chunk2 = this.chunk;\n this.chunk2Pos = this.chunkPos;\n let nextChunk = this.input.chunk(this.pos);\n let end = this.pos + nextChunk.length;\n this.chunk = end > this.range.to ? nextChunk.slice(0, this.range.to - this.pos) : nextChunk;\n this.chunkPos = this.pos;\n this.chunkOff = 0;\n }\n }\n readNext() {\n if (this.chunkOff >= this.chunk.length) {\n this.getChunk();\n if (this.chunkOff == this.chunk.length)\n return this.next = -1;\n }\n return this.next = this.chunk.charCodeAt(this.chunkOff);\n }\n /// Move the stream forward N (defaults to 1) code units. Returns\n /// the new value of [`next`](#lr.InputStream.next).\n advance(n = 1) {\n this.chunkOff += n;\n while (this.pos + n >= this.range.to) {\n if (this.rangeIndex == this.ranges.length - 1)\n return this.setDone();\n n -= this.range.to - this.pos;\n this.range = this.ranges[++this.rangeIndex];\n this.pos = this.range.from;\n }\n this.pos += n;\n if (this.pos >= this.token.lookAhead)\n this.token.lookAhead = this.pos + 1;\n return this.readNext();\n }\n setDone() {\n this.pos = this.chunkPos = this.end;\n this.range = this.ranges[this.rangeIndex = this.ranges.length - 1];\n this.chunk = \"\";\n return this.next = -1;\n }\n /// @internal\n reset(pos, token) {\n if (token) {\n this.token = token;\n token.start = pos;\n token.lookAhead = pos + 1;\n token.value = token.extended = -1;\n }\n else {\n this.token = nullToken;\n }\n if (this.pos != pos) {\n this.pos = pos;\n if (pos == this.end) {\n this.setDone();\n return this;\n }\n while (pos < this.range.from)\n this.range = this.ranges[--this.rangeIndex];\n while (pos >= this.range.to)\n this.range = this.ranges[++this.rangeIndex];\n if (pos >= this.chunkPos && pos < this.chunkPos + this.chunk.length) {\n this.chunkOff = pos - this.chunkPos;\n }\n else {\n this.chunk = \"\";\n this.chunkOff = 0;\n }\n this.readNext();\n }\n return this;\n }\n /// @internal\n read(from, to) {\n if (from >= this.chunkPos && to <= this.chunkPos + this.chunk.length)\n return this.chunk.slice(from - this.chunkPos, to - this.chunkPos);\n if (from >= this.chunk2Pos && to <= this.chunk2Pos + this.chunk2.length)\n return this.chunk2.slice(from - this.chunk2Pos, to - this.chunk2Pos);\n if (from >= this.range.from && to <= this.range.to)\n return this.input.read(from, to);\n let result = \"\";\n for (let r of this.ranges) {\n if (r.from >= to)\n break;\n if (r.to > from)\n result += this.input.read(Math.max(r.from, from), Math.min(r.to, to));\n }\n return result;\n }\n}\n/// @internal\nclass TokenGroup {\n constructor(data, id) {\n this.data = data;\n this.id = id;\n }\n token(input, stack) {\n let { parser } = stack.p;\n readToken(this.data, input, stack, this.id, parser.data, parser.tokenPrecTable);\n }\n}\nTokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;\n/// @hide\nclass LocalTokenGroup {\n constructor(data, precTable, elseToken) {\n this.precTable = precTable;\n this.elseToken = elseToken;\n this.data = typeof data == \"string\" ? decodeArray(data) : data;\n }\n token(input, stack) {\n let start = input.pos, skipped = 0;\n for (;;) {\n let atEof = input.next < 0, nextPos = input.resolveOffset(1, 1);\n readToken(this.data, input, stack, 0, this.data, this.precTable);\n if (input.token.value > -1)\n break;\n if (this.elseToken == null)\n return;\n if (!atEof)\n skipped++;\n if (nextPos == null)\n break;\n input.reset(nextPos, input.token);\n }\n if (skipped) {\n input.reset(start, input.token);\n input.acceptToken(this.elseToken, skipped);\n }\n }\n}\nLocalTokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;\n/// `@external tokens` declarations in the grammar should resolve to\n/// an instance of this class.\nclass ExternalTokenizer {\n /// Create a tokenizer. The first argument is the function that,\n /// given an input stream, scans for the types of tokens it\n /// recognizes at the stream's position, and calls\n /// [`acceptToken`](#lr.InputStream.acceptToken) when it finds\n /// one.\n constructor(\n /// @internal\n token, options = {}) {\n this.token = token;\n this.contextual = !!options.contextual;\n this.fallback = !!options.fallback;\n this.extend = !!options.extend;\n }\n}\n// Tokenizer data is stored a big uint16 array containing, for each\n// state:\n//\n// - A group bitmask, indicating what token groups are reachable from\n// this state, so that paths that can only lead to tokens not in\n// any of the current groups can be cut off early.\n//\n// - The position of the end of the state's sequence of accepting\n// tokens\n//\n// - The number of outgoing edges for the state\n//\n// - The accepting tokens, as (token id, group mask) pairs\n//\n// - The outgoing edges, as (start character, end character, state\n// index) triples, with end character being exclusive\n//\n// This function interprets that data, running through a stream as\n// long as new states with the a matching group mask can be reached,\n// and updating `input.token` when it matches a token.\nfunction readToken(data, input, stack, group, precTable, precOffset) {\n let state = 0, groupMask = 1 << group, { dialect } = stack.p.parser;\n scan: for (;;) {\n if ((groupMask & data[state]) == 0)\n break;\n let accEnd = data[state + 1];\n // Check whether this state can lead to a token in the current group\n // Accept tokens in this state, possibly overwriting\n // lower-precedence / shorter tokens\n for (let i = state + 3; i < accEnd; i += 2)\n if ((data[i + 1] & groupMask) > 0) {\n let term = data[i];\n if (dialect.allows(term) &&\n (input.token.value == -1 || input.token.value == term ||\n overrides(term, input.token.value, precTable, precOffset))) {\n input.acceptToken(term);\n break;\n }\n }\n let next = input.next, low = 0, high = data[state + 2];\n // Special case for EOF\n if (input.next < 0 && high > low && data[accEnd + high * 3 - 3] == 65535 /* Seq.End */ && data[accEnd + high * 3 - 3] == 65535 /* Seq.End */) {\n state = data[accEnd + high * 3 - 1];\n continue scan;\n }\n // Do a binary search on the state's edges\n for (; low < high;) {\n let mid = (low + high) >> 1;\n let index = accEnd + mid + (mid << 1);\n let from = data[index], to = data[index + 1] || 0x10000;\n if (next < from)\n high = mid;\n else if (next >= to)\n low = mid + 1;\n else {\n state = data[index + 2];\n input.advance();\n continue scan;\n }\n }\n break;\n }\n}\nfunction findOffset(data, start, term) {\n for (let i = start, next; (next = data[i]) != 65535 /* Seq.End */; i++)\n if (next == term)\n return i - start;\n return -1;\n}\nfunction overrides(token, prev, tableData, tableOffset) {\n let iPrev = findOffset(tableData, tableOffset, prev);\n return iPrev < 0 || findOffset(tableData, tableOffset, token) < iPrev;\n}\n\n// Environment variable used to control console output\nconst verbose = typeof process != \"undefined\" && process.env && /\\bparse\\b/.test(process.env.LOG);\nlet stackIDs = null;\nvar Safety;\n(function (Safety) {\n Safety[Safety[\"Margin\"] = 25] = \"Margin\";\n})(Safety || (Safety = {}));\nfunction cutAt(tree, pos, side) {\n let cursor = tree.cursor(IterMode.IncludeAnonymous);\n cursor.moveTo(pos);\n for (;;) {\n if (!(side < 0 ? cursor.childBefore(pos) : cursor.childAfter(pos)))\n for (;;) {\n if ((side < 0 ? cursor.to < pos : cursor.from > pos) && !cursor.type.isError)\n return side < 0 ? Math.max(0, Math.min(cursor.to - 1, pos - 25 /* Safety.Margin */))\n : Math.min(tree.length, Math.max(cursor.from + 1, pos + 25 /* Safety.Margin */));\n if (side < 0 ? cursor.prevSibling() : cursor.nextSibling())\n break;\n if (!cursor.parent())\n return side < 0 ? 0 : tree.length;\n }\n }\n}\nclass FragmentCursor {\n constructor(fragments, nodeSet) {\n this.fragments = fragments;\n this.nodeSet = nodeSet;\n this.i = 0;\n this.fragment = null;\n this.safeFrom = -1;\n this.safeTo = -1;\n this.trees = [];\n this.start = [];\n this.index = [];\n this.nextFragment();\n }\n nextFragment() {\n let fr = this.fragment = this.i == this.fragments.length ? null : this.fragments[this.i++];\n if (fr) {\n this.safeFrom = fr.openStart ? cutAt(fr.tree, fr.from + fr.offset, 1) - fr.offset : fr.from;\n this.safeTo = fr.openEnd ? cutAt(fr.tree, fr.to + fr.offset, -1) - fr.offset : fr.to;\n while (this.trees.length) {\n this.trees.pop();\n this.start.pop();\n this.index.pop();\n }\n this.trees.push(fr.tree);\n this.start.push(-fr.offset);\n this.index.push(0);\n this.nextStart = this.safeFrom;\n }\n else {\n this.nextStart = 1e9;\n }\n }\n // `pos` must be >= any previously given `pos` for this cursor\n nodeAt(pos) {\n if (pos < this.nextStart)\n return null;\n while (this.fragment && this.safeTo <= pos)\n this.nextFragment();\n if (!this.fragment)\n return null;\n for (;;) {\n let last = this.trees.length - 1;\n if (last < 0) { // End of tree\n this.nextFragment();\n return null;\n }\n let top = this.trees[last], index = this.index[last];\n if (index == top.children.length) {\n this.trees.pop();\n this.start.pop();\n this.index.pop();\n continue;\n }\n let next = top.children[index];\n let start = this.start[last] + top.positions[index];\n if (start > pos) {\n this.nextStart = start;\n return null;\n }\n if (next instanceof Tree) {\n if (start == pos) {\n if (start < this.safeFrom)\n return null;\n let end = start + next.length;\n if (end <= this.safeTo) {\n let lookAhead = next.prop(NodeProp.lookAhead);\n if (!lookAhead || end + lookAhead < this.fragment.to)\n return next;\n }\n }\n this.index[last]++;\n if (start + next.length >= Math.max(this.safeFrom, pos)) { // Enter this node\n this.trees.push(next);\n this.start.push(start);\n this.index.push(0);\n }\n }\n else {\n this.index[last]++;\n this.nextStart = start + next.length;\n }\n }\n }\n}\nclass TokenCache {\n constructor(parser, stream) {\n this.stream = stream;\n this.tokens = [];\n this.mainToken = null;\n this.actions = [];\n this.tokens = parser.tokenizers.map(_ => new CachedToken);\n }\n getActions(stack) {\n let actionIndex = 0;\n let main = null;\n let { parser } = stack.p, { tokenizers } = parser;\n let mask = parser.stateSlot(stack.state, 3 /* ParseState.TokenizerMask */);\n let context = stack.curContext ? stack.curContext.hash : 0;\n let lookAhead = 0;\n for (let i = 0; i < tokenizers.length; i++) {\n if (((1 << i) & mask) == 0)\n continue;\n let tokenizer = tokenizers[i], token = this.tokens[i];\n if (main && !tokenizer.fallback)\n continue;\n if (tokenizer.contextual || token.start != stack.pos || token.mask != mask || token.context != context) {\n this.updateCachedToken(token, tokenizer, stack);\n token.mask = mask;\n token.context = context;\n }\n if (token.lookAhead > token.end + 25 /* Safety.Margin */)\n lookAhead = Math.max(token.lookAhead, lookAhead);\n if (token.value != 0 /* Term.Err */) {\n let startIndex = actionIndex;\n if (token.extended > -1)\n actionIndex = this.addActions(stack, token.extended, token.end, actionIndex);\n actionIndex = this.addActions(stack, token.value, token.end, actionIndex);\n if (!tokenizer.extend) {\n main = token;\n if (actionIndex > startIndex)\n break;\n }\n }\n }\n while (this.actions.length > actionIndex)\n this.actions.pop();\n if (lookAhead)\n stack.setLookAhead(lookAhead);\n if (!main && stack.pos == this.stream.end) {\n main = new CachedToken;\n main.value = stack.p.parser.eofTerm;\n main.start = main.end = stack.pos;\n actionIndex = this.addActions(stack, main.value, main.end, actionIndex);\n }\n this.mainToken = main;\n return this.actions;\n }\n getMainToken(stack) {\n if (this.mainToken)\n return this.mainToken;\n let main = new CachedToken, { pos, p } = stack;\n main.start = pos;\n main.end = Math.min(pos + 1, p.stream.end);\n main.value = pos == p.stream.end ? p.parser.eofTerm : 0 /* Term.Err */;\n return main;\n }\n updateCachedToken(token, tokenizer, stack) {\n let start = this.stream.clipPos(stack.pos);\n tokenizer.token(this.stream.reset(start, token), stack);\n if (token.value > -1) {\n let { parser } = stack.p;\n for (let i = 0; i < parser.specialized.length; i++)\n if (parser.specialized[i] == token.value) {\n let result = parser.specializers[i](this.stream.read(token.start, token.end), stack);\n if (result >= 0 && stack.p.parser.dialect.allows(result >> 1)) {\n if ((result & 1) == 0 /* Specialize.Specialize */)\n token.value = result >> 1;\n else\n token.extended = result >> 1;\n break;\n }\n }\n }\n else {\n token.value = 0 /* Term.Err */;\n token.end = this.stream.clipPos(start + 1);\n }\n }\n putAction(action, token, end, index) {\n // Don't add duplicate actions\n for (let i = 0; i < index; i += 3)\n if (this.actions[i] == action)\n return index;\n this.actions[index++] = action;\n this.actions[index++] = token;\n this.actions[index++] = end;\n return index;\n }\n addActions(stack, token, end, index) {\n let { state } = stack, { parser } = stack.p, { data } = parser;\n for (let set = 0; set < 2; set++) {\n for (let i = parser.stateSlot(state, set ? 2 /* ParseState.Skip */ : 1 /* ParseState.Actions */);; i += 3) {\n if (data[i] == 65535 /* Seq.End */) {\n if (data[i + 1] == 1 /* Seq.Next */) {\n i = pair(data, i + 2);\n }\n else {\n if (index == 0 && data[i + 1] == 2 /* Seq.Other */)\n index = this.putAction(pair(data, i + 2), token, end, index);\n break;\n }\n }\n if (data[i] == token)\n index = this.putAction(pair(data, i + 1), token, end, index);\n }\n }\n return index;\n }\n}\nvar Rec;\n(function (Rec) {\n Rec[Rec[\"Distance\"] = 5] = \"Distance\";\n Rec[Rec[\"MaxRemainingPerStep\"] = 3] = \"MaxRemainingPerStep\";\n // When two stacks have been running independently long enough to\n // add this many elements to their buffers, prune one.\n Rec[Rec[\"MinBufferLengthPrune\"] = 500] = \"MinBufferLengthPrune\";\n Rec[Rec[\"ForceReduceLimit\"] = 10] = \"ForceReduceLimit\";\n // Once a stack reaches this depth (in .stack.length) force-reduce\n // it back to CutTo to avoid creating trees that overflow the stack\n // on recursive traversal.\n Rec[Rec[\"CutDepth\"] = 15000] = \"CutDepth\";\n Rec[Rec[\"CutTo\"] = 9000] = \"CutTo\";\n Rec[Rec[\"MaxLeftAssociativeReductionCount\"] = 300] = \"MaxLeftAssociativeReductionCount\";\n // The maximum number of non-recovering stacks to explore (to avoid\n // getting bogged down with exponentially multiplying stacks in\n // ambiguous content)\n Rec[Rec[\"MaxStackCount\"] = 12] = \"MaxStackCount\";\n})(Rec || (Rec = {}));\nclass Parse {\n constructor(parser, input, fragments, ranges) {\n this.parser = parser;\n this.input = input;\n this.ranges = ranges;\n this.recovering = 0;\n this.nextStackID = 0x2654; // \u2654, \u2655, \u2656, \u2657, \u2658, \u2659, \u2660, \u2661, \u2662, \u2663, \u2664, \u2665, \u2666, \u2667\n this.minStackPos = 0;\n this.reused = [];\n this.stoppedAt = null;\n this.lastBigReductionStart = -1;\n this.lastBigReductionSize = 0;\n this.bigReductionCount = 0;\n this.stream = new InputStream(input, ranges);\n this.tokens = new TokenCache(parser, this.stream);\n this.topTerm = parser.top[1];\n let { from } = ranges[0];\n this.stacks = [Stack.start(this, parser.top[0], from)];\n this.fragments = fragments.length && this.stream.end - from > parser.bufferLength * 4\n ? new FragmentCursor(fragments, parser.nodeSet) : null;\n }\n get parsedPos() {\n return this.minStackPos;\n }\n // Move the parser forward. This will process all parse stacks at\n // `this.pos` and try to advance them to a further position. If no\n // stack for such a position is found, it'll start error-recovery.\n //\n // When the parse is finished, this will return a syntax tree. When\n // not, it returns `null`.\n advance() {\n let stacks = this.stacks, pos = this.minStackPos;\n // This will hold stacks beyond `pos`.\n let newStacks = this.stacks = [];\n let stopped, stoppedTokens;\n // If a large amount of reductions happened with the same start\n // position, force the stack out of that production in order to\n // avoid creating a tree too deep to recurse through.\n // (This is an ugly kludge, because unfortunately there is no\n // straightforward, cheap way to check for this happening, due to\n // the history of reductions only being available in an\n // expensive-to-access format in the stack buffers.)\n if (this.bigReductionCount > 300 /* Rec.MaxLeftAssociativeReductionCount */ && stacks.length == 1) {\n let [s] = stacks;\n while (s.forceReduce() && s.stack.length && s.stack[s.stack.length - 2] >= this.lastBigReductionStart) { }\n this.bigReductionCount = this.lastBigReductionSize = 0;\n }\n // Keep advancing any stacks at `pos` until they either move\n // forward or can't be advanced. Gather stacks that can't be\n // advanced further in `stopped`.\n for (let i = 0; i < stacks.length; i++) {\n let stack = stacks[i];\n for (;;) {\n this.tokens.mainToken = null;\n if (stack.pos > pos) {\n newStacks.push(stack);\n }\n else if (this.advanceStack(stack, newStacks, stacks)) {\n continue;\n }\n else {\n if (!stopped) {\n stopped = [];\n stoppedTokens = [];\n }\n stopped.push(stack);\n let tok = this.tokens.getMainToken(stack);\n stoppedTokens.push(tok.value, tok.end);\n }\n break;\n }\n }\n if (!newStacks.length) {\n let finished = stopped && findFinished(stopped);\n if (finished)\n return this.stackToTree(finished);\n if (this.parser.strict) {\n if (verbose && stopped)\n console.log(\"Stuck with token \" + (this.tokens.mainToken ? this.parser.getName(this.tokens.mainToken.value) : \"none\"));\n throw new SyntaxError(\"No parse at \" + pos);\n }\n if (!this.recovering)\n this.recovering = 5 /* Rec.Distance */;\n }\n if (this.recovering && stopped) {\n let finished = this.stoppedAt != null && stopped[0].pos > this.stoppedAt ? stopped[0]\n : this.runRecovery(stopped, stoppedTokens, newStacks);\n if (finished)\n return this.stackToTree(finished.forceAll());\n }\n if (this.recovering) {\n let maxRemaining = this.recovering == 1 ? 1 : this.recovering * 3 /* Rec.MaxRemainingPerStep */;\n if (newStacks.length > maxRemaining) {\n newStacks.sort((a, b) => b.score - a.score);\n while (newStacks.length > maxRemaining)\n newStacks.pop();\n }\n if (newStacks.some(s => s.reducePos > pos))\n this.recovering--;\n }\n else if (newStacks.length > 1) {\n // Prune stacks that are in the same state, or that have been\n // running without splitting for a while, to avoid getting stuck\n // with multiple successful stacks running endlessly on.\n outer: for (let i = 0; i < newStacks.length - 1; i++) {\n let stack = newStacks[i];\n for (let j = i + 1; j < newStacks.length; j++) {\n let other = newStacks[j];\n if (stack.sameState(other) ||\n stack.buffer.length > 500 /* Rec.MinBufferLengthPrune */ && other.buffer.length > 500 /* Rec.MinBufferLengthPrune */) {\n if (((stack.score - other.score) || (stack.buffer.length - other.buffer.length)) > 0) {\n newStacks.splice(j--, 1);\n }\n else {\n newStacks.splice(i--, 1);\n continue outer;\n }\n }\n }\n }\n if (newStacks.length > 12 /* Rec.MaxStackCount */)\n newStacks.splice(12 /* Rec.MaxStackCount */, newStacks.length - 12 /* Rec.MaxStackCount */);\n }\n this.minStackPos = newStacks[0].pos;\n for (let i = 1; i < newStacks.length; i++)\n if (newStacks[i].pos < this.minStackPos)\n this.minStackPos = newStacks[i].pos;\n return null;\n }\n stopAt(pos) {\n if (this.stoppedAt != null && this.stoppedAt < pos)\n throw new RangeError(\"Can't move stoppedAt forward\");\n this.stoppedAt = pos;\n }\n // Returns an updated version of the given stack, or null if the\n // stack can't advance normally. When `split` and `stacks` are\n // given, stacks split off by ambiguous operations will be pushed to\n // `split`, or added to `stacks` if they move `pos` forward.\n advanceStack(stack, stacks, split) {\n let start = stack.pos, { parser } = this;\n let base = verbose ? this.stackID(stack) + \" -> \" : \"\";\n if (this.stoppedAt != null && start > this.stoppedAt)\n return stack.forceReduce() ? stack : null;\n if (this.fragments) {\n let strictCx = stack.curContext && stack.curContext.tracker.strict, cxHash = strictCx ? stack.curContext.hash : 0;\n for (let cached = this.fragments.nodeAt(start); cached;) {\n let match = this.parser.nodeSet.types[cached.type.id] == cached.type ? parser.getGoto(stack.state, cached.type.id) : -1;\n if (match > -1 && cached.length && (!strictCx || (cached.prop(NodeProp.contextHash) || 0) == cxHash)) {\n stack.useNode(cached, match);\n if (verbose)\n console.log(base + this.stackID(stack) + ` (via reuse of ${parser.getName(cached.type.id)})`);\n return true;\n }\n if (!(cached instanceof Tree) || cached.children.length == 0 || cached.positions[0] > 0)\n break;\n let inner = cached.children[0];\n if (inner instanceof Tree && cached.positions[0] == 0)\n cached = inner;\n else\n break;\n }\n }\n let defaultReduce = parser.stateSlot(stack.state, 4 /* ParseState.DefaultReduce */);\n if (defaultReduce > 0) {\n stack.reduce(defaultReduce);\n if (verbose)\n console.log(base + this.stackID(stack) + ` (via always-reduce ${parser.getName(defaultReduce & 65535 /* Action.ValueMask */)})`);\n return true;\n }\n if (stack.stack.length >= 15000 /* Rec.CutDepth */) {\n while (stack.stack.length > 9000 /* Rec.CutTo */ && stack.forceReduce()) { }\n }\n let actions = this.tokens.getActions(stack);\n for (let i = 0; i < actions.length;) {\n let action = actions[i++], term = actions[i++], end = actions[i++];\n let last = i == actions.length || !split;\n let localStack = last ? stack : stack.split();\n localStack.apply(action, term, end);\n if (verbose)\n console.log(base + this.stackID(localStack) + ` (via ${(action & 65536 /* Action.ReduceFlag */) == 0 ? \"shift\"\n : `reduce of ${parser.getName(action & 65535 /* Action.ValueMask */)}`} for ${parser.getName(term)} @ ${start}${localStack == stack ? \"\" : \", split\"})`);\n if (last)\n return true;\n else if (localStack.pos > start)\n stacks.push(localStack);\n else\n split.push(localStack);\n }\n return false;\n }\n // Advance a given stack forward as far as it will go. Returns the\n // (possibly updated) stack if it got stuck, or null if it moved\n // forward and was given to `pushStackDedup`.\n advanceFully(stack, newStacks) {\n let pos = stack.pos;\n for (;;) {\n if (!this.advanceStack(stack, null, null))\n return false;\n if (stack.pos > pos) {\n pushStackDedup(stack, newStacks);\n return true;\n }\n }\n }\n runRecovery(stacks, tokens, newStacks) {\n let finished = null, restarted = false;\n for (let i = 0; i < stacks.length; i++) {\n let stack = stacks[i], token = tokens[i << 1], tokenEnd = tokens[(i << 1) + 1];\n let base = verbose ? this.stackID(stack) + \" -> \" : \"\";\n if (stack.deadEnd) {\n if (restarted)\n continue;\n restarted = true;\n stack.restart();\n if (verbose)\n console.log(base + this.stackID(stack) + \" (restarted)\");\n let done = this.advanceFully(stack, newStacks);\n if (done)\n continue;\n }\n let force = stack.split(), forceBase = base;\n for (let j = 0; force.forceReduce() && j < 10 /* Rec.ForceReduceLimit */; j++) {\n if (verbose)\n console.log(forceBase + this.stackID(force) + \" (via force-reduce)\");\n let done = this.advanceFully(force, newStacks);\n if (done)\n break;\n if (verbose)\n forceBase = this.stackID(force) + \" -> \";\n }\n for (let insert of stack.recoverByInsert(token)) {\n if (verbose)\n console.log(base + this.stackID(insert) + \" (via recover-insert)\");\n this.advanceFully(insert, newStacks);\n }\n if (this.stream.end > stack.pos) {\n if (tokenEnd == stack.pos) {\n tokenEnd++;\n token = 0 /* Term.Err */;\n }\n stack.recoverByDelete(token, tokenEnd);\n if (verbose)\n console.log(base + this.stackID(stack) + ` (via recover-delete ${this.parser.getName(token)})`);\n pushStackDedup(stack, newStacks);\n }\n else if (!finished || finished.score < stack.score) {\n finished = stack;\n }\n }\n return finished;\n }\n // Convert the stack's buffer to a syntax tree.\n stackToTree(stack) {\n stack.close();\n return Tree.build({ buffer: StackBufferCursor.create(stack),\n nodeSet: this.parser.nodeSet,\n topID: this.topTerm,\n maxBufferLength: this.parser.bufferLength,\n reused: this.reused,\n start: this.ranges[0].from,\n length: stack.pos - this.ranges[0].from,\n minRepeatType: this.parser.minRepeatTerm });\n }\n stackID(stack) {\n let id = (stackIDs || (stackIDs = new WeakMap)).get(stack);\n if (!id)\n stackIDs.set(stack, id = String.fromCodePoint(this.nextStackID++));\n return id + stack;\n }\n}\nfunction pushStackDedup(stack, newStacks) {\n for (let i = 0; i < newStacks.length; i++) {\n let other = newStacks[i];\n if (other.pos == stack.pos && other.sameState(stack)) {\n if (newStacks[i].score < stack.score)\n newStacks[i] = stack;\n return;\n }\n }\n newStacks.push(stack);\n}\nclass Dialect {\n constructor(source, flags, disabled) {\n this.source = source;\n this.flags = flags;\n this.disabled = disabled;\n }\n allows(term) { return !this.disabled || this.disabled[term] == 0; }\n}\nconst id = x => x;\n/// Context trackers are used to track stateful context (such as\n/// indentation in the Python grammar, or parent elements in the XML\n/// grammar) needed by external tokenizers. You declare them in a\n/// grammar file as `@context exportName from \"module\"`.\n///\n/// Context values should be immutable, and can be updated (replaced)\n/// on shift or reduce actions.\n///\n/// The export used in a `@context` declaration should be of this\n/// type.\nclass ContextTracker {\n /// Define a context tracker.\n constructor(spec) {\n this.start = spec.start;\n this.shift = spec.shift || id;\n this.reduce = spec.reduce || id;\n this.reuse = spec.reuse || id;\n this.hash = spec.hash || (() => 0);\n this.strict = spec.strict !== false;\n }\n}\n/// Holds the parse tables for a given grammar, as generated by\n/// `lezer-generator`, and provides [methods](#common.Parser) to parse\n/// content with.\nclass LRParser extends Parser {\n /// @internal\n constructor(spec) {\n super();\n /// @internal\n this.wrappers = [];\n if (spec.version != 14 /* File.Version */)\n throw new RangeError(`Parser version (${spec.version}) doesn't match runtime version (${14 /* File.Version */})`);\n let nodeNames = spec.nodeNames.split(\" \");\n this.minRepeatTerm = nodeNames.length;\n for (let i = 0; i < spec.repeatNodeCount; i++)\n nodeNames.push(\"\");\n let topTerms = Object.keys(spec.topRules).map(r => spec.topRules[r][1]);\n let nodeProps = [];\n for (let i = 0; i < nodeNames.length; i++)\n nodeProps.push([]);\n function setProp(nodeID, prop, value) {\n nodeProps[nodeID].push([prop, prop.deserialize(String(value))]);\n }\n if (spec.nodeProps)\n for (let propSpec of spec.nodeProps) {\n let prop = propSpec[0];\n if (typeof prop == \"string\")\n prop = NodeProp[prop];\n for (let i = 1; i < propSpec.length;) {\n let next = propSpec[i++];\n if (next >= 0) {\n setProp(next, prop, propSpec[i++]);\n }\n else {\n let value = propSpec[i + -next];\n for (let j = -next; j > 0; j--)\n setProp(propSpec[i++], prop, value);\n i++;\n }\n }\n }\n this.nodeSet = new NodeSet(nodeNames.map((name, i) => NodeType.define({\n name: i >= this.minRepeatTerm ? undefined : name,\n id: i,\n props: nodeProps[i],\n top: topTerms.indexOf(i) > -1,\n error: i == 0,\n skipped: spec.skippedNodes && spec.skippedNodes.indexOf(i) > -1\n })));\n if (spec.propSources)\n this.nodeSet = this.nodeSet.extend(...spec.propSources);\n this.strict = false;\n this.bufferLength = DefaultBufferLength;\n let tokenArray = decodeArray(spec.tokenData);\n this.context = spec.context;\n this.specializerSpecs = spec.specialized || [];\n this.specialized = new Uint16Array(this.specializerSpecs.length);\n for (let i = 0; i < this.specializerSpecs.length; i++)\n this.specialized[i] = this.specializerSpecs[i].term;\n this.specializers = this.specializerSpecs.map(getSpecializer);\n this.states = decodeArray(spec.states, Uint32Array);\n this.data = decodeArray(spec.stateData);\n this.goto = decodeArray(spec.goto);\n this.maxTerm = spec.maxTerm;\n this.tokenizers = spec.tokenizers.map(value => typeof value == \"number\" ? new TokenGroup(tokenArray, value) : value);\n this.topRules = spec.topRules;\n this.dialects = spec.dialects || {};\n this.dynamicPrecedences = spec.dynamicPrecedences || null;\n this.tokenPrecTable = spec.tokenPrec;\n this.termNames = spec.termNames || null;\n this.maxNode = this.nodeSet.types.length - 1;\n this.dialect = this.parseDialect();\n this.top = this.topRules[Object.keys(this.topRules)[0]];\n }\n createParse(input, fragments, ranges) {\n let parse = new Parse(this, input, fragments, ranges);\n for (let w of this.wrappers)\n parse = w(parse, input, fragments, ranges);\n return parse;\n }\n /// Get a goto table entry @internal\n getGoto(state, term, loose = false) {\n let table = this.goto;\n if (term >= table[0])\n return -1;\n for (let pos = table[term + 1];;) {\n let groupTag = table[pos++], last = groupTag & 1;\n let target = table[pos++];\n if (last && loose)\n return target;\n for (let end = pos + (groupTag >> 1); pos < end; pos++)\n if (table[pos] == state)\n return target;\n if (last)\n return -1;\n }\n }\n /// Check if this state has an action for a given terminal @internal\n hasAction(state, terminal) {\n let data = this.data;\n for (let set = 0; set < 2; set++) {\n for (let i = this.stateSlot(state, set ? 2 /* ParseState.Skip */ : 1 /* ParseState.Actions */), next;; i += 3) {\n if ((next = data[i]) == 65535 /* Seq.End */) {\n if (data[i + 1] == 1 /* Seq.Next */)\n next = data[i = pair(data, i + 2)];\n else if (data[i + 1] == 2 /* Seq.Other */)\n return pair(data, i + 2);\n else\n break;\n }\n if (next == terminal || next == 0 /* Term.Err */)\n return pair(data, i + 1);\n }\n }\n return 0;\n }\n /// @internal\n stateSlot(state, slot) {\n return this.states[(state * 6 /* ParseState.Size */) + slot];\n }\n /// @internal\n stateFlag(state, flag) {\n return (this.stateSlot(state, 0 /* ParseState.Flags */) & flag) > 0;\n }\n /// @internal\n validAction(state, action) {\n return !!this.allActions(state, a => a == action ? true : null);\n }\n /// @internal\n allActions(state, action) {\n let deflt = this.stateSlot(state, 4 /* ParseState.DefaultReduce */);\n let result = deflt ? action(deflt) : undefined;\n for (let i = this.stateSlot(state, 1 /* ParseState.Actions */); result == null; i += 3) {\n if (this.data[i] == 65535 /* Seq.End */) {\n if (this.data[i + 1] == 1 /* Seq.Next */)\n i = pair(this.data, i + 2);\n else\n break;\n }\n result = action(pair(this.data, i + 1));\n }\n return result;\n }\n /// Get the states that can follow this one through shift actions or\n /// goto jumps. @internal\n nextStates(state) {\n let result = [];\n for (let i = this.stateSlot(state, 1 /* ParseState.Actions */);; i += 3) {\n if (this.data[i] == 65535 /* Seq.End */) {\n if (this.data[i + 1] == 1 /* Seq.Next */)\n i = pair(this.data, i + 2);\n else\n break;\n }\n if ((this.data[i + 2] & (65536 /* Action.ReduceFlag */ >> 16)) == 0) {\n let value = this.data[i + 1];\n if (!result.some((v, i) => (i & 1) && v == value))\n result.push(this.data[i], value);\n }\n }\n return result;\n }\n /// Configure the parser. Returns a new parser instance that has the\n /// given settings modified. Settings not provided in `config` are\n /// kept from the original parser.\n configure(config) {\n // Hideous reflection-based kludge to make it easy to create a\n // slightly modified copy of a parser.\n let copy = Object.assign(Object.create(LRParser.prototype), this);\n if (config.props)\n copy.nodeSet = this.nodeSet.extend(...config.props);\n if (config.top) {\n let info = this.topRules[config.top];\n if (!info)\n throw new RangeError(`Invalid top rule name ${config.top}`);\n copy.top = info;\n }\n if (config.tokenizers)\n copy.tokenizers = this.tokenizers.map(t => {\n let found = config.tokenizers.find(r => r.from == t);\n return found ? found.to : t;\n });\n if (config.specializers) {\n copy.specializers = this.specializers.slice();\n copy.specializerSpecs = this.specializerSpecs.map((s, i) => {\n let found = config.specializers.find(r => r.from == s.external);\n if (!found)\n return s;\n let spec = Object.assign(Object.assign({}, s), { external: found.to });\n copy.specializers[i] = getSpecializer(spec);\n return spec;\n });\n }\n if (config.contextTracker)\n copy.context = config.contextTracker;\n if (config.dialect)\n copy.dialect = this.parseDialect(config.dialect);\n if (config.strict != null)\n copy.strict = config.strict;\n if (config.wrap)\n copy.wrappers = copy.wrappers.concat(config.wrap);\n if (config.bufferLength != null)\n copy.bufferLength = config.bufferLength;\n return copy;\n }\n /// Tells you whether any [parse wrappers](#lr.ParserConfig.wrap)\n /// are registered for this parser.\n hasWrappers() {\n return this.wrappers.length > 0;\n }\n /// Returns the name associated with a given term. This will only\n /// work for all terms when the parser was generated with the\n /// `--names` option. By default, only the names of tagged terms are\n /// stored.\n getName(term) {\n return this.termNames ? this.termNames[term] : String(term <= this.maxNode && this.nodeSet.types[term].name || term);\n }\n /// The eof term id is always allocated directly after the node\n /// types. @internal\n get eofTerm() { return this.maxNode + 1; }\n /// The type of top node produced by the parser.\n get topNode() { return this.nodeSet.types[this.top[1]]; }\n /// @internal\n dynamicPrecedence(term) {\n let prec = this.dynamicPrecedences;\n return prec == null ? 0 : prec[term] || 0;\n }\n /// @internal\n parseDialect(dialect) {\n let values = Object.keys(this.dialects), flags = values.map(() => false);\n if (dialect)\n for (let part of dialect.split(\" \")) {\n let id = values.indexOf(part);\n if (id >= 0)\n flags[id] = true;\n }\n let disabled = null;\n for (let i = 0; i < values.length; i++)\n if (!flags[i]) {\n for (let j = this.dialects[values[i]], id; (id = this.data[j++]) != 65535 /* Seq.End */;)\n (disabled || (disabled = new Uint8Array(this.maxTerm + 1)))[id] = 1;\n }\n return new Dialect(dialect, flags, disabled);\n }\n /// Used by the output of the parser generator. Not available to\n /// user code. @hide\n static deserialize(spec) {\n return new LRParser(spec);\n }\n}\nfunction pair(data, off) { return data[off] | (data[off + 1] << 16); }\nfunction findFinished(stacks) {\n let best = null;\n for (let stack of stacks) {\n let stopped = stack.p.stoppedAt;\n if ((stack.pos == stack.p.stream.end || stopped != null && stack.pos > stopped) &&\n stack.p.parser.stateFlag(stack.state, 2 /* StateFlag.Accepting */) &&\n (!best || best.score < stack.score))\n best = stack;\n }\n return best;\n}\nfunction getSpecializer(spec) {\n if (spec.external) {\n let mask = spec.extend ? 1 /* Specialize.Extend */ : 0 /* Specialize.Specialize */;\n return (value, stack) => (spec.external(value, stack) << 1) | mask;\n }\n return spec.get;\n}\n\nexport { ContextTracker, ExternalTokenizer, InputStream, LRParser, LocalTokenGroup, Stack };\n", "// This file was generated by lezer-generator. You probably shouldn't edit it.\nimport { LRParser } from \"@lezer/lr\";\nexport const parser = LRParser.deserialize({\n version: 14,\n states: \"%QOVQPOOOOQO'#C_'#C_O_QQO'#C^OOQO'#DO'#DOOvQQO'#C|OOQO'#DR'#DROVQPO'#CuOOQO'#C}'#C}QOQPOOOOQO'#C`'#C`O!UQQO,58xO!dQPO,59VOVQPO,59]OVQPO,59_O!iQPO,59hO!nQQO,59aOOQO'#DQ'#DQOOQO1G.d1G.dO!UQQO1G.qO!yQQO1G.wOOQO1G.y1G.yOOQO'#Cw'#CwOOQO1G/S1G/SOOQO1G.{1G.{O#[QPO'#CnO#dQPO7+$]O!UQQO'#CxO#iQPO,59YOOQO<<Gw<<GwOOQO,59d,59dOOQO-E6v-E6v\",\n stateData: \"#q~OoOS~OsPOvUO~OTXOUXOVXOWXOXXOYXO`ZO~Of[Oh]Oj^OmpX~OZ`O[`O]`O^`O~OabO~OseO~Of[Oh]OwgO~Oh]Ofeijeimeiwei~OcjOdbX~OdlO~OcjOdba~O\",\n goto: \"#YvPPw}!TPPPPPPPPPPwPP!WPP!ZP!ZP!aP!g!jPPP!p!s!aP#P!aXROU[]XQOU[]RYQRibXTOU[]XVOU[]Rf^QkhRnkRWOQSOQ_UQc[Rd]QaYQhbRmj\",\n nodeNames: \"\u26A0 Filter ColumnValueExpression Column Operator Eq NotEq Gt Lt Starts Ends Number String True False ColumnSetExpression In LBrack Values Comma RBrack AndExpression And OrExpression Or ParenthesizedExpression As FilterName\",\n maxTerm: 39,\n skippedNodes: [0],\n repeatNodeCount: 1,\n tokenData: \"6p~RnXY#PYZ#P]^#Ppq#Pqr#brs#mxy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R#S%n#T#o%nR.bWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#b%n#b#c.z#c#o%nR/RU`QsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR/jWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#f%n#f#g0S#g#o%nR0ZUhQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR0rWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#h%n#h#i1[#i#o%nR1aVsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#U1v#U#o%nR1{WsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#f%n#f#g2e#g#o%nR2jWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#h%n#h#i3S#i#o%nR3XWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#g%n#g#h3q#h#o%nR3xUXQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR4aWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#f%n#f#g4y#g#o%nR5OWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#i%n#i#j5h#j#o%nR5mWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#X%n#X#Y6V#Y#o%nR6^U]QsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%n\",\n tokenizers: [0, 1],\n topRules: {\"Filter\":[0,1]},\n tokenPrec: 0\n})\n", "import { Tree } from \"@lezer/common\";\nimport {\n Filter,\n FilterCombinatorOp,\n MultipleValueFilterClauseOp,\n SingleValueFilterClauseOp,\n} from \"@vuu-ui/vuu-filter-types\";\nimport {\n isMultiClauseFilter,\n isMultiValueFilter,\n isSingleValueFilter,\n} from \"@vuu-ui/vuu-utils\";\n\nclass FilterExpression {\n public name: string | undefined;\n #filter: Partial<Filter> | undefined = undefined;\n\n setFilterCombinatorOp(op: string, filter = this.#filter) {\n if (isMultiClauseFilter(filter) && filter.op === op) {\n return;\n } else {\n this.#filter = {\n op: op as FilterCombinatorOp,\n filters: [this.#filter as Filter],\n };\n }\n }\n\n add(filter: Partial<Filter>) {\n if (this.#filter === undefined) {\n this.#filter = filter;\n } else if (isMultiClauseFilter(this.#filter)) {\n this.#filter.filters.push(filter as Filter);\n } else {\n throw Error(`Invalid filter passed to FilterExpression`);\n }\n }\n\n setColumn(column: string, filter = this.#filter) {\n if (isMultiClauseFilter(filter)) {\n const target = filter.filters.at(-1);\n if (target) {\n this.setColumn(column, target);\n }\n } else if (filter) {\n filter.column = column;\n }\n }\n setOp(value: string, filter = this.#filter) {\n if (isMultiClauseFilter(filter)) {\n const target = filter.filters.at(-1);\n if (target) {\n this.setOp(value, target);\n }\n } else if (filter) {\n filter.op = value as\n | SingleValueFilterClauseOp\n | MultipleValueFilterClauseOp;\n }\n }\n setValue(value: string | number | boolean, filter = this.#filter) {\n if (isMultiClauseFilter(filter)) {\n const target = filter.filters.at(-1);\n if (target) {\n this.setValue(value, target);\n }\n } else if (isMultiValueFilter(filter)) {\n filter.values ??= [];\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n filter.values.push(value);\n } else if (isSingleValueFilter(filter)) {\n filter.value = value;\n }\n }\n\n toJSON(filter = this.#filter) {\n if (this.name) {\n return {\n ...filter,\n name: this.name,\n };\n } else {\n return filter;\n }\n }\n}\n\nexport const walkTree = (tree: Tree, source: string) => {\n const filterExpression = new FilterExpression();\n const cursor = tree.cursor();\n do {\n const { name, from, to } = cursor;\n switch (name) {\n case \"ColumnValueExpression\":\n filterExpression.add({});\n break;\n case \"ColumnSetExpression\":\n filterExpression.add({ op: \"in\" });\n break;\n\n case \"Or\":\n case \"And\":\n filterExpression.setFilterCombinatorOp(source.substring(from, to));\n break;\n\n case \"Column\":\n filterExpression.setColumn(source.substring(from, to));\n break;\n\n case \"Operator\":\n filterExpression.setOp(source.substring(from, to));\n break;\n\n case \"String\":\n filterExpression.setValue(source.substring(from + 1, to - 1));\n break;\n\n case \"Number\":\n filterExpression.setValue(parseFloat(source.substring(from, to)));\n break;\n\n case \"True\":\n filterExpression.setValue(true);\n break;\n\n case \"False\":\n filterExpression.setValue(false);\n break;\n\n case \"FilterName\":\n filterExpression.name = source.substring(from, to);\n break;\n\n default:\n }\n } while (cursor.next());\n\n return filterExpression.toJSON();\n};\n", "import { Filter } from \"@vuu-ui/vuu-filter-types\";\nimport { parser } from \"./generated/filter-parser\";\nimport { walkTree } from \"./FilterTreeWalker\";\n\nconst strictParser = parser.configure({ strict: true });\n\nexport const parseFilter = (filterQuery: string): Filter => {\n const parseTree = strictParser.parse(filterQuery);\n const filter = walkTree(parseTree, filterQuery) as Filter;\n return filter;\n};\n", "import {\n LanguageSupport,\n LRLanguage,\n styleTags,\n tags as tag,\n} from \"@vuu-ui/vuu-codemirror\";\nimport { parser } from \"@vuu-ui/vuu-filter-parser\";\n\nconst filterLanguage = LRLanguage.define({\n name: \"VuuFilterQuery\",\n parser: parser.configure({\n props: [\n styleTags({\n Identifier: tag.variableName,\n String: tag.string,\n Or: tag.emphasis,\n Operator: tag.operator,\n }),\n ],\n }),\n});\n\nexport const filterLanguageSupport = () => {\n return new LanguageSupport(filterLanguage);\n};\n", "import {\n HighlightStyle,\n syntaxHighlighting,\n tags,\n} from \"@vuu-ui/vuu-codemirror\";\n\nconst myHighlightStyle = HighlightStyle.define([\n { tag: tags.variableName, color: \"var(--vuuFilterEditor-variableColor)\" },\n { tag: tags.comment, color: \"green\", fontStyle: \"italic\" },\n]);\n\nexport const vuuHighlighting = syntaxHighlighting(myHighlightStyle);\n", "import { EditorView } from \"@vuu-ui/vuu-codemirror\";\n\nexport const vuuTheme = EditorView.theme(\n {\n \"&\": {\n color: \"var(--vuuFilterEditor-color)\",\n backgroundColor: \"var(--vuuFilterEditor-background)\",\n fontSize: \"var(--vuuFilterEditor-fontSize)\",\n },\n \".cm-content\": {\n caretColor: \"var(--vuuFilterEditor-cursorColor)\",\n padding: 0,\n },\n \".cm-line\": {\n lineHeight: \"var(--vuuFilterEditor-lineHeight)\",\n },\n \"&.cm-focused .cm-cursor\": {\n borderLeftColor: \"var(--vuuFilterEditor-cursorColor)\",\n },\n \"&.cm-focused .cm-selectionBackground, ::selection\": {\n backgroundColor: \"var(--vuuFilterEditor-selectionBackground)\",\n },\n \".cm-selectionBackground, ::selection\": {\n backgroundColor: \"var(--vuuFilterEditor-selectionBackground)\",\n },\n \".cm-scroller\": {\n fontFamily: \"var(--vuuFilterEditor-fontFamily)\",\n },\n \".cm-tooltip\": {\n background: \"var(--vuuFilterEditor-tooltipBackground)\",\n border: \"var(--vuuFilterEditor-tooltipBorder)\",\n borderRadius: \"4px\",\n boxShadow: \"var(--vuuFilterEditor-tooltipElevation)\",\n \"&.cm-tooltip-autocomplete > ul\": {\n fontFamily: \"var(--vuuFilterEditor-fontFamily)\",\n fontSize: \"var(--vuuFilterEditor-fontSize)\",\n maxHeight: \"240px\",\n },\n \"&.cm-tooltip-autocomplete > ul > li\": {\n alignItems: \"center\",\n display: \"flex\",\n height: \"var(--vuuFilterEditor-suggestion-height)\",\n padding: \"0 3px\",\n lineHeight: \"var(--vuuFilterEditor-suggestion-height)\",\n },\n \"&.cm-tooltip-autocomplete li[aria-selected]\": {\n background: \"var(--vuuFilterEditor-suggestion-selectedBackground)\",\n color: \"var(--vuuFilterEditor-suggestion-selectedColor)\",\n },\n },\n \".cm-completionIcon\": {\n height: \"18px\",\n flex: \"0 0 16px\",\n },\n \".cm-completionLabel\": {\n flex: \"1 1 auto\",\n },\n \".cm-completionIcon-filter\": {\n position: \"relative\",\n \"&:after\": {\n background: \"var(--salt-text-secondary-foreground)\",\n content: \"''\",\n \"-webkit-mask\": \"var(--svg-filter) center center/13px 13px\",\n \"-webkit-mask-repeat\": \"no-repeat\",\n position: \"absolute\",\n height: \"18px\",\n left: \"0px\",\n top: \"0px\",\n width: \"16px\",\n },\n },\n },\n { dark: false }\n);\n", "import {\n CompletionContext,\n CompletionSource,\n EditorState,\n getNodeByName,\n getValue,\n SyntaxNode,\n syntaxTree,\n} from \"@vuu-ui/vuu-codemirror\";\nimport { Filter } from \"@vuu-ui/vuu-filter-types\";\nimport { MutableRefObject, useCallback } from \"react\";\nimport {\n IFilterSuggestionProvider,\n SuggestionType,\n} from \"./useCodeMirrorEditor\";\n\nexport type FilterSubmissionMode = \"and\" | \"or\" | \"replace\" | \"tab\";\n\nexport type ApplyCompletion = (mode?: FilterSubmissionMode) => void;\n\nconst getOperator = (node: SyntaxNode, state: EditorState) => {\n let maybeColumnNode = node.prevSibling || node.parent;\n while (\n maybeColumnNode &&\n ![\"Column\", \"Operator\", \"In\"].includes(maybeColumnNode.name)\n ) {\n maybeColumnNode = maybeColumnNode.prevSibling || maybeColumnNode.parent;\n }\n if (maybeColumnNode?.name === \"In\" || maybeColumnNode?.name === \"Operator\") {\n return getValue(maybeColumnNode, state);\n } else {\n return undefined;\n }\n};\n\n// Operators that are more than a single character in length may incur partial matches\n// TODO need to check that previous token is a column\nconst getPartialOperator = (\n maybeOperatorNode: SyntaxNode,\n state: EditorState,\n columnName?: string\n) => {\n const value = getValue(maybeOperatorNode, state);\n if (columnName === undefined || value === columnName) {\n return;\n }\n if (\n [\"contains\", \"ends\", \"starts\"].some((val) =>\n val.startsWith(value.toLowerCase())\n )\n ) {\n return value;\n } else {\n return undefined;\n }\n};\n\nconst getClauseOperator = (node: SyntaxNode, state: EditorState) => {\n let maybeTargetNode = node.prevSibling || node.parent || node.lastChild;\n while (maybeTargetNode && maybeTargetNode.name === \"\u26A0\")\n maybeTargetNode = maybeTargetNode.prevSibling;\n if (maybeTargetNode && [\"As\", \"Or\", \"And\"].includes(maybeTargetNode.name)) {\n return getValue(maybeTargetNode, state);\n } else {\n return undefined;\n }\n};\n\nconst getFilterName = (node: SyntaxNode, state: EditorState) => {\n if (node.name === \"FilterName\") {\n return getValue(node, state);\n } else {\n let maybeTargetNode = node.prevSibling || node.parent || node.lastChild;\n while (maybeTargetNode && maybeTargetNode.name !== \"FilterName\")\n maybeTargetNode = maybeTargetNode.prevSibling;\n if (maybeTargetNode && maybeTargetNode.name === \"FilterName\") {\n return getValue(node, state);\n }\n }\n};\n\nconst getColumnName = (\n node: SyntaxNode,\n state: EditorState\n): string | undefined => {\n const prevNode = node.prevSibling;\n if (prevNode?.name === \"Column\") {\n return getValue(prevNode, state);\n } else if (prevNode?.name === \"Operator\") {\n return getColumnName(prevNode, state);\n }\n};\n\nconst getSetValues = (node: SyntaxNode, state: EditorState): string[] => {\n let maybeTargetNode = node.lastChild;\n const values: string[] = [];\n while (maybeTargetNode && maybeTargetNode.name !== \"In\") {\n const value = getValue(maybeTargetNode, state);\n if (value) {\n values.push(value);\n } else {\n break;\n }\n maybeTargetNode = maybeTargetNode.prevSibling;\n }\n return values;\n};\nexport const FilterlNamedTerms: readonly string[] = [\n \"Filter\",\n \"ParenthesizedExpression\",\n \"AndExpression\",\n \"OrExpression\",\n \"ColumnValueExpression\",\n \"ColumnSetExpression\",\n \"FilterName\",\n \"Column\",\n \"Operator\",\n \"Values\",\n \"Number\",\n \"String\",\n];\nexport const lastNamedChild = (node: SyntaxNode): SyntaxNode | null => {\n let { lastChild } = node;\n while (lastChild && !FilterlNamedTerms.includes(lastChild.name)) {\n lastChild = lastChild.prevSibling;\n console.log(lastChild?.name);\n }\n return lastChild;\n};\n\nexport const useAutoComplete = (\n suggestionProvider: IFilterSuggestionProvider,\n onSubmit: MutableRefObject<ApplyCompletion>,\n existingFilter?: Filter\n) => {\n const makeSuggestions = useCallback(\n async (\n context: CompletionContext,\n suggestionType: SuggestionType,\n optionalArgs: {\n columnName?: string;\n existingFilter?: Filter;\n filterName?: string;\n operator?: string;\n quoted?: boolean;\n onSubmit?: () => void;\n selection?: string[];\n startsWith?: string;\n } = {}\n ) => {\n const { startsWith = \"\" } = optionalArgs;\n const options = await suggestionProvider.getSuggestions(\n suggestionType,\n optionalArgs\n );\n return { from: context.pos - startsWith.length, options };\n },\n [suggestionProvider]\n );\n\n return useCallback(\n async (context: CompletionContext) => {\n const { state, pos } = context;\n const word = context.matchBefore(/\\w*/) ?? {\n from: 0,\n to: 0,\n text: undefined,\n };\n\n const tree = syntaxTree(state);\n const nodeBefore = tree.resolveInner(pos, -1);\n console.log({ nodeBeforeName: nodeBefore.name });\n\n switch (nodeBefore.name) {\n case \"Filter\":\n if (context.pos === 0) {\n return makeSuggestions(context, \"column\");\n } else {\n const clauseOperator = getClauseOperator(nodeBefore, state);\n if (clauseOperator === \"as\") {\n return makeSuggestions(context, \"name\");\n } else {\n const filterName = getFilterName(nodeBefore, state);\n return makeSuggestions(context, \"save\", {\n onSubmit: onSubmit.current,\n existingFilter,\n filterName,\n });\n }\n }\n\n case \"String\":\n {\n // we only encounter a string as the right hand operand of a conditional expression\n const operator = getOperator(nodeBefore, state);\n const columnName = getColumnName(nodeBefore, state);\n // are we inside the string or immediately after it\n const { from, to } = nodeBefore;\n if (to - from === 2 && context.pos === from + 1) {\n // We are in an empty string, i.e between two quotes\n if (columnName && operator) {\n return makeSuggestions(context, \"columnValue\", {\n columnName,\n operator,\n quoted: true,\n startsWith: word.text,\n });\n }\n } else {\n console.log(\n `we have a string, column is ${columnName} ${from} ${to}`\n );\n }\n }\n break;\n\n case \"As\":\n return makeSuggestions(context, \"name\");\n\n case \"FilterName\":\n return makeSuggestions(context, \"save\", {\n onSubmit: onSubmit.current,\n existingFilter,\n filterName: getFilterName(nodeBefore, state),\n });\n\n case \"Column\": {\n const columnName = getValue(nodeBefore, state);\n const isPartialMatch = await suggestionProvider.isPartialMatch(\n \"column\",\n undefined,\n columnName\n );\n if (isPartialMatch) {\n return makeSuggestions(context, \"column\", {\n startsWith: columnName,\n });\n } else {\n return makeSuggestions(context, \"operator\", { columnName });\n }\n }\n\n case \"\u26A0\": {\n const columnName = getNodeByName(nodeBefore, state);\n const operator = getOperator(nodeBefore, state);\n // TODO check if we're mnatching a partial jojn operator\n const partialOperator = operator\n ? undefined\n : getPartialOperator(nodeBefore, state, columnName);\n\n if (partialOperator) {\n return makeSuggestions(context, \"operator\", {\n columnName,\n startsWith: partialOperator,\n });\n } else {\n return makeSuggestions(context, \"columnValue\", {\n columnName,\n operator,\n startsWith: word.text,\n });\n }\n }\n\n case \"Identifier\":\n {\n const clauseOperator = getClauseOperator(nodeBefore, state);\n if (clauseOperator === \"as\") {\n return {\n from: context.pos,\n options: [\n {\n label: \"press ENTER to apply filter and save\",\n apply: () => onSubmit.current(),\n boost: 5,\n },\n ],\n };\n }\n }\n break;\n case \"ColumnSetExpression\":\n case \"Values\": {\n const columnName = getNodeByName(nodeBefore, state);\n const selection = getSetValues(nodeBefore, state);\n return makeSuggestions(context, \"columnValue\", {\n columnName,\n selection,\n });\n }\n case \"Comma\":\n case \"LBrack\": {\n const columnName = getNodeByName(nodeBefore, state) as string;\n return makeSuggestions(context, \"columnValue\", { columnName });\n }\n\n case \"ColumnValueExpression\":\n {\n const lastToken = nodeBefore.lastChild?.prevSibling;\n if (lastToken?.name === \"Column\") {\n return makeSuggestions(context, \"operator\", {\n columnName: getNodeByName(nodeBefore, state),\n });\n } else if (lastToken?.name === \"Operator\") {\n return makeSuggestions(context, \"columnValue\", {\n columnName: getNodeByName(lastToken, state),\n operator: getValue(lastToken, state),\n });\n }\n }\n break;\n\n case \"In\": {\n return {\n from: context.pos,\n options: [{ label: \"[\", apply: \" [\", type: \"text\" }],\n };\n }\n\n case \"Eq\": {\n return makeSuggestions(context, \"columnValue\", {\n columnName: getNodeByName(nodeBefore, state),\n });\n }\n\n case \"AndExpression\":\n case \"OrExpression\": {\n return makeSuggestions(context, \"column\");\n }\n\n default:\n }\n },\n [existingFilter, makeSuggestions, onSubmit, suggestionProvider]\n ) as CompletionSource;\n};\n", "import {\n asNameSuggestion,\n booleanJoinSuggestions,\n Completion,\n getNamePrompt,\n numericOperators,\n stringOperators,\n toSuggestions,\n} from \"@vuu-ui/vuu-codemirror\";\nimport {\n getTypeaheadParams,\n SuggestionFetcher,\n useTypeaheadSuggestions,\n} from \"@vuu-ui/vuu-data-react\";\nimport { ColumnDescriptor } from \"@vuu-ui/vuu-table-types\";\nimport { Filter } from \"@vuu-ui/vuu-filter-types\";\nimport { VuuTable } from \"@vuu-ui/vuu-protocol-types\";\n// import { isMappedValueTypeRenderer, isTypeDescriptor } from \"@vuu-ui/vuu-utils\";\nimport { useCallback, useRef } from \"react\";\nimport { filterInfo } from \"./filterInfo\";\nimport {\n IFilterSuggestionProvider,\n SuggestionType,\n} from \"./useCodeMirrorEditor\";\nimport { ApplyCompletion } from \"./useFilterAutoComplete\";\n\nconst NO_NAMED_FILTERS = [] as Completion[];\nconst NONE = {};\n\nconst saveAsTab = (onSubmit: ApplyCompletion) => [\n {\n label: \"Press ENTER to create TAB\",\n apply: () => onSubmit(\"tab\"),\n boost: 6,\n },\n];\n\nconst makeSaveOrExtendSuggestions = (\n onSubmit: ApplyCompletion,\n existingFilter?: Filter,\n withJoinSuggestions = true\n) => {\n const result = existingFilter\n ? ([\n {\n label: \"REPLACE existing filter\",\n apply: () => onSubmit(\"replace\"),\n boost: 8,\n },\n {\n label: \"AND existing filter\",\n apply: () => onSubmit(\"and\"),\n boost: 7,\n },\n {\n label: \"OR existing filter\",\n apply: () => onSubmit(\"or\"),\n boost: 7,\n },\n ] as Completion[])\n : ([\n {\n label: \"Press ENTER to submit\",\n apply: () => onSubmit(),\n boost: 6,\n },\n ] as Completion[]);\n\n return withJoinSuggestions\n ? result.concat(booleanJoinSuggestions).concat(asNameSuggestion)\n : result;\n};\n\nconst promptToSaveOrExtend = (\n onSubmit: ApplyCompletion,\n existingFilter?: Filter\n) => makeSaveOrExtendSuggestions(onSubmit, existingFilter, true);\n\nconst promptToSave = (onSubmit: ApplyCompletion) =>\n makeSaveOrExtendSuggestions(onSubmit, undefined);\n\nconst getSaveSuggestions = ({\n existingFilter,\n filterName,\n onSubmit,\n saveOptions,\n}: {\n existingFilter?: Filter;\n filterName?: string;\n onSubmit: () => void;\n saveOptions: FilterSaveOptions;\n}) => {\n const includeTabSuggestion = filterName && saveOptions.allowSaveAsTab;\n const result = existingFilter\n ? promptToSaveOrExtend(onSubmit, existingFilter)\n : promptToSave(onSubmit);\n\n if (includeTabSuggestion) {\n return result.concat(saveAsTab(onSubmit));\n } else {\n return result;\n }\n};\n\nconst suggestColumns = (columns: ColumnDescriptor[]) =>\n columns.map((column) => ({\n boost: 5,\n label: column.name,\n }));\n\nconst suggestNamedFilters = (namedFilters?: Map<string, string>) =>\n namedFilters\n ? (Array.from(namedFilters.entries()).map(([filterName, filterQuery]) => ({\n info: () => filterInfo(filterName, filterQuery),\n label: filterName,\n type: \"filter\",\n })) as Completion[])\n : NO_NAMED_FILTERS;\n\nconst doneCommand: Completion = {\n label: \"Done\",\n apply: \"] \",\n type: \"keyword\",\n boost: 10,\n};\n\nconst withApplySpace = (\n suggestions: Completion[],\n startsWith = \"\"\n): Completion[] =>\n suggestions\n .filter((sugg) => startsWith === \"\" || sugg.label.startsWith(startsWith))\n .map((suggestion) => ({\n ...suggestion,\n apply: suggestion.label + \" \",\n }));\n\nexport type FilterSaveOptions = {\n allowSaveAsTab?: boolean;\n allowReplace?: boolean;\n};\nexport interface SuggestionProviderHookProps {\n columns: ColumnDescriptor[];\n namedFilters?: Map<string, string>;\n saveOptions?: FilterSaveOptions;\n table: VuuTable;\n typeaheadHook?: () => SuggestionFetcher;\n}\n\nconst defaultSaveOptions = {\n allowReplace: true,\n};\n\nexport const useFilterSuggestionProvider = ({\n columns,\n namedFilters,\n saveOptions = defaultSaveOptions,\n table,\n typeaheadHook: useTypeahead = useTypeaheadSuggestions,\n}: SuggestionProviderHookProps): IFilterSuggestionProvider => {\n const latestSuggestionsRef = useRef<Completion[]>();\n const getTypeaheadSuggestions = useTypeahead();\n const getSuggestions: IFilterSuggestionProvider[\"getSuggestions\"] =\n useCallback(\n async (suggestionType, options = NONE): Promise<Completion[]> => {\n const {\n columnName,\n existingFilter,\n filterName,\n operator,\n quoted: autoQuoted,\n onSubmit,\n startsWith,\n selection,\n } = options;\n\n switch (suggestionType) {\n case \"operator\":\n {\n const column = columns.find((col) => col.name === columnName);\n if (column) {\n switch (column.serverDataType) {\n case \"string\":\n case \"char\":\n return withApplySpace(stringOperators, startsWith);\n case \"int\":\n case \"long\":\n case \"double\":\n return withApplySpace(numericOperators);\n }\n } else {\n console.warn(`'${columnName}' does not match any column name`);\n }\n }\n break;\n case \"column\": {\n const columnSuggestions = await suggestColumns(columns);\n const filterSuggestions = await suggestNamedFilters(namedFilters);\n return (latestSuggestionsRef.current =\n withApplySpace(columnSuggestions)).concat(\n withApplySpace(filterSuggestions)\n );\n }\n case \"columnValue\":\n {\n if (columnName) {\n const column = columns.find((col) => col.name === columnName);\n if (!column) {\n throw Error(\n `useFilterSUggestionProvider no column ${columnName}`\n );\n }\n const prefix = Array.isArray(selection)\n ? selection.length === 0\n ? \"[\"\n : \",\"\n : \"\";\n const params = getTypeaheadParams(\n table,\n columnName,\n startsWith\n );\n const suggestions = await getTypeaheadSuggestions(params);\n // const { type } = column;\n // if (\n // isTypeDescriptor(type) &&\n // isMappedValueTypeRenderer(type?.renderer)\n // ) {\n // const { map } = type.renderer;\n // suggestions = suggestions.map((value) => map[value] ?? value);\n // }\n\n // prob don't want to save the prefix\n const isIllustration = operator === \"starts\";\n latestSuggestionsRef.current = toSuggestions(suggestions, {\n moveCursorToEnd: autoQuoted,\n quoted: column?.serverDataType === \"string\" && !autoQuoted,\n suffix: autoQuoted ? \"\" : \" \",\n prefix: isIllustration ? startsWith : prefix,\n isIllustration,\n });\n if (Array.isArray(selection) && selection?.length > 1) {\n return [doneCommand, ...latestSuggestionsRef.current];\n }\n return latestSuggestionsRef.current;\n }\n }\n break;\n case \"save\": {\n if (typeof onSubmit !== \"function\") {\n throw Error(\n \"useFilterSuggestionProvider, onSubmit must be supplied for 'save' suggestions\"\n );\n }\n return await getSaveSuggestions({\n existingFilter,\n filterName,\n onSubmit,\n saveOptions,\n });\n }\n case \"name\":\n return await getNamePrompt(\"filter\");\n default:\n }\n\n return [];\n },\n [columns, getTypeaheadSuggestions, namedFilters, saveOptions, table]\n );\n\n const isPartialMatch = useCallback(\n async (\n valueType: SuggestionType,\n columnName?: string,\n pattern?: string\n ) => {\n // const { current: latestSuggestions } = latestSuggestionsRef;\n const suggestions =\n // latestSuggestions && latestSuggestions.length > 0\n // ? latestSuggestions\n await getSuggestions(valueType, { columnName });\n\n if (pattern && suggestions) {\n for (const option of suggestions) {\n if (option.label === pattern) {\n return false;\n } else if (option.label.startsWith(pattern)) {\n return true;\n }\n }\n }\n return false;\n },\n [getSuggestions]\n );\n\n return {\n getSuggestions,\n isPartialMatch,\n };\n};\n", "import { createEl } from \"@vuu-ui/vuu-utils\";\n\nexport const filterInfo = (\n filterName: string,\n filterQuery: string\n // filter: Filter\n) => {\n const rootElement = createEl(\"div\", \"vuuFunctionDoc\");\n const headingElement = createEl(\"div\", \"function-heading\");\n\n const nameElement = createEl(\"span\", \"function-name\", filterName);\n // const paramElement = createEl(\"span\", \"param-list\", params.description);\n // const typeElement = createEl(\"span\", \"function-type\", type);\n\n headingElement.appendChild(nameElement);\n // headingElement.appendChild(paramElement);\n // headingElement.appendChild(typeElement);\n\n const child2 = createEl(\"p\", undefined, filterQuery);\n\n rootElement.appendChild(headingElement);\n rootElement.appendChild(child2);\n\n return rootElement;\n};\n", "export const getLocalEntity = <T>(url: string): T | undefined => {\n const data = localStorage.getItem(url);\n return data ? JSON.parse(data) : undefined;\n};\n\nexport const getAllLocalEntity = <T>(url: string): T[] =>\n Object.entries(localStorage)\n .filter(([key]) => key.includes(url))\n .map(([, value]) => JSON.parse(value) as T);\n\nexport const saveLocalEntity = <T>(url: string, data: T): T | undefined => {\n try {\n localStorage.setItem(url, JSON.stringify(data));\n return data;\n } catch {\n return undefined;\n }\n};\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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nC,IAAI,CAAC,CAAC,EAAE,KAAK,MAAM,KAAK,MAAM,KAAK,CAAM;AAEvC,IAAM,kBAAkB,CAAI,KAAa,SAA2B;AACzE,MAAI;AACF,iBAAa,QAAQ,KAAK,KAAK,UAAU,IAAI,CAAC;AAC9C,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;",
4
+ "sourcesContent": ["export * from \"./filter-bar\";\nexport * from \"./filter-builder-menu\";\nexport * from \"./filter-clause\";\nexport * from \"./filter-input\";\nexport * from \"./filter-pill\";\nexport * from \"./filter-utils\";\nexport * from \"./local-config\";\n", "import { DataSourceFilter, TableSchema } from \"@vuu-ui/vuu-data-types\";\nimport { Filter, FilterState } from \"@vuu-ui/vuu-filter-types\";\nimport { Prompt } from \"@vuu-ui/vuu-popups\";\nimport { Toolbar } from \"@vuu-ui/vuu-ui-controls\";\nimport { ColumnDescriptor } from \"@vuu-ui/vuu-table-types\";\nimport { Button } from \"@salt-ds/core\";\nimport cx from \"clsx\";\nimport { HTMLAttributes, ReactElement, useRef } from \"react\";\nimport { FilterBuilderMenu } from \"../filter-builder-menu\";\nimport { FilterClauseEditor, FilterClauseEditorProps } from \"../filter-clause\";\nimport { FilterPill } from \"../filter-pill\";\nimport { filterClauses as getFilterClauses } from \"../filter-utils\";\nimport { FilterBarMenu } from \"./FilterBarMenu\";\nimport { useFilterBar } from \"./useFilterBar\";\n\nimport \"./FilterBar.css\";\n\nexport interface FilterBarProps extends HTMLAttributes<HTMLDivElement> {\n FilterClauseEditorProps?: Partial<FilterClauseEditorProps>;\n /**\n * This is used to apply tailored filters based on column types and other attributes.\n * NOTE: Always make sure that these are passed with proper re-render optimization, otherwise,\n * might end up with infinite state updates.\n */\n columnDescriptors: ColumnDescriptor[];\n defaultFilterState?: FilterState;\n filterState?: FilterState;\n onApplyFilter: (filter: DataSourceFilter) => void;\n onFilterDeleted?: (filter: Filter) => void;\n onFilterRenamed?: (filter: Filter, name: string) => void;\n onFilterStateChanged?: (state: FilterState) => void;\n showMenu?: boolean;\n tableSchema?: TableSchema;\n}\n\nconst classBase = \"vuuFilterBar\";\n\nexport const FilterBar = ({\n FilterClauseEditorProps,\n className: classNameProp,\n columnDescriptors,\n defaultFilterState,\n filterState,\n onApplyFilter,\n onFilterDeleted,\n onFilterRenamed,\n onFilterStateChanged,\n showMenu: showMenuProp = false,\n tableSchema,\n ...htmlAttributes\n}: FilterBarProps) => {\n const rootRef = useRef<HTMLDivElement>(null);\n const {\n activeFilterIndex,\n addButtonProps,\n columnsByName,\n editFilter,\n filters,\n onBlurFilterClause,\n onCancelFilterClause,\n onClickAddFilter,\n onClickRemoveFilter,\n onChangeFilterClause,\n onChangeActiveFilterIndex,\n onFocusFilterClause,\n onNavigateOutOfBounds,\n onKeyDownFilterbar,\n onKeyDownMenu,\n onMenuAction,\n pillProps,\n promptProps,\n showMenu,\n } = useFilterBar({\n containerRef: rootRef,\n columnDescriptors,\n defaultFilterState,\n filterState,\n onApplyFilter,\n onFilterStateChanged,\n onFilterDeleted,\n onFilterRenamed,\n showMenu: showMenuProp,\n });\n\n const className = cx(classBase, classNameProp, {\n [`${classBase}-display`]: editFilter === undefined,\n [`${classBase}-edit`]: editFilter !== undefined,\n });\n\n const getChildren = () => {\n const items: ReactElement[] = [];\n if (editFilter === undefined) {\n filters.forEach((filter, i) => {\n items.push(\n <FilterPill\n {...pillProps}\n columnsByName={columnsByName}\n filter={filter}\n key={`filter-${i}`}\n />\n );\n });\n return items;\n } else if (editFilter) {\n const filterClauses = getFilterClauses(editFilter);\n items.push(\n <div className={`${classBase}-Editor`} key={`editor`}>\n {filterClauses.map((f, i) => (\n <FilterClauseEditor\n {...FilterClauseEditorProps}\n columnsByName={columnsByName}\n filterClause={f}\n key={`editor-${i}`}\n onCancel={onCancelFilterClause}\n onChange={onChangeFilterClause(i)}\n onBlur={onBlurFilterClause}\n onFocus={onFocusFilterClause}\n tableSchema={tableSchema}\n />\n ))}\n </div>\n );\n if (showMenu) {\n items.push(\n <FilterBuilderMenu\n key=\"menu\"\n onMenuAction={onMenuAction}\n ListProps={{ onKeyDownCapture: onKeyDownMenu }}\n />\n );\n }\n items.push(\n <Button\n className={`${classBase}-remove`}\n data-align=\"right\"\n data-icon=\"cross\"\n key=\"filter-remove\"\n onClick={onClickRemoveFilter}\n variant=\"primary\"\n />\n );\n\n return items;\n }\n };\n\n return (\n <div\n {...htmlAttributes}\n className={className}\n onKeyDown={onKeyDownFilterbar}\n ref={rootRef}\n >\n <FilterBarMenu />\n <Toolbar\n activeItemIndex={activeFilterIndex}\n height={28}\n onActiveChange={onChangeActiveFilterIndex}\n onNavigateOutOfBounds={onNavigateOutOfBounds}\n selectionStrategy=\"multiple-special-key\"\n >\n {getChildren()}\n </Toolbar>\n {editFilter === undefined ? (\n <Button\n {...addButtonProps}\n className={`${classBase}-add`}\n data-icon=\"plus\"\n data-selectable={false}\n key=\"filter-add\"\n onClick={onClickAddFilter}\n tabIndex={0}\n variant=\"primary\"\n />\n ) : null}\n\n {promptProps ? (\n <Prompt\n {...promptProps}\n PopupProps={{\n anchorElement: rootRef,\n offsetTop: 16,\n placement: \"below-center\",\n }}\n />\n ) : null}\n </div>\n );\n};\n", "function r(e){var t,f,n=\"\";if(\"string\"==typeof e||\"number\"==typeof e)n+=e;else if(\"object\"==typeof e)if(Array.isArray(e))for(t=0;t<e.length;t++)e[t]&&(f=r(e[t]))&&(n&&(n+=\" \"),n+=f);else for(t in e)e[t]&&(n&&(n+=\" \"),n+=t);return n}export function clsx(){for(var e,t,f=0,n=\"\";f<arguments.length;)(e=arguments[f++])&&(t=r(e))&&(n&&(n+=\" \"),n+=t);return n}export default clsx;", "import { ContextMenuProps } from \"@vuu-ui/vuu-popups\";\nimport { MenuActionHandler } from \"@vuu-ui/vuu-data-types\";\nimport { ReactElement, useCallback, useRef } from \"react\";\nimport { PopupComponent as Popup, Portal } from \"@vuu-ui/vuu-popups\";\nimport { List, ListItem, ListProps } from \"@vuu-ui/vuu-ui-controls\";\n\nimport \"./FilterBuilderMenu.css\";\n\nconst classBase = \"vuuFilterBuilderMenu\";\n\nexport interface FilterBuilderMenuProps\n extends Omit<ContextMenuProps, \"children\"> {\n ListProps?: Pick<ListProps, \"onKeyDownCapture\">;\n onMenuAction: MenuActionHandler;\n}\n\nexport const FilterBuilderMenu = ({\n ListProps,\n onMenuAction,\n}: FilterBuilderMenuProps) => {\n const ref = useRef<HTMLSpanElement>(null);\n const listRef = useCallback((el: HTMLDivElement | null) => {\n if (el) {\n requestAnimationFrame(() => {\n el.focus();\n });\n }\n }, []);\n\n const handleSelect = useCallback(\n (evt, selected: ReactElement) => {\n const {\n props: { \"data-action\": action },\n } = selected;\n onMenuAction({ type: \"menu-action\", menuId: action, options: {} });\n },\n [onMenuAction]\n );\n\n return (\n <>\n <span className={`${classBase}-trigger`} ref={ref} />\n <Portal>\n <Popup anchorElement={ref} placement=\"right\">\n <List\n {...ListProps}\n className={`${classBase}List`}\n defaultHighlightedIndex={0}\n itemHeight={22}\n ref={listRef}\n onSelect={handleSelect}\n style={{ position: \"relative\" }}\n width={100}\n >\n <ListItem data-action=\"apply-save\">\n <span className=\"vuuMenuButton\">APPLY AND SAVE</span>\n </ListItem>\n <ListItem data-action=\"and-clause\">AND</ListItem>\n <ListItem data-action=\"or-clause\">OR</ListItem>\n </List>\n </Popup>\n </Portal>\n </>\n );\n};\n", "import { itemToString as defaultToString } from \"@vuu-ui/vuu-utils\";\nimport {\n ComboBox,\n ComboBoxProps,\n MultiSelectionHandler,\n SelectionStrategy,\n SingleSelectionHandler,\n} from \"@vuu-ui/vuu-ui-controls\";\nimport cx from \"clsx\";\nimport {\n FormEvent,\n ForwardedRef,\n forwardRef,\n ReactElement,\n useCallback,\n useMemo,\n useRef,\n useState,\n} from \"react\";\n\nimport \"./ExpandoCombobox.css\";\n\nconst classBase = \"vuuExpandoCombobox\";\n\nconst NO_INPUT_PROPS = {};\n\nexport interface ExpandoComboboxProps<\n Item = string,\n S extends SelectionStrategy = \"default\"\n> extends Omit<ComboBoxProps<Item, S>, \"itemToString\" | \"value\"> {\n itemToString?: (item: unknown) => string;\n onInputChange?: (evt: FormEvent<HTMLInputElement>) => void;\n value?: string | string[];\n}\n\nexport const ExpandoCombobox = forwardRef(function ExpandoCombobox<\n Item = string,\n S extends SelectionStrategy = \"default\"\n>(\n {\n className: classNameProp,\n InputProps: InputPropsProp = NO_INPUT_PROPS,\n ListProps: ListPropsProp,\n onInputChange,\n onSelectionChange,\n selectionStrategy,\n source,\n style,\n title,\n value = \"\",\n ...props\n }: ExpandoComboboxProps<Item, S>,\n forwardedRef: ForwardedRef<HTMLDivElement>\n) {\n const [text, setText] = useState(value);\n const { itemToString = defaultToString } = props;\n const initialValue = useRef(value);\n\n const itemsToString = useCallback<<I = Item>(items: I[]) => string>(\n (items) => {\n const [first, ...rest] = items;\n if (rest.length) {\n return `${itemToString(first)} + ${rest.length}`;\n } else {\n return itemToString(first);\n }\n },\n [itemToString]\n );\n\n const handleInputChange = useCallback(\n (evt: FormEvent<HTMLInputElement>) => {\n const { value } = evt.target as HTMLInputElement;\n setText(value);\n onInputChange?.(evt);\n },\n [onInputChange]\n );\n\n const handleSetSelectedText = useCallback((text: string) => {\n setText(text);\n }, []);\n\n const [InputProps, ListProps] = useMemo<\n [ComboBoxProps[\"InputProps\"], any]\n >(() => {\n const { inputProps, ...restInputProps } = InputPropsProp;\n return [\n {\n ...restInputProps,\n className: `${classBase}-Input`,\n endAdornment: null,\n inputProps: {\n ...inputProps,\n autoComplete: \"off\",\n onInput: handleInputChange,\n },\n },\n {\n ...ListPropsProp,\n className: cx(\"vuuMenuList\", ListPropsProp?.className),\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n \"data-mode\": \"light\",\n displayedItemCount: 10,\n itemHeight: 22,\n maxWidth: 300,\n minWidth: 80,\n width: \"content-width\",\n },\n ];\n }, [InputPropsProp, handleInputChange, ListPropsProp]);\n\n const handleSelectionChange = useCallback(\n (_, selected) => {\n if (Array.isArray(selected)) {\n (onSelectionChange as MultiSelectionHandler<Item>)?.(\n null,\n selected as Item[]\n );\n } else if (selected) {\n setText(itemToString(selected));\n (onSelectionChange as SingleSelectionHandler<Item>)?.(\n null,\n selected as Item\n );\n }\n },\n [itemToString, onSelectionChange]\n );\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const getDefaultSelected = (): any => {\n if (initialValue.current === undefined) {\n return undefined;\n } else if (Array.isArray(initialValue.current)) {\n return source?.filter((item) =>\n initialValue.current.includes(itemToString(item))\n );\n } else {\n return source?.find(\n (item) => itemToString(item) === initialValue.current\n );\n }\n };\n\n const popupProps = {\n minWidth: \"fit-content\",\n };\n return (\n <div\n className={cx(classBase, classNameProp)}\n data-text={text}\n ref={forwardedRef}\n style={style}\n >\n <ComboBox<Item, S>\n {...props}\n PopupProps={popupProps}\n allowEnterCommitsText\n defaultSelected={getDefaultSelected()}\n defaultValue={\n Array.isArray(initialValue.current)\n ? itemsToString<string>(initialValue.current)\n : initialValue.current\n }\n fullWidth\n ListProps={ListProps}\n InputProps={InputProps}\n itemsToString={itemsToString}\n onSelectionChange={handleSelectionChange}\n onSetSelectedText={handleSetSelectedText}\n selectionStrategy={selectionStrategy}\n source={source}\n />\n </div>\n );\n}) as <Item, S extends SelectionStrategy = \"default\">(\n props: ExpandoComboboxProps<Item, S> & {\n ref?: ForwardedRef<HTMLDivElement>;\n }\n) => ReactElement<ExpandoComboboxProps<Item, S>>;\n", "import { SuggestionFetcher, TableSchema } from \"@vuu-ui/vuu-data-types\";\nimport {\n ColumnDescriptorsByName,\n FilterClause,\n} from \"@vuu-ui/vuu-filter-types\";\nimport { ColumnDescriptor } from \"@vuu-ui/vuu-table-types\";\nimport { CloseReason } from \"@vuu-ui/vuu-ui-controls\";\nimport { Button } from \"@salt-ds/core\";\nimport cx from \"clsx\";\nimport { HTMLAttributes, useMemo } from \"react\";\nimport { ExpandoCombobox } from \"./ExpandoCombobox\";\nimport { getOperators } from \"./operator-utils\";\nimport { FilterClauseValueEditor } from \"./FilterClauseValueEditor\";\nimport {\n FilterClauseCancelHandler,\n useFilterClauseEditor,\n} from \"./useFilterClauseEditor\";\n\nimport \"./FilterClauseEditor.css\";\n\nexport interface FilterClauseEditorProps\n extends Omit<HTMLAttributes<HTMLDivElement>, \"onChange\"> {\n columnsByName: ColumnDescriptorsByName;\n filterClause: Partial<FilterClause>;\n onCancel?: FilterClauseCancelHandler;\n onChange: (filterClause: Partial<FilterClause>) => void;\n onDropdownClose?: (closeReason: CloseReason) => void;\n onDropdownOpen?: () => void;\n suggestionProvider?: () => SuggestionFetcher;\n tableSchema?: TableSchema;\n}\n\nconst classBase = \"vuuFilterClause\";\n\nexport const FilterClauseEditor = ({\n className,\n columnsByName,\n onCancel,\n onChange,\n onDropdownClose,\n onDropdownOpen,\n filterClause,\n suggestionProvider,\n tableSchema,\n ...htmlAttributes\n}: FilterClauseEditorProps) => {\n const {\n InputProps,\n columnRef,\n onChangeValue,\n onClear,\n onClearKeyDown,\n onDeselectValue,\n onColumnSelect,\n onOperatorSelect,\n operator,\n operatorRef,\n selectedColumn,\n value,\n } = useFilterClauseEditor({\n filterClause,\n onCancel,\n onChange,\n columnsByName,\n });\n\n const columns = useMemo(() => Object.values(columnsByName), [columnsByName]);\n\n return (\n <div className={cx(classBase, className)} {...htmlAttributes} tabIndex={0}>\n <ExpandoCombobox<ColumnDescriptor>\n InputProps={InputProps}\n allowBackspaceClearsSelection\n className={cx(`${classBase}Field`, `${classBase}Column`)}\n data-field=\"column\"\n initialHighlightedIndex={0}\n itemToString={(column) => (column as ColumnDescriptor).name}\n onListItemSelect={onColumnSelect}\n ref={columnRef}\n source={columns}\n title=\"column\"\n value={selectedColumn?.name ?? \"\"}\n />\n {selectedColumn?.name ? (\n <ExpandoCombobox<string>\n InputProps={InputProps}\n allowBackspaceClearsSelection\n className={cx(`${classBase}Field`, `${classBase}Operator`, {\n [`${classBase}Operator-hidden`]: selectedColumn === null,\n })}\n data-field=\"operator\"\n initialHighlightedIndex={0}\n onListItemSelect={onOperatorSelect}\n ref={operatorRef}\n source={getOperators(selectedColumn)}\n title=\"operator\"\n value={operator ?? \"\"}\n />\n ) : null}\n <FilterClauseValueEditor\n InputProps={InputProps}\n onChangeValue={onChangeValue}\n onDeselectValue={onDeselectValue}\n operator={operator}\n selectedColumn={selectedColumn}\n suggestionProvider={suggestionProvider}\n table={tableSchema?.table}\n value={value}\n />\n {value !== undefined ? (\n <Button\n className={`${classBase}-clearButton`}\n onClick={onClear}\n onKeyDown={onClearKeyDown}\n data-icon=\"close\"\n />\n ) : null}\n </div>\n );\n};\n", "import { ColumnDescriptor } from \"@vuu-ui/vuu-table-types\";\nimport { isNumericColumn, isTextColumn } from \"@vuu-ui/vuu-utils\";\n\nexport const textOperators = [\"=\", \"in\", \"!=\", \"starts\", \"ends\"];\nexport const numericperators = [\"=\", \"!=\", \">\", \">=\", \"<\", \"<=\"];\n\nexport const getOperators = (column: ColumnDescriptor): string[] => {\n if (isTextColumn(column)) {\n return textOperators;\n } else if (isNumericColumn(column)) {\n return numericperators;\n } else {\n throw Error(\"getOperators only supports text and numeric columns\");\n }\n};\n", "import {\n ChangeEvent,\n forwardRef,\n ForwardedRef,\n HTMLAttributes,\n RefObject,\n useState,\n useCallback,\n KeyboardEvent,\n} from \"react\";\nimport { ExpandoInput } from \"@vuu-ui/vuu-ui-controls\";\nimport { isValidNumber } from \"@vuu-ui/vuu-utils\";\nimport { FilterClauseValueEditor } from \"./filterClauseTypes\";\n\nexport interface NumericInputProps\n extends FilterClauseValueEditor<number>,\n HTMLAttributes<HTMLDivElement> {\n operatorInputRef?: RefObject<HTMLInputElement>;\n operator: string;\n ref: RefObject<HTMLDivElement>;\n value?: number;\n}\n\nexport const NumericInput = forwardRef(function NumericInput(\n {\n InputProps,\n className,\n onInputComplete,\n value: valueProp,\n }: NumericInputProps,\n forwardedRef: ForwardedRef<HTMLDivElement>\n) {\n const [value, setValue] = useState<string>(\n isValidNumber(valueProp) ? valueProp.toString() : \"\"\n );\n\n // useEffect(() => {\n // setValueInputValue(\"\");\n // }, [column]);\n\n const handleChange = useCallback((evt: ChangeEvent<HTMLInputElement>) => {\n const { value } = evt.target as HTMLInputElement;\n\n const numericValue = parseFloat(value);\n if (isValidNumber(numericValue)) {\n console.log(\"its valid\");\n }\n setValue(value);\n }, []);\n\n const handleKeyDown = useCallback(\n (evt: KeyboardEvent<HTMLInputElement>) => {\n if (evt.key === \"Enter\") {\n const { value } = evt.target as HTMLInputElement;\n const numericValue = parseFloat(value);\n if (isValidNumber(numericValue)) {\n onInputComplete(numericValue);\n }\n }\n },\n [onInputComplete]\n );\n\n return (\n <ExpandoInput\n {...InputProps}\n className={className}\n value={value}\n ref={forwardedRef}\n onChange={handleChange}\n onKeyDown={handleKeyDown}\n />\n );\n});\n", "import {\n FormEvent,\n ForwardedRef,\n forwardRef,\n HTMLAttributes,\n KeyboardEvent,\n RefObject,\n useCallback,\n useEffect,\n useMemo,\n useState,\n} from \"react\";\nimport { TypeaheadParams, VuuTable } from \"@vuu-ui/vuu-protocol-types\";\nimport { useTypeaheadSuggestions } from \"@vuu-ui/vuu-data-react\";\nimport {\n ExpandoInput,\n MultiSelectionHandler,\n SingleSelectionHandler,\n} from \"@vuu-ui/vuu-ui-controls\";\nimport { ExpandoCombobox } from \"./ExpandoCombobox\";\nimport { FilterClauseValueEditor } from \"./filterClauseTypes\";\nimport { SuggestionFetcher, TableSchemaTable } from \"@vuu-ui/vuu-data-types\";\n\nconst selectionKeys = [\"Enter\", \" \"];\n\nconst getVuuTable = (schemaTable: TableSchemaTable): VuuTable => {\n if (schemaTable.session) {\n const { module, session } = schemaTable;\n return { module, table: session };\n } else {\n return schemaTable;\n }\n};\n\nexport interface TextInputProps\n extends FilterClauseValueEditor,\n HTMLAttributes<HTMLDivElement> {\n \"data-field\"?: string;\n ref: RefObject<HTMLDivElement>;\n operator: string;\n suggestionProvider?: () => SuggestionFetcher;\n value: string | string[];\n}\n\nconst NO_DATA_MATCH = [\"No matching data\"];\n\nexport const FilterClauseTextValueEditor = forwardRef(function TextInput(\n {\n InputProps: InputPropsProp = {},\n className,\n column,\n \"data-field\": dataField,\n onDeselect,\n onInputComplete,\n operator,\n suggestionProvider = useTypeaheadSuggestions,\n table,\n value,\n }: TextInputProps,\n forwardedRef: ForwardedRef<HTMLDivElement>\n) {\n const isMultiValue = operator === \"in\";\n\n // If we have a multiselect text value which we are editing, this will render\n // a comma delimited list of the selected values. That is not what we display\n // by default when using a multiselect combo. Its not a huge problem - as soon\n // as user focuses this component and we display dropdown, input text is cleared\n // (so user can type to filter list) until dropdown closes again. <ight need to\n // revisit.\n const [valueInputValue, setValueInputValue] = useState(\n value?.toString() ?? \"\"\n );\n const [typeaheadValues, setTypeaheadValues] = useState<string[]>([]);\n\n const getSuggestions = suggestionProvider();\n\n const handleSingleValueSelectionChange = useCallback<SingleSelectionHandler>(\n (_, value) => onInputComplete(value),\n [onInputComplete]\n );\n\n const handleMultiValueSelectionChange = useCallback<MultiSelectionHandler>(\n (_, values) => onInputComplete(values),\n [onInputComplete]\n );\n\n useEffect(() => {\n if (table) {\n const vuuTable = getVuuTable(table);\n const params: TypeaheadParams =\n valueInputValue && !isMultiValue\n ? [vuuTable, column.name, valueInputValue]\n : [vuuTable, column.name];\n getSuggestions(params)\n .then((suggestions) => {\n if (suggestions.length === 0 && valueInputValue) {\n setTypeaheadValues(NO_DATA_MATCH);\n } else {\n setTypeaheadValues(suggestions);\n }\n })\n .catch((err) => {\n console.error(\"Error getting suggestions\", err);\n });\n }\n }, [table, column, valueInputValue, getSuggestions, isMultiValue]);\n\n const handleInputChange = useCallback((evt: FormEvent<HTMLInputElement>) => {\n const { value } = evt.target as HTMLInputElement;\n setValueInputValue(value);\n }, []);\n\n const InputProps = useMemo(() => {\n if (operator !== \"in\") {\n const { inputProps, ...restInputProps } = InputPropsProp;\n return {\n ...restInputProps,\n inputProps: {\n ...inputProps,\n onKeyDown: (evt: KeyboardEvent<HTMLInputElement>) => {\n if (evt.key === \"Enter\" && valueInputValue !== \"\") {\n evt.stopPropagation();\n evt.preventDefault();\n onInputComplete(valueInputValue);\n } else {\n inputProps?.onKeyDown?.(evt);\n }\n },\n },\n };\n } else {\n return InputPropsProp;\n }\n }, [InputPropsProp, onInputComplete, operator, valueInputValue]);\n\n const getValueInputField = useCallback(() => {\n switch (operator) {\n case \"in\":\n return (\n <ExpandoCombobox\n InputProps={InputProps}\n className={className}\n data-field={dataField}\n initialHighlightedIndex={0}\n source={typeaheadValues}\n onInputChange={handleInputChange}\n onSelectionChange={handleMultiValueSelectionChange}\n ref={forwardedRef}\n selectionStrategy=\"multiple\"\n selectionKeys={selectionKeys}\n value={value}\n />\n );\n case \"starts\": {\n return (\n <ExpandoCombobox<string>\n InputProps={InputProps}\n ListProps={{\n className: \"vuuIllustrationsOnly\",\n disabled: true,\n }}\n allowFreeText\n className={className}\n data-field={dataField}\n initialHighlightedIndex={0}\n disableFilter={\n typeaheadValues === NO_DATA_MATCH && valueInputValue?.length > 0\n }\n source={typeaheadValues}\n onInputChange={handleInputChange}\n onSelectionChange={handleSingleValueSelectionChange}\n ref={forwardedRef}\n value={value}\n />\n );\n }\n\n case \"ends\":\n return (\n <ExpandoInput\n {...InputProps}\n className={className}\n data-field={dataField}\n value={valueInputValue}\n ref={forwardedRef}\n onChange={handleInputChange}\n />\n );\n\n default:\n //TODO get a ref to input and listen to changes - connect these to typeahead\n return (\n <ExpandoCombobox<string>\n InputProps={InputProps}\n allowBackspaceClearsSelection\n allowFreeText\n className={className}\n data-field={dataField}\n initialHighlightedIndex={0}\n source={typeaheadValues}\n title=\"value\"\n onInputChange={handleInputChange}\n onDeselect={onDeselect}\n onSelectionChange={handleSingleValueSelectionChange}\n ref={forwardedRef}\n value={value}\n />\n );\n }\n }, [\n InputProps,\n operator,\n className,\n dataField,\n typeaheadValues,\n handleInputChange,\n handleMultiValueSelectionChange,\n forwardedRef,\n value,\n valueInputValue,\n onDeselect,\n handleSingleValueSelectionChange,\n ]);\n\n return getValueInputField();\n});\n", "import { TableSchema } from \"@vuu-ui/vuu-data-types\";\nimport cx from \"clsx\";\nimport { NumericInput } from \"./NumericInput\";\nimport { FilterClauseTextValueEditor } from \"./FilterClauseTextValueEditor\";\nimport { useFilterClauseEditor } from \"./useFilterClauseEditor\";\n\nimport { NumericFilterClauseOp } from \"@vuu-ui/vuu-filter-types\";\nimport { isDateTimeColumn } from \"@vuu-ui/vuu-utils\";\nimport { DateInput } from \"./DateInput\";\nimport { FilterClauseEditorProps } from \"./FilterClauseEditor\";\n\nconst classBase = \"vuuFilterClause\";\n\ntype InputElementProps = Pick<\n ReturnType<typeof useFilterClauseEditor>,\n | \"selectedColumn\"\n | \"operator\"\n | \"InputProps\"\n | \"onChangeValue\"\n | \"onDeselectValue\"\n | \"value\"\n> &\n Pick<FilterClauseEditorProps, \"suggestionProvider\"> & {\n table?: TableSchema[\"table\"];\n };\n\nexport const FilterClauseValueEditor: React.FC<InputElementProps> = ({\n selectedColumn,\n operator,\n InputProps,\n onChangeValue,\n onDeselectValue,\n suggestionProvider,\n table,\n value,\n}) => {\n if (selectedColumn === undefined || operator === undefined) {\n return null;\n }\n\n if (isDateTimeColumn(selectedColumn)) {\n return (\n <DateInput\n value={value as number}\n operator={operator as NumericFilterClauseOp}\n onInputComplete={onChangeValue}\n />\n );\n }\n\n switch (selectedColumn.serverDataType) {\n case \"string\":\n case \"char\":\n return (\n <FilterClauseTextValueEditor\n InputProps={InputProps}\n className={cx(`${classBase}Field`, `${classBase}Value`)}\n column={selectedColumn}\n data-field=\"value\"\n onDeselect={onDeselectValue}\n onInputComplete={onChangeValue}\n operator={operator}\n suggestionProvider={suggestionProvider}\n table={table}\n value={value as string | string[]}\n />\n );\n case \"int\":\n case \"long\":\n case \"double\":\n return (\n <NumericInput\n InputProps={InputProps}\n className={cx(`${classBase}Field`, `${classBase}Value`)}\n column={selectedColumn}\n onInputComplete={onChangeValue}\n operator={operator}\n />\n );\n default:\n console.log(\"returning null\");\n return null;\n }\n};\n", "import React, { useCallback, useState } from \"react\";\nimport { getLocalTimeZone, DateValue } from \"@internationalized/date\";\nimport { DatePicker } from \"@vuu-ui/vuu-ui-controls\";\nimport { toCalendarDate } from \"@vuu-ui/vuu-utils\";\nimport { NumericFilterClauseOp } from \"@vuu-ui/vuu-filter-types\";\nimport { FilterClauseValueEditor } from \"./filterClauseTypes\";\n\ninterface Props\n extends Pick<FilterClauseValueEditor<number>, \"onInputComplete\"> {\n value: number | undefined;\n operator: NumericFilterClauseOp;\n}\n\nexport const DateInput: React.FC<Props> = (props) => {\n const { value, onInputComplete, operator } = props;\n const toEpochMilliS = getEpochMillisConverter(operator);\n\n const [date, setDate] = useState<DateValue | undefined>(() =>\n getInitialState(value)\n );\n\n const onSelectedDateChange = useCallback((d: DateValue | undefined) => {\n setDate(d);\n }, []);\n\n const onBlur = useCallback(() => {\n date && onInputComplete(toEpochMilliS(date));\n }, [date, onInputComplete, toEpochMilliS]);\n\n return (\n <DatePicker\n className={\"vuuFilterClause-DatePicker\"}\n selectedDate={date}\n onBlur={onBlur}\n onSelectedDateChange={onSelectedDateChange}\n closeOnSelection\n hideOutOfRangeDates\n />\n );\n};\n\nfunction getInitialState(value: Props[\"value\"]) {\n return value ? toCalendarDate(new Date(value)) : undefined;\n}\n\nconst getEpochMillisConverter =\n (op: NumericFilterClauseOp) =>\n (date: DateValue, timezone: string = getLocalTimeZone()): number => {\n const d = date.toDate(timezone);\n switch (op) {\n case \">\":\n case \"<=\":\n d.setHours(23, 59, 59, 999);\n return d.getTime();\n case \">=\":\n case \"<\":\n case \"=\": // converted to \"< `start of next day` and >= `start of this day`\" when query is created\n case \"!=\": // converted to \">= `start of next day` or < `start of this day`\" when query is created\n d.setHours(0, 0, 0, 0);\n return d.getTime();\n }\n };\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nexport type {\n AnyCalendarDate,\n AnyTime,\n AnyDateTime,\n Calendar,\n DateDuration,\n TimeDuration,\n DateTimeDuration,\n DateFields,\n TimeFields,\n DateField,\n TimeField,\n Disambiguation,\n CycleOptions,\n CycleTimeOptions\n} from './types';\n\nexport {CalendarDate, CalendarDateTime, Time, ZonedDateTime} from './CalendarDate';\nexport {GregorianCalendar} from './calendars/GregorianCalendar';\nexport {JapaneseCalendar} from './calendars/JapaneseCalendar';\nexport {BuddhistCalendar} from './calendars/BuddhistCalendar';\nexport {TaiwanCalendar} from './calendars/TaiwanCalendar';\nexport {PersianCalendar} from './calendars/PersianCalendar';\nexport {IndianCalendar} from './calendars/IndianCalendar';\nexport {IslamicCivilCalendar, IslamicTabularCalendar, IslamicUmalquraCalendar} from './calendars/IslamicCalendar';\nexport {HebrewCalendar} from './calendars/HebrewCalendar';\nexport {EthiopicCalendar, EthiopicAmeteAlemCalendar, CopticCalendar} from './calendars/EthiopicCalendar';\nexport {createCalendar} from './createCalendar';\nexport {\n toCalendarDate,\n toCalendarDateTime,\n toTime,\n toCalendar,\n toZoned,\n toTimeZone,\n toLocalTimeZone,\n fromDate,\n fromAbsolute\n} from './conversion';\nexport {\n isSameDay,\n isSameMonth,\n isSameYear,\n isEqualDay,\n isEqualMonth,\n isEqualYear,\n isToday,\n getDayOfWeek,\n now,\n today,\n getHoursInDay,\n getLocalTimeZone,\n startOfMonth,\n startOfWeek,\n startOfYear,\n endOfMonth,\n endOfWeek,\n endOfYear,\n getMinimumMonthInYear,\n getMinimumDayInMonth,\n getWeeksInMonth,\n minDate,\n maxDate,\n isWeekend,\n isWeekday\n} from './queries';\nexport {\n parseDate,\n parseDateTime,\n parseTime,\n parseAbsolute,\n parseAbsoluteToLocal,\n parseZonedDateTime,\n parseDuration\n} from './string';\nexport {DateFormatter} from './DateFormatter';\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {add, addTime, addZoned, constrain, constrainTime, cycleDate, cycleTime, cycleZoned, set, setTime, setZoned, subtract, subtractTime, subtractZoned} from './manipulation';\nimport {AnyCalendarDate, AnyTime, Calendar, CycleOptions, CycleTimeOptions, DateDuration, DateField, DateFields, DateTimeDuration, Disambiguation, TimeDuration, TimeField, TimeFields} from './types';\nimport {compareDate, compareTime} from './queries';\nimport {dateTimeToString, dateToString, timeToString, zonedDateTimeToString} from './string';\nimport {GregorianCalendar} from './calendars/GregorianCalendar';\nimport {toCalendarDateTime, toDate, toZoned, zonedToDate} from './conversion';\n\nfunction shiftArgs(args: any[]) {\n let calendar: Calendar = typeof args[0] === 'object'\n ? args.shift()\n : new GregorianCalendar();\n\n let era: string;\n if (typeof args[0] === 'string') {\n era = args.shift();\n } else {\n let eras = calendar.getEras();\n era = eras[eras.length - 1];\n }\n\n let year = args.shift();\n let month = args.shift();\n let day = args.shift();\n\n return [calendar, era, year, month, day];\n}\n\n/** A CalendarDate represents a date without any time components in a specific calendar system. */\nexport class CalendarDate {\n // This prevents TypeScript from allowing other types with the same fields to match.\n // i.e. a ZonedDateTime should not be be passable to a parameter that expects CalendarDate.\n // If that behavior is desired, use the AnyCalendarDate interface instead.\n // @ts-ignore\n #type;\n /** The calendar system associated with this date, e.g. Gregorian. */\n public readonly calendar: Calendar;\n /** The calendar era for this date, e.g. \"BC\" or \"AD\". */\n public readonly era: string;\n /** The year of this date within the era. */\n public readonly year: number;\n /**\n * The month number within the year. Note that some calendar systems such as Hebrew\n * may have a variable number of months per year. Therefore, month numbers may not\n * always correspond to the same month names in different years.\n */\n public readonly month: number;\n /** The day number within the month. */\n public readonly day: number;\n\n constructor(year: number, month: number, day: number);\n constructor(era: string, year: number, month: number, day: number);\n constructor(calendar: Calendar, year: number, month: number, day: number);\n constructor(calendar: Calendar, era: string, year: number, month: number, day: number);\n constructor(...args: any[]) {\n let [calendar, era, year, month, day] = shiftArgs(args);\n this.calendar = calendar;\n this.era = era;\n this.year = year;\n this.month = month;\n this.day = day;\n\n constrain(this);\n }\n\n /** Returns a copy of this date. */\n copy(): CalendarDate {\n if (this.era) {\n return new CalendarDate(this.calendar, this.era, this.year, this.month, this.day);\n } else {\n return new CalendarDate(this.calendar, this.year, this.month, this.day);\n }\n }\n\n /** Returns a new `CalendarDate` with the given duration added to it. */\n add(duration: DateDuration): CalendarDate {\n return add(this, duration);\n }\n\n /** Returns a new `CalendarDate` with the given duration subtracted from it. */\n subtract(duration: DateDuration): CalendarDate {\n return subtract(this, duration);\n }\n\n /** Returns a new `CalendarDate` with the given fields set to the provided values. Other fields will be constrained accordingly. */\n set(fields: DateFields): CalendarDate {\n return set(this, fields);\n }\n\n /**\n * Returns a new `CalendarDate` with the given field adjusted by a specified amount.\n * When the resulting value reaches the limits of the field, it wraps around.\n */\n cycle(field: DateField, amount: number, options?: CycleOptions): CalendarDate {\n return cycleDate(this, field, amount, options);\n }\n\n /** Converts the date to a native JavaScript Date object, with the time set to midnight in the given time zone. */\n toDate(timeZone: string): Date {\n return toDate(this, timeZone);\n }\n\n /** Converts the date to an ISO 8601 formatted string. */\n toString(): string {\n return dateToString(this);\n }\n\n /** Compares this date with another. A negative result indicates that this date is before the given one, and a positive date indicates that it is after. */\n compare(b: AnyCalendarDate): number {\n return compareDate(this, b);\n }\n}\n\n/** A Time represents a clock time without any date components. */\nexport class Time {\n // This prevents TypeScript from allowing other types with the same fields to match.\n // @ts-ignore\n #type;\n /** The hour, numbered from 0 to 23. */\n public readonly hour: number;\n /** The minute in the hour. */\n public readonly minute: number;\n /** The second in the minute. */\n public readonly second: number;\n /** The millisecond in the second. */\n public readonly millisecond: number;\n\n constructor(\n hour: number = 0,\n minute: number = 0,\n second: number = 0,\n millisecond: number = 0\n ) {\n this.hour = hour;\n this.minute = minute;\n this.second = second;\n this.millisecond = millisecond;\n constrainTime(this);\n }\n\n /** Returns a copy of this time. */\n copy(): Time {\n return new Time(this.hour, this.minute, this.second, this.millisecond);\n }\n\n /** Returns a new `Time` with the given duration added to it. */\n add(duration: TimeDuration) {\n return addTime(this, duration);\n }\n\n /** Returns a new `Time` with the given duration subtracted from it. */\n subtract(duration: TimeDuration) {\n return subtractTime(this, duration);\n }\n\n /** Returns a new `Time` with the given fields set to the provided values. Other fields will be constrained accordingly. */\n set(fields: TimeFields) {\n return setTime(this, fields);\n }\n\n /**\n * Returns a new `Time` with the given field adjusted by a specified amount.\n * When the resulting value reaches the limits of the field, it wraps around.\n */\n cycle(field: TimeField, amount: number, options?: CycleTimeOptions) {\n return cycleTime(this, field, amount, options);\n }\n\n /** Converts the time to an ISO 8601 formatted string. */\n toString() {\n return timeToString(this);\n }\n\n /** Compares this time with another. A negative result indicates that this time is before the given one, and a positive time indicates that it is after. */\n compare(b: AnyTime) {\n return compareTime(this, b);\n }\n}\n\n/** A CalendarDateTime represents a date and time without a time zone, in a specific calendar system. */\nexport class CalendarDateTime {\n // This prevents TypeScript from allowing other types with the same fields to match.\n // @ts-ignore\n #type;\n /** The calendar system associated with this date, e.g. Gregorian. */\n public readonly calendar: Calendar;\n /** The calendar era for this date, e.g. \"BC\" or \"AD\". */\n public readonly era: string;\n /** The year of this date within the era. */\n public readonly year: number;\n /**\n * The month number within the year. Note that some calendar systems such as Hebrew\n * may have a variable number of months per year. Therefore, month numbers may not\n * always correspond to the same month names in different years.\n */\n public readonly month: number;\n /** The day number within the month. */\n public readonly day: number;\n /** The hour in the day, numbered from 0 to 23. */\n public readonly hour: number;\n /** The minute in the hour. */\n public readonly minute: number;\n /** The second in the minute. */\n public readonly second: number;\n /** The millisecond in the second. */\n public readonly millisecond: number;\n\n constructor(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number);\n constructor(era: string, year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number);\n constructor(calendar: Calendar, year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number);\n constructor(calendar: Calendar, era: string, year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number);\n constructor(...args: any[]) {\n let [calendar, era, year, month, day] = shiftArgs(args);\n this.calendar = calendar;\n this.era = era;\n this.year = year;\n this.month = month;\n this.day = day;\n this.hour = args.shift() || 0;\n this.minute = args.shift() || 0;\n this.second = args.shift() || 0;\n this.millisecond = args.shift() || 0;\n\n constrain(this);\n }\n\n /** Returns a copy of this date. */\n copy(): CalendarDateTime {\n if (this.era) {\n return new CalendarDateTime(this.calendar, this.era, this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond);\n } else {\n return new CalendarDateTime(this.calendar, this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond);\n }\n }\n\n /** Returns a new `CalendarDateTime` with the given duration added to it. */\n add(duration: DateTimeDuration): CalendarDateTime {\n return add(this, duration);\n }\n\n /** Returns a new `CalendarDateTime` with the given duration subtracted from it. */\n subtract(duration: DateTimeDuration): CalendarDateTime {\n return subtract(this, duration);\n }\n\n /** Returns a new `CalendarDateTime` with the given fields set to the provided values. Other fields will be constrained accordingly. */\n set(fields: DateFields & TimeFields): CalendarDateTime {\n return set(setTime(this, fields), fields);\n }\n\n /**\n * Returns a new `CalendarDateTime` with the given field adjusted by a specified amount.\n * When the resulting value reaches the limits of the field, it wraps around.\n */\n cycle(field: DateField | TimeField, amount: number, options?: CycleTimeOptions): CalendarDateTime {\n switch (field) {\n case 'era':\n case 'year':\n case 'month':\n case 'day':\n return cycleDate(this, field, amount, options);\n default:\n return cycleTime(this, field, amount, options);\n }\n }\n\n /** Converts the date to a native JavaScript Date object in the given time zone. */\n toDate(timeZone: string, disambiguation?: Disambiguation): Date {\n return toDate(this, timeZone, disambiguation);\n }\n\n /** Converts the date to an ISO 8601 formatted string. */\n toString(): string {\n return dateTimeToString(this);\n }\n\n /** Compares this date with another. A negative result indicates that this date is before the given one, and a positive date indicates that it is after. */\n compare(b: CalendarDate | CalendarDateTime | ZonedDateTime): number {\n let res = compareDate(this, b);\n if (res === 0) {\n return compareTime(this, toCalendarDateTime(b));\n }\n\n return res;\n }\n}\n\n/** A ZonedDateTime represents a date and time in a specific time zone and calendar system. */\nexport class ZonedDateTime {\n // This prevents TypeScript from allowing other types with the same fields to match.\n // @ts-ignore\n #type;\n /** The calendar system associated with this date, e.g. Gregorian. */\n public readonly calendar: Calendar;\n /** The calendar era for this date, e.g. \"BC\" or \"AD\". */\n public readonly era: string;\n /** The year of this date within the era. */\n public readonly year: number;\n /**\n * The month number within the year. Note that some calendar systems such as Hebrew\n * may have a variable number of months per year. Therefore, month numbers may not\n * always correspond to the same month names in different years.\n */\n public readonly month: number;\n /** The day number within the month. */\n public readonly day: number;\n /** The hour in the day, numbered from 0 to 23. */\n public readonly hour: number;\n /** The minute in the hour. */\n public readonly minute: number;\n /** The second in the minute. */\n public readonly second: number;\n /** The millisecond in the second. */\n public readonly millisecond: number;\n /** The IANA time zone identifier that this date and time is represented in. */\n public readonly timeZone: string;\n /** The UTC offset for this time, in milliseconds. */\n public readonly offset: number;\n\n constructor(year: number, month: number, day: number, timeZone: string, offset: number, hour?: number, minute?: number, second?: number, millisecond?: number);\n constructor(era: string, year: number, month: number, day: number, timeZone: string, offset: number, hour?: number, minute?: number, second?: number, millisecond?: number);\n constructor(calendar: Calendar, year: number, month: number, day: number, timeZone: string, offset: number, hour?: number, minute?: number, second?: number, millisecond?: number);\n constructor(calendar: Calendar, era: string, year: number, month: number, day: number, timeZone: string, offset: number, hour?: number, minute?: number, second?: number, millisecond?: number);\n constructor(...args: any[]) {\n let [calendar, era, year, month, day] = shiftArgs(args);\n let timeZone = args.shift();\n let offset = args.shift();\n this.calendar = calendar;\n this.era = era;\n this.year = year;\n this.month = month;\n this.day = day;\n this.timeZone = timeZone;\n this.offset = offset;\n this.hour = args.shift() || 0;\n this.minute = args.shift() || 0;\n this.second = args.shift() || 0;\n this.millisecond = args.shift() || 0;\n\n constrain(this);\n }\n\n /** Returns a copy of this date. */\n copy(): ZonedDateTime {\n if (this.era) {\n return new ZonedDateTime(this.calendar, this.era, this.year, this.month, this.day, this.timeZone, this.offset, this.hour, this.minute, this.second, this.millisecond);\n } else {\n return new ZonedDateTime(this.calendar, this.year, this.month, this.day, this.timeZone, this.offset, this.hour, this.minute, this.second, this.millisecond);\n }\n }\n\n /** Returns a new `ZonedDateTime` with the given duration added to it. */\n add(duration: DateTimeDuration) {\n return addZoned(this, duration);\n }\n\n /** Returns a new `ZonedDateTime` with the given duration subtracted from it. */\n subtract(duration: DateTimeDuration) {\n return subtractZoned(this, duration);\n }\n\n /** Returns a new `ZonedDateTime` with the given fields set to the provided values. Other fields will be constrained accordingly. */\n set(fields: DateFields & TimeFields, disambiguation?: Disambiguation) {\n return setZoned(this, fields, disambiguation);\n }\n\n /**\n * Returns a new `ZonedDateTime` with the given field adjusted by a specified amount.\n * When the resulting value reaches the limits of the field, it wraps around.\n */\n cycle(field: DateField | TimeField, amount: number, options?: CycleTimeOptions) {\n return cycleZoned(this, field, amount, options);\n }\n\n /** Converts the date to a native JavaScript Date object. */\n toDate() {\n return zonedToDate(this);\n }\n\n /** Converts the date to an ISO 8601 formatted string, including the UTC offset and time zone identifier. */\n toString() {\n return zonedDateTimeToString(this);\n }\n\n /** Converts the date to an ISO 8601 formatted string in UTC. */\n toAbsoluteString() {\n return this.toDate().toISOString();\n }\n\n /** Compares this date with another. A negative result indicates that this date is before the given one, and a positive date indicates that it is after. */\n compare(b: CalendarDate | CalendarDateTime | ZonedDateTime) {\n // TODO: Is this a bad idea??\n return this.toDate().getTime() - toZoned(b, this.timeZone).toDate().getTime();\n }\n}\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {AnyCalendarDate, AnyDateTime, AnyTime, CycleOptions, CycleTimeOptions, DateDuration, DateField, DateFields, DateTimeDuration, Disambiguation, TimeDuration, TimeField, TimeFields} from './types';\nimport {CalendarDate, CalendarDateTime, Time, ZonedDateTime} from './CalendarDate';\nimport {epochFromDate, fromAbsolute, toAbsolute, toCalendar, toCalendarDateTime} from './conversion';\nimport {GregorianCalendar} from './calendars/GregorianCalendar';\nimport {Mutable} from './utils';\n\nconst ONE_HOUR = 3600000;\n\nexport function add(date: CalendarDateTime, duration: DateTimeDuration): CalendarDateTime;\nexport function add(date: CalendarDate, duration: DateDuration): CalendarDate;\nexport function add(date: CalendarDate | CalendarDateTime, duration: DateTimeDuration): CalendarDate | CalendarDateTime;\nexport function add(date: CalendarDate | CalendarDateTime, duration: DateTimeDuration) {\n let mutableDate: Mutable<AnyCalendarDate | AnyDateTime> = date.copy();\n let days = 'hour' in mutableDate ? addTimeFields(mutableDate, duration) : 0;\n\n addYears(mutableDate, duration.years || 0);\n if (mutableDate.calendar.balanceYearMonth) {\n mutableDate.calendar.balanceYearMonth(mutableDate, date);\n }\n\n mutableDate.month += duration.months || 0;\n\n balanceYearMonth(mutableDate);\n constrainMonthDay(mutableDate);\n\n mutableDate.day += (duration.weeks || 0) * 7;\n mutableDate.day += duration.days || 0;\n mutableDate.day += days;\n\n balanceDay(mutableDate);\n\n if (mutableDate.calendar.balanceDate) {\n mutableDate.calendar.balanceDate(mutableDate);\n }\n\n // Constrain in case adding ended up with a date outside the valid range for the calendar system.\n // The behavior here is slightly different than when constraining in the `set` function in that\n // we adjust smaller fields to their minimum/maximum values rather than constraining each field\n // individually. This matches the general behavior of `add` vs `set` regarding how fields are balanced.\n if (mutableDate.year < 1) {\n mutableDate.year = 1;\n mutableDate.month = 1;\n mutableDate.day = 1;\n }\n\n let maxYear = mutableDate.calendar.getYearsInEra(mutableDate);\n if (mutableDate.year > maxYear) {\n let isInverseEra = mutableDate.calendar.isInverseEra?.(mutableDate);\n mutableDate.year = maxYear;\n mutableDate.month = isInverseEra ? 1 : mutableDate.calendar.getMonthsInYear(mutableDate);\n mutableDate.day = isInverseEra ? 1 : mutableDate.calendar.getDaysInMonth(mutableDate);\n }\n\n if (mutableDate.month < 1) {\n mutableDate.month = 1;\n mutableDate.day = 1;\n }\n\n let maxMonth = mutableDate.calendar.getMonthsInYear(mutableDate);\n if (mutableDate.month > maxMonth) {\n mutableDate.month = maxMonth;\n mutableDate.day = mutableDate.calendar.getDaysInMonth(mutableDate);\n }\n\n mutableDate.day = Math.max(1, Math.min(mutableDate.calendar.getDaysInMonth(mutableDate), mutableDate.day));\n return mutableDate;\n}\n\nfunction addYears(date: Mutable<AnyCalendarDate>, years: number) {\n if (date.calendar.isInverseEra?.(date)) {\n years = -years;\n }\n\n date.year += years;\n}\n\nfunction balanceYearMonth(date: Mutable<AnyCalendarDate>) {\n while (date.month < 1) {\n addYears(date, -1);\n date.month += date.calendar.getMonthsInYear(date);\n }\n\n let monthsInYear = 0;\n while (date.month > (monthsInYear = date.calendar.getMonthsInYear(date))) {\n date.month -= monthsInYear;\n addYears(date, 1);\n }\n}\n\nfunction balanceDay(date: Mutable<AnyCalendarDate>) {\n while (date.day < 1) {\n date.month--;\n balanceYearMonth(date);\n date.day += date.calendar.getDaysInMonth(date);\n }\n\n while (date.day > date.calendar.getDaysInMonth(date)) {\n date.day -= date.calendar.getDaysInMonth(date);\n date.month++;\n balanceYearMonth(date);\n }\n}\n\nfunction constrainMonthDay(date: Mutable<AnyCalendarDate>) {\n date.month = Math.max(1, Math.min(date.calendar.getMonthsInYear(date), date.month));\n date.day = Math.max(1, Math.min(date.calendar.getDaysInMonth(date), date.day));\n}\n\nexport function constrain(date: Mutable<AnyCalendarDate>) {\n if (date.calendar.constrainDate) {\n date.calendar.constrainDate(date);\n }\n\n date.year = Math.max(1, Math.min(date.calendar.getYearsInEra(date), date.year));\n constrainMonthDay(date);\n}\n\nexport function invertDuration(duration: DateTimeDuration): DateTimeDuration {\n let inverseDuration = {};\n for (let key in duration) {\n if (typeof duration[key] === 'number') {\n inverseDuration[key] = -duration[key];\n }\n }\n\n return inverseDuration;\n}\n\nexport function subtract(date: CalendarDateTime, duration: DateTimeDuration): CalendarDateTime;\nexport function subtract(date: CalendarDate, duration: DateDuration): CalendarDate;\nexport function subtract(date: CalendarDate | CalendarDateTime, duration: DateTimeDuration): CalendarDate | CalendarDateTime {\n return add(date, invertDuration(duration));\n}\n\nexport function set(date: CalendarDateTime, fields: DateFields): CalendarDateTime;\nexport function set(date: CalendarDate, fields: DateFields): CalendarDate;\nexport function set(date: CalendarDate | CalendarDateTime, fields: DateFields) {\n let mutableDate: Mutable<AnyCalendarDate> = date.copy();\n\n if (fields.era != null) {\n mutableDate.era = fields.era;\n }\n\n if (fields.year != null) {\n mutableDate.year = fields.year;\n }\n\n if (fields.month != null) {\n mutableDate.month = fields.month;\n }\n\n if (fields.day != null) {\n mutableDate.day = fields.day;\n }\n\n constrain(mutableDate);\n return mutableDate;\n}\n\nexport function setTime(value: CalendarDateTime, fields: TimeFields): CalendarDateTime;\nexport function setTime(value: Time, fields: TimeFields): Time;\nexport function setTime(value: Time | CalendarDateTime, fields: TimeFields) {\n let mutableValue: Mutable<Time | CalendarDateTime> = value.copy();\n\n if (fields.hour != null) {\n mutableValue.hour = fields.hour;\n }\n\n if (fields.minute != null) {\n mutableValue.minute = fields.minute;\n }\n\n if (fields.second != null) {\n mutableValue.second = fields.second;\n }\n\n if (fields.millisecond != null) {\n mutableValue.millisecond = fields.millisecond;\n }\n\n constrainTime(mutableValue);\n return mutableValue;\n}\n\nfunction balanceTime(time: Mutable<AnyTime>): number {\n time.second += Math.floor(time.millisecond / 1000);\n time.millisecond = nonNegativeMod(time.millisecond, 1000);\n\n time.minute += Math.floor(time.second / 60);\n time.second = nonNegativeMod(time.second, 60);\n\n time.hour += Math.floor(time.minute / 60);\n time.minute = nonNegativeMod(time.minute, 60);\n\n let days = Math.floor(time.hour / 24);\n time.hour = nonNegativeMod(time.hour, 24);\n\n return days;\n}\n\nexport function constrainTime(time: Mutable<AnyTime>) {\n time.millisecond = Math.max(0, Math.min(time.millisecond, 1000));\n time.second = Math.max(0, Math.min(time.second, 59));\n time.minute = Math.max(0, Math.min(time.minute, 59));\n time.hour = Math.max(0, Math.min(time.hour, 23));\n}\n\nfunction nonNegativeMod(a: number, b: number) {\n let result = a % b;\n if (result < 0) {\n result += b;\n }\n return result;\n}\n\nfunction addTimeFields(time: Mutable<AnyTime>, duration: TimeDuration): number {\n time.hour += duration.hours || 0;\n time.minute += duration.minutes || 0;\n time.second += duration.seconds || 0;\n time.millisecond += duration.milliseconds || 0;\n return balanceTime(time);\n}\n\nexport function addTime(time: Time, duration: TimeDuration): Time {\n let res = time.copy();\n addTimeFields(res, duration);\n return res;\n}\n\nexport function subtractTime(time: Time, duration: TimeDuration): Time {\n return addTime(time, invertDuration(duration));\n}\n\nexport function cycleDate(value: CalendarDateTime, field: DateField, amount: number, options?: CycleOptions): CalendarDateTime;\nexport function cycleDate(value: CalendarDate, field: DateField, amount: number, options?: CycleOptions): CalendarDate;\nexport function cycleDate(value: CalendarDate | CalendarDateTime, field: DateField, amount: number, options?: CycleOptions) {\n let mutable: Mutable<CalendarDate | CalendarDateTime> = value.copy();\n\n switch (field) {\n case 'era': {\n let eras = value.calendar.getEras();\n let eraIndex = eras.indexOf(value.era);\n if (eraIndex < 0) {\n throw new Error('Invalid era: ' + value.era);\n }\n eraIndex = cycleValue(eraIndex, amount, 0, eras.length - 1, options?.round);\n mutable.era = eras[eraIndex];\n\n // Constrain the year and other fields within the era, so the era doesn't change when we balance below.\n constrain(mutable);\n break;\n }\n case 'year': {\n if (mutable.calendar.isInverseEra?.(mutable)) {\n amount = -amount;\n }\n\n // The year field should not cycle within the era as that can cause weird behavior affecting other fields.\n // We need to also allow values < 1 so that decrementing goes to the previous era. If we get -Infinity back\n // we know we wrapped around after reaching 9999 (the maximum), so set the year back to 1.\n mutable.year = cycleValue(value.year, amount, -Infinity, 9999, options?.round);\n if (mutable.year === -Infinity) {\n mutable.year = 1;\n }\n\n if (mutable.calendar.balanceYearMonth) {\n mutable.calendar.balanceYearMonth(mutable, value);\n }\n break;\n }\n case 'month':\n mutable.month = cycleValue(value.month, amount, 1, value.calendar.getMonthsInYear(value), options?.round);\n break;\n case 'day':\n mutable.day = cycleValue(value.day, amount, 1, value.calendar.getDaysInMonth(value), options?.round);\n break;\n default:\n throw new Error('Unsupported field ' + field);\n }\n\n if (value.calendar.balanceDate) {\n value.calendar.balanceDate(mutable);\n }\n\n constrain(mutable);\n return mutable;\n}\n\nexport function cycleTime(value: CalendarDateTime, field: TimeField, amount: number, options?: CycleTimeOptions): CalendarDateTime;\nexport function cycleTime(value: Time, field: TimeField, amount: number, options?: CycleTimeOptions): Time;\nexport function cycleTime(value: Time | CalendarDateTime, field: TimeField, amount: number, options?: CycleTimeOptions) {\n let mutable: Mutable<Time | CalendarDateTime> = value.copy();\n\n switch (field) {\n case 'hour': {\n let hours = value.hour;\n let min = 0;\n let max = 23;\n if (options?.hourCycle === 12) {\n let isPM = hours >= 12;\n min = isPM ? 12 : 0;\n max = isPM ? 23 : 11;\n }\n mutable.hour = cycleValue(hours, amount, min, max, options?.round);\n break;\n }\n case 'minute':\n mutable.minute = cycleValue(value.minute, amount, 0, 59, options?.round);\n break;\n case 'second':\n mutable.second = cycleValue(value.second, amount, 0, 59, options?.round);\n break;\n case 'millisecond':\n mutable.millisecond = cycleValue(value.millisecond, amount, 0, 999, options?.round);\n break;\n default:\n throw new Error('Unsupported field ' + field);\n }\n\n return mutable;\n}\n\nfunction cycleValue(value: number, amount: number, min: number, max: number, round = false) {\n if (round) {\n value += Math.sign(amount);\n\n if (value < min) {\n value = max;\n }\n\n let div = Math.abs(amount);\n if (amount > 0) {\n value = Math.ceil(value / div) * div;\n } else {\n value = Math.floor(value / div) * div;\n }\n\n if (value > max) {\n value = min;\n }\n } else {\n value += amount;\n if (value < min) {\n value = max - (min - value - 1);\n } else if (value > max) {\n value = min + (value - max - 1);\n }\n }\n\n return value;\n}\n\nexport function addZoned(dateTime: ZonedDateTime, duration: DateTimeDuration): ZonedDateTime {\n let ms: number;\n if ((duration.years != null && duration.years !== 0) || (duration.months != null && duration.months !== 0) || (duration.weeks != null && duration.weeks !== 0) || (duration.days != null && duration.days !== 0)) {\n let res = add(toCalendarDateTime(dateTime), {\n years: duration.years,\n months: duration.months,\n weeks: duration.weeks,\n days: duration.days\n });\n\n // Changing the date may change the timezone offset, so we need to recompute\n // using the 'compatible' disambiguation.\n ms = toAbsolute(res, dateTime.timeZone);\n } else {\n // Otherwise, preserve the offset of the original date.\n ms = epochFromDate(dateTime) - dateTime.offset;\n }\n\n // Perform time manipulation in milliseconds rather than on the original time fields to account for DST.\n // For example, adding one hour during a DST transition may result in the hour field staying the same or\n // skipping an hour. This results in the offset field changing value instead of the specified field.\n ms += duration.milliseconds || 0;\n ms += (duration.seconds || 0) * 1000;\n ms += (duration.minutes || 0) * 60 * 1000;\n ms += (duration.hours || 0) * 60 * 60 * 1000;\n\n let res = fromAbsolute(ms, dateTime.timeZone);\n return toCalendar(res, dateTime.calendar);\n}\n\nexport function subtractZoned(dateTime: ZonedDateTime, duration: DateTimeDuration): ZonedDateTime {\n return addZoned(dateTime, invertDuration(duration));\n}\n\nexport function cycleZoned(dateTime: ZonedDateTime, field: DateField | TimeField, amount: number, options?: CycleTimeOptions): ZonedDateTime {\n // For date fields, we want the time to remain consistent and the UTC offset to potentially change to account for DST changes.\n // For time fields, we want the time to change by the amount given. This may result in the hour field staying the same, but the UTC\n // offset changing in the case of a backward DST transition, or skipping an hour in the case of a forward DST transition.\n switch (field) {\n case 'hour': {\n let min = 0;\n let max = 23;\n if (options?.hourCycle === 12) {\n let isPM = dateTime.hour >= 12;\n min = isPM ? 12 : 0;\n max = isPM ? 23 : 11;\n }\n\n // The minimum and maximum hour may be affected by daylight saving time.\n // For example, it might jump forward at midnight, and skip 1am.\n // Or it might end at midnight and repeat the 11pm hour. To handle this, we get\n // the possible absolute times for the min and max, and find the maximum range\n // that is within the current day.\n let plainDateTime = toCalendarDateTime(dateTime);\n let minDate = toCalendar(setTime(plainDateTime, {hour: min}), new GregorianCalendar());\n let minAbsolute = [toAbsolute(minDate, dateTime.timeZone, 'earlier'), toAbsolute(minDate, dateTime.timeZone, 'later')]\n .filter(ms => fromAbsolute(ms, dateTime.timeZone).day === minDate.day)[0];\n\n let maxDate = toCalendar(setTime(plainDateTime, {hour: max}), new GregorianCalendar());\n let maxAbsolute = [toAbsolute(maxDate, dateTime.timeZone, 'earlier'), toAbsolute(maxDate, dateTime.timeZone, 'later')]\n .filter(ms => fromAbsolute(ms, dateTime.timeZone).day === maxDate.day).pop();\n\n // Since hours may repeat, we need to operate on the absolute time in milliseconds.\n // This is done in hours from the Unix epoch so that cycleValue works correctly,\n // and then converted back to milliseconds.\n let ms = epochFromDate(dateTime) - dateTime.offset;\n let hours = Math.floor(ms / ONE_HOUR);\n let remainder = ms % ONE_HOUR;\n ms = cycleValue(\n hours,\n amount,\n Math.floor(minAbsolute / ONE_HOUR),\n Math.floor(maxAbsolute / ONE_HOUR),\n options?.round\n ) * ONE_HOUR + remainder;\n\n // Now compute the new timezone offset, and convert the absolute time back to local time.\n return toCalendar(fromAbsolute(ms, dateTime.timeZone), dateTime.calendar);\n }\n case 'minute':\n case 'second':\n case 'millisecond':\n // @ts-ignore\n return cycleTime(dateTime, field, amount, options);\n case 'era':\n case 'year':\n case 'month':\n case 'day': {\n let res = cycleDate(toCalendarDateTime(dateTime), field, amount, options);\n let ms = toAbsolute(res, dateTime.timeZone);\n return toCalendar(fromAbsolute(ms, dateTime.timeZone), dateTime.calendar);\n }\n default:\n throw new Error('Unsupported field ' + field);\n }\n}\n\nexport function setZoned(dateTime: ZonedDateTime, fields: DateFields & TimeFields, disambiguation?: Disambiguation): ZonedDateTime {\n // Set the date/time fields, and recompute the UTC offset to account for DST changes.\n // We also need to validate by converting back to a local time in case hours are skipped during forward DST transitions.\n let plainDateTime = toCalendarDateTime(dateTime);\n let res = setTime(set(plainDateTime, fields), fields);\n\n // If the resulting plain date time values are equal, return the original time.\n // We don't want to change the offset when setting the time to the same value.\n if (res.compare(plainDateTime) === 0) {\n return dateTime;\n }\n\n let ms = toAbsolute(res, dateTime.timeZone, disambiguation);\n return toCalendar(fromAbsolute(ms, dateTime.timeZone), dateTime.calendar);\n}\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Portions of the code in this file are based on code from the TC39 Temporal proposal.\n// Original licensing can be found in the NOTICE file in the root directory of this source tree.\n\nimport {AnyCalendarDate, AnyDateTime, AnyTime, Calendar, DateFields, Disambiguation, TimeFields} from './types';\nimport {CalendarDate, CalendarDateTime, Time, ZonedDateTime} from './CalendarDate';\nimport {constrain} from './manipulation';\nimport {getExtendedYear, GregorianCalendar} from './calendars/GregorianCalendar';\nimport {getLocalTimeZone} from './queries';\nimport {Mutable} from './utils';\n\nexport function epochFromDate(date: AnyDateTime) {\n date = toCalendar(date, new GregorianCalendar());\n let year = getExtendedYear(date.era, date.year);\n return epochFromParts(year, date.month, date.day, date.hour, date.minute, date.second, date.millisecond);\n}\n\nfunction epochFromParts(year: number, month: number, day: number, hour: number, minute: number, second: number, millisecond: number) {\n // Note: Date.UTC() interprets one and two-digit years as being in the\n // 20th century, so don't use it\n let date = new Date();\n date.setUTCHours(hour, minute, second, millisecond);\n date.setUTCFullYear(year, month - 1, day);\n return date.getTime();\n}\n\nexport function getTimeZoneOffset(ms: number, timeZone: string) {\n // Fast path for UTC.\n if (timeZone === 'UTC') {\n return 0;\n }\n\n // Fast path: for local timezone after 1970, use native Date.\n if (ms > 0 && timeZone === getLocalTimeZone()) {\n return new Date(ms).getTimezoneOffset() * -60 * 1000;\n }\n\n let {year, month, day, hour, minute, second} = getTimeZoneParts(ms, timeZone);\n let utc = epochFromParts(year, month, day, hour, minute, second, 0);\n return utc - Math.floor(ms / 1000) * 1000;\n}\n\nconst formattersByTimeZone = new Map<string, Intl.DateTimeFormat>();\n\nfunction getTimeZoneParts(ms: number, timeZone: string) {\n let formatter = formattersByTimeZone.get(timeZone);\n if (!formatter) {\n formatter = new Intl.DateTimeFormat('en-US', {\n timeZone,\n hour12: false,\n era: 'short',\n year: 'numeric',\n month: 'numeric',\n day: 'numeric',\n hour: 'numeric',\n minute: 'numeric',\n second: 'numeric'\n });\n\n formattersByTimeZone.set(timeZone, formatter);\n }\n\n let parts = formatter.formatToParts(new Date(ms));\n let namedParts: {[name: string]: string} = {};\n for (let part of parts) {\n if (part.type !== 'literal') {\n namedParts[part.type] = part.value;\n }\n }\n\n\n return {\n // Firefox returns B instead of BC... https://bugzilla.mozilla.org/show_bug.cgi?id=1752253\n year: namedParts.era === 'BC' || namedParts.era === 'B' ? -namedParts.year + 1 : +namedParts.year,\n month: +namedParts.month,\n day: +namedParts.day,\n hour: namedParts.hour === '24' ? 0 : +namedParts.hour, // bugs.chromium.org/p/chromium/issues/detail?id=1045791\n minute: +namedParts.minute,\n second: +namedParts.second\n };\n}\n\nconst DAYMILLIS = 86400000;\n\nexport function possibleAbsolutes(date: CalendarDateTime, timeZone: string): number[] {\n let ms = epochFromDate(date);\n let earlier = ms - getTimeZoneOffset(ms - DAYMILLIS, timeZone);\n let later = ms - getTimeZoneOffset(ms + DAYMILLIS, timeZone);\n return getValidWallTimes(date, timeZone, earlier, later);\n}\n\nfunction getValidWallTimes(date: CalendarDateTime, timeZone: string, earlier: number, later: number): number[] {\n let found = earlier === later ? [earlier] : [earlier, later];\n return found.filter(absolute => isValidWallTime(date, timeZone, absolute));\n}\n\nfunction isValidWallTime(date: CalendarDateTime, timeZone: string, absolute: number) {\n let parts = getTimeZoneParts(absolute, timeZone);\n return date.year === parts.year\n && date.month === parts.month\n && date.day === parts.day\n && date.hour === parts.hour\n && date.minute === parts.minute\n && date.second === parts.second;\n}\n\nexport function toAbsolute(date: CalendarDate | CalendarDateTime, timeZone: string, disambiguation: Disambiguation = 'compatible'): number {\n let dateTime = toCalendarDateTime(date);\n\n // Fast path: if the time zone is UTC, use native Date.\n if (timeZone === 'UTC') {\n return epochFromDate(dateTime);\n }\n\n // Fast path: if the time zone is the local timezone and disambiguation is compatible, use native Date.\n if (timeZone === getLocalTimeZone() && disambiguation === 'compatible') {\n dateTime = toCalendar(dateTime, new GregorianCalendar());\n\n // Don't use Date constructor here because two-digit years are interpreted in the 20th century.\n let date = new Date();\n let year = getExtendedYear(dateTime.era, dateTime.year);\n date.setFullYear(year, dateTime.month - 1, dateTime.day);\n date.setHours(dateTime.hour, dateTime.minute, dateTime.second, dateTime.millisecond);\n return date.getTime();\n }\n\n let ms = epochFromDate(dateTime);\n let offsetBefore = getTimeZoneOffset(ms - DAYMILLIS, timeZone);\n let offsetAfter = getTimeZoneOffset(ms + DAYMILLIS, timeZone);\n let valid = getValidWallTimes(dateTime, timeZone, ms - offsetBefore, ms - offsetAfter);\n\n if (valid.length === 1) {\n return valid[0];\n }\n\n if (valid.length > 1) {\n switch (disambiguation) {\n // 'compatible' means 'earlier' for \"fall back\" transitions\n case 'compatible':\n case 'earlier':\n return valid[0];\n case 'later':\n return valid[valid.length - 1];\n case 'reject':\n throw new RangeError('Multiple possible absolute times found');\n }\n }\n\n switch (disambiguation) {\n case 'earlier':\n return Math.min(ms - offsetBefore, ms - offsetAfter);\n // 'compatible' means 'later' for \"spring forward\" transitions\n case 'compatible':\n case 'later':\n return Math.max(ms - offsetBefore, ms - offsetAfter);\n case 'reject':\n throw new RangeError('No such absolute time found');\n }\n}\n\nexport function toDate(dateTime: CalendarDate | CalendarDateTime, timeZone: string, disambiguation: Disambiguation = 'compatible'): Date {\n return new Date(toAbsolute(dateTime, timeZone, disambiguation));\n}\n\n/**\n * Takes a Unix epoch (milliseconds since 1970) and converts it to the provided time zone.\n */\nexport function fromAbsolute(ms: number, timeZone: string): ZonedDateTime {\n let offset = getTimeZoneOffset(ms, timeZone);\n let date = new Date(ms + offset);\n let year = date.getUTCFullYear();\n let month = date.getUTCMonth() + 1;\n let day = date.getUTCDate();\n let hour = date.getUTCHours();\n let minute = date.getUTCMinutes();\n let second = date.getUTCSeconds();\n let millisecond = date.getUTCMilliseconds();\n\n return new ZonedDateTime(year, month, day, timeZone, offset, hour, minute, second, millisecond);\n}\n\n/**\n * Takes a `Date` object and converts it to the provided time zone.\n */\nexport function fromDate(date: Date, timeZone: string): ZonedDateTime {\n return fromAbsolute(date.getTime(), timeZone);\n}\n\nexport function fromDateToLocal(date: Date): ZonedDateTime {\n return fromDate(date, getLocalTimeZone());\n}\n\n/** Converts a value with date components such as a `CalendarDateTime` or `ZonedDateTime` into a `CalendarDate`. */\nexport function toCalendarDate(dateTime: AnyCalendarDate): CalendarDate {\n return new CalendarDate(dateTime.calendar, dateTime.era, dateTime.year, dateTime.month, dateTime.day);\n}\n\nexport function toDateFields(date: AnyCalendarDate): DateFields {\n return {\n era: date.era,\n year: date.year,\n month: date.month,\n day: date.day\n };\n}\n\nexport function toTimeFields(date: AnyTime): TimeFields {\n return {\n hour: date.hour,\n minute: date.minute,\n second: date.second,\n millisecond: date.millisecond\n };\n}\n\n/**\n * Converts a date value to a `CalendarDateTime`. An optional `Time` value can be passed to set the time\n * of the resulting value, otherwise it will default to midnight.\n */\nexport function toCalendarDateTime(date: CalendarDate | CalendarDateTime | ZonedDateTime, time?: AnyTime): CalendarDateTime {\n let hour = 0, minute = 0, second = 0, millisecond = 0;\n if ('timeZone' in date) {\n ({hour, minute, second, millisecond} = date);\n } else if ('hour' in date && !time) {\n return date;\n }\n\n if (time) {\n ({hour, minute, second, millisecond} = time);\n }\n\n return new CalendarDateTime(\n date.calendar,\n date.era,\n date.year,\n date.month,\n date.day,\n hour,\n minute,\n second,\n millisecond\n );\n}\n\n/** Extracts the time components from a value containing a date and time. */\nexport function toTime(dateTime: CalendarDateTime | ZonedDateTime): Time {\n return new Time(dateTime.hour, dateTime.minute, dateTime.second, dateTime.millisecond);\n}\n\n/** Converts a date from one calendar system to another. */\nexport function toCalendar<T extends AnyCalendarDate>(date: T, calendar: Calendar): T {\n if (date.calendar.identifier === calendar.identifier) {\n return date;\n }\n\n let calendarDate = calendar.fromJulianDay(date.calendar.toJulianDay(date));\n let copy: Mutable<T> = date.copy();\n copy.calendar = calendar;\n copy.era = calendarDate.era;\n copy.year = calendarDate.year;\n copy.month = calendarDate.month;\n copy.day = calendarDate.day;\n constrain(copy);\n return copy;\n}\n\n/**\n * Converts a date value to a `ZonedDateTime` in the provided time zone. The `disambiguation` option can be set\n * to control how values that fall on daylight saving time changes are interpreted.\n */\nexport function toZoned(date: CalendarDate | CalendarDateTime | ZonedDateTime, timeZone: string, disambiguation?: Disambiguation): ZonedDateTime {\n if (date instanceof ZonedDateTime) {\n if (date.timeZone === timeZone) {\n return date;\n }\n\n return toTimeZone(date, timeZone);\n }\n\n let ms = toAbsolute(date, timeZone, disambiguation);\n return fromAbsolute(ms, timeZone);\n}\n\nexport function zonedToDate(date: ZonedDateTime) {\n let ms = epochFromDate(date) - date.offset;\n return new Date(ms);\n}\n\n/** Converts a `ZonedDateTime` from one time zone to another. */\nexport function toTimeZone(date: ZonedDateTime, timeZone: string): ZonedDateTime {\n let ms = epochFromDate(date) - date.offset;\n return toCalendar(fromAbsolute(ms, timeZone), date.calendar);\n}\n\n/** Converts the given `ZonedDateTime` into the user's local time zone. */\nexport function toLocalTimeZone(date: ZonedDateTime): ZonedDateTime {\n return toTimeZone(date, getLocalTimeZone());\n}\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Portions of the code in this file are based on code from ICU.\n// Original licensing can be found in the NOTICE file in the root directory of this source tree.\n\nimport {AnyCalendarDate, Calendar} from '../types';\nimport {CalendarDate} from '../CalendarDate';\nimport {mod, Mutable} from '../utils';\n\nconst EPOCH = 1721426; // 001/01/03 Julian C.E.\nexport function gregorianToJulianDay(era: string, year: number, month: number, day: number): number {\n year = getExtendedYear(era, year);\n\n let y1 = year - 1;\n let monthOffset = -2;\n if (month <= 2) {\n monthOffset = 0;\n } else if (isLeapYear(year)) {\n monthOffset = -1;\n }\n\n return (\n EPOCH -\n 1 +\n 365 * y1 +\n Math.floor(y1 / 4) -\n Math.floor(y1 / 100) +\n Math.floor(y1 / 400) +\n Math.floor((367 * month - 362) / 12 + monthOffset + day)\n );\n}\n\nexport function isLeapYear(year: number): boolean {\n return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n}\n\nexport function getExtendedYear(era: string, year: number): number {\n return era === 'BC' ? 1 - year : year;\n}\n\nexport function fromExtendedYear(year: number): [string, number] {\n let era = 'AD';\n if (year <= 0) {\n era = 'BC';\n year = 1 - year;\n }\n\n return [era, year];\n}\n\nconst daysInMonth = {\n standard: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],\n leapyear: [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n};\n\n/**\n * The Gregorian calendar is the most commonly used calendar system in the world. It supports two eras: BC, and AD.\n * Years always contain 12 months, and 365 or 366 days depending on whether it is a leap year.\n */\nexport class GregorianCalendar implements Calendar {\n identifier = 'gregory';\n\n fromJulianDay(jd: number): CalendarDate {\n let jd0 = jd;\n let depoch = jd0 - EPOCH;\n let quadricent = Math.floor(depoch / 146097);\n let dqc = mod(depoch, 146097);\n let cent = Math.floor(dqc / 36524);\n let dcent = mod(dqc, 36524);\n let quad = Math.floor(dcent / 1461);\n let dquad = mod(dcent, 1461);\n let yindex = Math.floor(dquad / 365);\n\n let extendedYear = quadricent * 400 + cent * 100 + quad * 4 + yindex + (cent !== 4 && yindex !== 4 ? 1 : 0);\n let [era, year] = fromExtendedYear(extendedYear);\n let yearDay = jd0 - gregorianToJulianDay(era, year, 1, 1);\n let leapAdj = 2;\n if (jd0 < gregorianToJulianDay(era, year, 3, 1)) {\n leapAdj = 0;\n } else if (isLeapYear(year)) {\n leapAdj = 1;\n }\n let month = Math.floor(((yearDay + leapAdj) * 12 + 373) / 367);\n let day = jd0 - gregorianToJulianDay(era, year, month, 1) + 1;\n\n return new CalendarDate(era, year, month, day);\n }\n\n toJulianDay(date: AnyCalendarDate): number {\n return gregorianToJulianDay(date.era, date.year, date.month, date.day);\n }\n\n getDaysInMonth(date: AnyCalendarDate): number {\n return daysInMonth[isLeapYear(date.year) ? 'leapyear' : 'standard'][date.month - 1];\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n getMonthsInYear(date: AnyCalendarDate): number {\n return 12;\n }\n\n getDaysInYear(date: AnyCalendarDate): number {\n return isLeapYear(date.year) ? 366 : 365;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n getYearsInEra(date: AnyCalendarDate): number {\n return 9999;\n }\n\n getEras() {\n return ['BC', 'AD'];\n }\n\n isInverseEra(date: AnyCalendarDate): boolean {\n return date.era === 'BC';\n }\n\n balanceDate(date: Mutable<AnyCalendarDate>) {\n if (date.year <= 0) {\n date.era = date.era === 'BC' ? 'AD' : 'BC';\n date.year = 1 - date.year;\n }\n }\n}\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {CalendarDate, CalendarDateTime} from './CalendarDate';\n\nexport type Mutable<T> = {\n -readonly[P in keyof T]: T[P]\n};\n\nexport function mod(amount: number, numerator: number): number {\n return amount - numerator * Math.floor(amount / numerator);\n}\n\nexport function copy(date: CalendarDate): Mutable<CalendarDate> {\n if (date.era) {\n return new CalendarDate(date.calendar, date.era, date.year, date.month, date.day);\n } else {\n return new CalendarDate(date.calendar, date.year, date.month, date.day);\n }\n}\n\nexport function copyDateTime(date: CalendarDateTime): Mutable<CalendarDateTime> {\n if (date.era) {\n return new CalendarDateTime(date.calendar, date.era, date.year, date.month, date.day, date.hour, date.minute, date.second, date.millisecond);\n } else {\n return new CalendarDateTime(date.calendar, date.year, date.month, date.day, date.hour, date.minute, date.second);\n }\n}\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {AnyCalendarDate, AnyTime} from './types';\nimport {CalendarDate, CalendarDateTime, ZonedDateTime} from './CalendarDate';\nimport {fromAbsolute, toAbsolute, toCalendar, toCalendarDate} from './conversion';\nimport {weekStartData} from './weekStartData';\n\ntype DateValue = CalendarDate | CalendarDateTime | ZonedDateTime;\n\n/** Returns whether the given dates occur on the same day, regardless of the time or calendar system. */\nexport function isSameDay(a: DateValue, b: DateValue): boolean {\n b = toCalendar(b, a.calendar);\n return a.era === b.era && a.year === b.year && a.month === b.month && a.day === b.day;\n}\n\n/** Returns whether the given dates occur in the same month, using the calendar system of the first date. */\nexport function isSameMonth(a: DateValue, b: DateValue): boolean {\n b = toCalendar(b, a.calendar);\n // In the Japanese calendar, months can span multiple eras/years, so only compare the first of the month.\n a = startOfMonth(a);\n b = startOfMonth(b);\n return a.era === b.era && a.year === b.year && a.month === b.month;\n}\n\n/** Returns whether the given dates occur in the same year, using the calendar system of the first date. */\nexport function isSameYear(a: DateValue, b: DateValue): boolean {\n b = toCalendar(b, a.calendar);\n a = startOfYear(a);\n b = startOfYear(b);\n return a.era === b.era && a.year === b.year;\n}\n\n/** Returns whether the given dates occur on the same day, and are of the same calendar system. */\nexport function isEqualDay(a: DateValue, b: DateValue): boolean {\n return a.calendar.identifier === b.calendar.identifier && a.era === b.era && a.year === b.year && a.month === b.month && a.day === b.day;\n}\n\n/** Returns whether the given dates occur in the same month, and are of the same calendar system. */\nexport function isEqualMonth(a: DateValue, b: DateValue): boolean {\n a = startOfMonth(a);\n b = startOfMonth(b);\n return a.calendar.identifier === b.calendar.identifier && a.era === b.era && a.year === b.year && a.month === b.month;\n}\n\n/** Returns whether the given dates occur in the same year, and are of the same calendar system. */\nexport function isEqualYear(a: DateValue, b: DateValue): boolean {\n a = startOfYear(a);\n b = startOfYear(b);\n return a.calendar.identifier === b.calendar.identifier && a.era === b.era && a.year === b.year;\n}\n\n/** Returns whether the date is today in the given time zone. */\nexport function isToday(date: DateValue, timeZone: string): boolean {\n return isSameDay(date, today(timeZone));\n}\n\n/**\n * Returns the day of week for the given date and locale. Days are numbered from zero to six,\n * where zero is the first day of the week in the given locale. For example, in the United States,\n * the first day of the week is Sunday, but in France it is Monday.\n */\nexport function getDayOfWeek(date: DateValue, locale: string): number {\n let julian = date.calendar.toJulianDay(date);\n\n // If julian is negative, then julian % 7 will be negative, so we adjust\n // accordingly. Julian day 0 is Monday.\n let dayOfWeek = Math.ceil(julian + 1 - getWeekStart(locale)) % 7;\n if (dayOfWeek < 0) {\n dayOfWeek += 7;\n }\n\n return dayOfWeek;\n}\n\n/** Returns the current time in the given time zone. */\nexport function now(timeZone: string): ZonedDateTime {\n return fromAbsolute(Date.now(), timeZone);\n}\n\n/** Returns today's date in the given time zone. */\nexport function today(timeZone: string): CalendarDate {\n return toCalendarDate(now(timeZone));\n}\n\nexport function compareDate(a: AnyCalendarDate, b: AnyCalendarDate): number {\n return a.calendar.toJulianDay(a) - b.calendar.toJulianDay(b);\n}\n\nexport function compareTime(a: AnyTime, b: AnyTime): number {\n return timeToMs(a) - timeToMs(b);\n}\n\nfunction timeToMs(a: AnyTime): number {\n return a.hour * 60 * 60 * 1000 + a.minute * 60 * 1000 + a.second * 1000 + a.millisecond;\n}\n\n/**\n * Returns the number of hours in the given date and time zone.\n * Usually this is 24, but it could be 23 or 25 if the date is on a daylight saving transition.\n */\nexport function getHoursInDay(a: CalendarDate, timeZone: string): number {\n let ms = toAbsolute(a, timeZone);\n let tomorrow = a.add({days: 1});\n let tomorrowMs = toAbsolute(tomorrow, timeZone);\n return (tomorrowMs - ms) / 3600000;\n}\n\nlet localTimeZone = null;\n\n/** Returns the time zone identifier for the current user. */\nexport function getLocalTimeZone(): string {\n // TODO: invalidate this somehow?\n if (localTimeZone == null) {\n localTimeZone = new Intl.DateTimeFormat().resolvedOptions().timeZone;\n }\n\n return localTimeZone;\n}\n\n/** Returns the first date of the month for the given date. */\nexport function startOfMonth(date: ZonedDateTime): ZonedDateTime;\nexport function startOfMonth(date: CalendarDateTime): CalendarDateTime;\nexport function startOfMonth(date: CalendarDate): CalendarDate;\nexport function startOfMonth(date: DateValue): DateValue;\nexport function startOfMonth(date: DateValue): DateValue {\n // Use `subtract` instead of `set` so we don't get constrained in an era.\n return date.subtract({days: date.day - 1});\n}\n\n/** Returns the last date of the month for the given date. */\nexport function endOfMonth(date: ZonedDateTime): ZonedDateTime;\nexport function endOfMonth(date: CalendarDateTime): CalendarDateTime;\nexport function endOfMonth(date: CalendarDate): CalendarDate;\nexport function endOfMonth(date: DateValue): DateValue;\nexport function endOfMonth(date: DateValue): DateValue {\n return date.add({days: date.calendar.getDaysInMonth(date) - date.day});\n}\n\n/** Returns the first day of the year for the given date. */\nexport function startOfYear(date: ZonedDateTime): ZonedDateTime;\nexport function startOfYear(date: CalendarDateTime): CalendarDateTime;\nexport function startOfYear(date: CalendarDate): CalendarDate;\nexport function startOfYear(date: DateValue): DateValue;\nexport function startOfYear(date: DateValue): DateValue {\n return startOfMonth(date.subtract({months: date.month - 1}));\n}\n\n/** Returns the last day of the year for the given date. */\nexport function endOfYear(date: ZonedDateTime): ZonedDateTime;\nexport function endOfYear(date: CalendarDateTime): CalendarDateTime;\nexport function endOfYear(date: CalendarDate): CalendarDate;\nexport function endOfYear(date: DateValue): DateValue;\nexport function endOfYear(date: DateValue): DateValue {\n return endOfMonth(date.add({months: date.calendar.getMonthsInYear(date) - date.month}));\n}\n\nexport function getMinimumMonthInYear(date: AnyCalendarDate) {\n if (date.calendar.getMinimumMonthInYear) {\n return date.calendar.getMinimumMonthInYear(date);\n }\n\n return 1;\n}\n\nexport function getMinimumDayInMonth(date: AnyCalendarDate) {\n if (date.calendar.getMinimumDayInMonth) {\n return date.calendar.getMinimumDayInMonth(date);\n }\n\n return 1;\n}\n\n/** Returns the first date of the week for the given date and locale. */\nexport function startOfWeek(date: ZonedDateTime, locale: string): ZonedDateTime;\nexport function startOfWeek(date: CalendarDateTime, locale: string): CalendarDateTime;\nexport function startOfWeek(date: CalendarDate, locale: string): CalendarDate;\nexport function startOfWeek(date: DateValue, locale: string): DateValue;\nexport function startOfWeek(date: DateValue, locale: string): DateValue {\n let dayOfWeek = getDayOfWeek(date, locale);\n return date.subtract({days: dayOfWeek});\n}\n\n/** Returns the last date of the week for the given date and locale. */\nexport function endOfWeek(date: ZonedDateTime, locale: string): ZonedDateTime;\nexport function endOfWeek(date: CalendarDateTime, locale: string): CalendarDateTime;\nexport function endOfWeek(date: CalendarDate, locale: string): CalendarDate;\nexport function endOfWeek(date: DateValue, locale: string): DateValue {\n return startOfWeek(date, locale).add({days: 6});\n}\n\nconst cachedRegions = new Map<string, string>();\n\nfunction getRegion(locale: string) {\n // If the Intl.Locale API is available, use it to get the region for the locale.\n // @ts-ignore\n if (Intl.Locale) {\n // Constructing an Intl.Locale is expensive, so cache the result.\n let region = cachedRegions.get(locale);\n if (!region) {\n // @ts-ignore\n region = new Intl.Locale(locale).maximize().region;\n cachedRegions.set(locale, region);\n }\n return region;\n }\n\n // If not, just try splitting the string.\n // If the second part of the locale string is 'u',\n // then this is a unicode extension, so ignore it.\n // Otherwise, it should be the region.\n let part = locale.split('-')[1];\n return part === 'u' ? null : part;\n}\n\nfunction getWeekStart(locale: string) {\n // TODO: use Intl.Locale for this once browsers support the weekInfo property\n // https://github.com/tc39/proposal-intl-locale-info\n let region = getRegion(locale);\n return weekStartData[region] || 0;\n}\n\n/** Returns the number of weeks in the given month and locale. */\nexport function getWeeksInMonth(date: DateValue, locale: string): number {\n let days = date.calendar.getDaysInMonth(date);\n return Math.ceil((getDayOfWeek(startOfMonth(date), locale) + days) / 7);\n}\n\n/** Returns the lesser of the two provider dates. */\nexport function minDate<A extends DateValue, B extends DateValue>(a: A, b: B): A | B {\n if (a && b) {\n return a.compare(b) <= 0 ? a : b;\n }\n\n return a || b;\n}\n\n/** Returns the greater of the two provider dates. */\nexport function maxDate<A extends DateValue, B extends DateValue>(a: A, b: B): A | B {\n if (a && b) {\n return a.compare(b) >= 0 ? a : b;\n }\n\n return a || b;\n}\n\nconst WEEKEND_DATA = {\n AF: [4, 5],\n AE: [5, 6],\n BH: [5, 6],\n DZ: [5, 6],\n EG: [5, 6],\n IL: [5, 6],\n IQ: [5, 6],\n IR: [5, 5],\n JO: [5, 6],\n KW: [5, 6],\n LY: [5, 6],\n OM: [5, 6],\n QA: [5, 6],\n SA: [5, 6],\n SD: [5, 6],\n SY: [5, 6],\n YE: [5, 6]\n};\n\n/** Returns whether the given date is on a weekend in the given locale. */\nexport function isWeekend(date: DateValue, locale: string): boolean {\n let julian = date.calendar.toJulianDay(date);\n\n // If julian is negative, then julian % 7 will be negative, so we adjust\n // accordingly. Julian day 0 is Monday.\n let dayOfWeek = Math.ceil(julian + 1) % 7;\n if (dayOfWeek < 0) {\n dayOfWeek += 7;\n }\n\n let region = getRegion(locale);\n // Use Intl.Locale for this once weekInfo is supported.\n // https://github.com/tc39/proposal-intl-locale-info\n let [start, end] = WEEKEND_DATA[region] || [6, 0];\n return dayOfWeek === start || dayOfWeek === end;\n}\n\n/** Returns whether the given date is on a weekday in the given locale. */\nexport function isWeekday(date: DateValue, locale: string): boolean {\n return !isWeekend(date, locale);\n}\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Data from https://github.com/unicode-cldr/cldr-core/blob/master/supplemental/weekData.json\n// Locales starting on Sunday have been removed for compression.\nexport const weekStartData = {\n '001': 1,\n AD: 1,\n AE: 6,\n AF: 6,\n AI: 1,\n AL: 1,\n AM: 1,\n AN: 1,\n AR: 1,\n AT: 1,\n AU: 1,\n AX: 1,\n AZ: 1,\n BA: 1,\n BE: 1,\n BG: 1,\n BH: 6,\n BM: 1,\n BN: 1,\n BY: 1,\n CH: 1,\n CL: 1,\n CM: 1,\n CN: 1,\n CR: 1,\n CY: 1,\n CZ: 1,\n DE: 1,\n DJ: 6,\n DK: 1,\n DZ: 6,\n EC: 1,\n EE: 1,\n EG: 6,\n ES: 1,\n FI: 1,\n FJ: 1,\n FO: 1,\n FR: 1,\n GB: 1,\n GE: 1,\n GF: 1,\n GP: 1,\n GR: 1,\n HR: 1,\n HU: 1,\n IE: 1,\n IQ: 6,\n IR: 6,\n IS: 1,\n IT: 1,\n JO: 6,\n KG: 1,\n KW: 6,\n KZ: 1,\n LB: 1,\n LI: 1,\n LK: 1,\n LT: 1,\n LU: 1,\n LV: 1,\n LY: 6,\n MC: 1,\n MD: 1,\n ME: 1,\n MK: 1,\n MN: 1,\n MQ: 1,\n MV: 5,\n MY: 1,\n NL: 1,\n NO: 1,\n NZ: 1,\n OM: 6,\n PL: 1,\n QA: 6,\n RE: 1,\n RO: 1,\n RS: 1,\n RU: 1,\n SD: 6,\n SE: 1,\n SI: 1,\n SK: 1,\n SM: 1,\n SY: 6,\n TJ: 1,\n TM: 1,\n TR: 1,\n UA: 1,\n UY: 1,\n UZ: 1,\n VA: 1,\n VN: 1,\n XK: 1\n};\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {AnyDateTime, DateTimeDuration, Disambiguation} from './types';\nimport {CalendarDate, CalendarDateTime, Time, ZonedDateTime} from './CalendarDate';\nimport {epochFromDate, fromAbsolute, possibleAbsolutes, toAbsolute, toCalendar, toCalendarDateTime, toTimeZone} from './conversion';\nimport {getLocalTimeZone} from './queries';\nimport {GregorianCalendar} from './calendars/GregorianCalendar';\nimport {Mutable} from './utils';\n\nconst TIME_RE = /^(\\d{2})(?::(\\d{2}))?(?::(\\d{2}))?(\\.\\d+)?$/;\nconst DATE_RE = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\nconst DATE_TIME_RE = /^(\\d{4})-(\\d{2})-(\\d{2})(?:T(\\d{2}))?(?::(\\d{2}))?(?::(\\d{2}))?(\\.\\d+)?$/;\nconst ZONED_DATE_TIME_RE = /^(\\d{4})-(\\d{2})-(\\d{2})(?:T(\\d{2}))?(?::(\\d{2}))?(?::(\\d{2}))?(\\.\\d+)?(?:([+-]\\d{2})(?::?(\\d{2}))?)?\\[(.*?)\\]$/;\nconst ABSOLUTE_RE = /^(\\d{4})-(\\d{2})-(\\d{2})(?:T(\\d{2}))?(?::(\\d{2}))?(?::(\\d{2}))?(\\.\\d+)?(?:(?:([+-]\\d{2})(?::?(\\d{2}))?)|Z)$/;\nconst DATE_TIME_DURATION_RE =\n /^((?<negative>-)|\\+)?P((?<years>\\d*)Y)?((?<months>\\d*)M)?((?<weeks>\\d*)W)?((?<days>\\d*)D)?((?<time>T)((?<hours>\\d*[.,]?\\d{1,9})H)?((?<minutes>\\d*[.,]?\\d{1,9})M)?((?<seconds>\\d*[.,]?\\d{1,9})S)?)?$/;\nconst requiredDurationTimeGroups = ['hours', 'minutes', 'seconds'];\nconst requiredDurationGroups = ['years', 'months', 'weeks', 'days', ...requiredDurationTimeGroups];\n\n/** Parses an ISO 8601 time string. */\nexport function parseTime(value: string): Time {\n let m = value.match(TIME_RE);\n if (!m) {\n throw new Error('Invalid ISO 8601 time string: ' + value);\n }\n\n return new Time(\n parseNumber(m[1], 0, 23),\n m[2] ? parseNumber(m[2], 0, 59) : 0,\n m[3] ? parseNumber(m[3], 0, 59) : 0,\n m[4] ? parseNumber(m[4], 0, Infinity) * 1000 : 0\n );\n}\n\n/** Parses an ISO 8601 date string, with no time components. */\nexport function parseDate(value: string): CalendarDate {\n let m = value.match(DATE_RE);\n if (!m) {\n throw new Error('Invalid ISO 8601 date string: ' + value);\n }\n\n let date: Mutable<CalendarDate> = new CalendarDate(\n parseNumber(m[1], 0, 9999),\n parseNumber(m[2], 1, 12),\n 1\n );\n\n date.day = parseNumber(m[3], 0, date.calendar.getDaysInMonth(date));\n return date as CalendarDate;\n}\n\n/** Parses an ISO 8601 date and time string, with no time zone. */\nexport function parseDateTime(value: string): CalendarDateTime {\n let m = value.match(DATE_TIME_RE);\n if (!m) {\n throw new Error('Invalid ISO 8601 date time string: ' + value);\n }\n\n let date: Mutable<CalendarDateTime> = new CalendarDateTime(\n parseNumber(m[1], 1, 9999),\n parseNumber(m[2], 1, 12),\n 1,\n m[4] ? parseNumber(m[4], 0, 23) : 0,\n m[5] ? parseNumber(m[5], 0, 59) : 0,\n m[6] ? parseNumber(m[6], 0, 59) : 0,\n m[7] ? parseNumber(m[7], 0, Infinity) * 1000 : 0\n );\n\n date.day = parseNumber(m[3], 0, date.calendar.getDaysInMonth(date));\n return date as CalendarDateTime;\n}\n\n/**\n * Parses an ISO 8601 date and time string with a time zone extension and optional UTC offset\n * (e.g. \"2021-11-07T00:45[America/Los_Angeles]\" or \"2021-11-07T00:45-07:00[America/Los_Angeles]\").\n * Ambiguous times due to daylight saving time transitions are resolved according to the `disambiguation`\n * parameter.\n */\nexport function parseZonedDateTime(value: string, disambiguation?: Disambiguation): ZonedDateTime {\n let m = value.match(ZONED_DATE_TIME_RE);\n if (!m) {\n throw new Error('Invalid ISO 8601 date time string: ' + value);\n }\n\n let date: Mutable<ZonedDateTime> = new ZonedDateTime(\n parseNumber(m[1], 1, 9999),\n parseNumber(m[2], 1, 12),\n 1,\n m[10],\n 0,\n m[4] ? parseNumber(m[4], 0, 23) : 0,\n m[5] ? parseNumber(m[5], 0, 59) : 0,\n m[6] ? parseNumber(m[6], 0, 59) : 0,\n m[7] ? parseNumber(m[7], 0, Infinity) * 1000 : 0\n );\n\n date.day = parseNumber(m[3], 0, date.calendar.getDaysInMonth(date));\n\n let plainDateTime = toCalendarDateTime(date as ZonedDateTime);\n\n let ms: number;\n if (m[8]) {\n date.offset = parseNumber(m[8], -23, 23) * 60 * 60 * 1000 + parseNumber(m[9] ?? '0', 0, 59) * 60 * 1000;\n ms = epochFromDate(date as ZonedDateTime) - date.offset;\n\n // Validate offset against parsed date.\n let absolutes = possibleAbsolutes(plainDateTime, date.timeZone);\n if (!absolutes.includes(ms)) {\n throw new Error(`Offset ${offsetToString(date.offset)} is invalid for ${dateTimeToString(date)} in ${date.timeZone}`);\n }\n } else {\n // Convert to absolute and back to fix invalid times due to DST.\n ms = toAbsolute(toCalendarDateTime(plainDateTime), date.timeZone, disambiguation);\n }\n\n return fromAbsolute(ms, date.timeZone);\n}\n\n/**\n * Parses an ISO 8601 date and time string with a UTC offset (e.g. \"2021-11-07T07:45:00Z\"\n * or \"2021-11-07T07:45:00-07:00\"). The result is converted to the provided time zone.\n */\nexport function parseAbsolute(value: string, timeZone: string): ZonedDateTime {\n let m = value.match(ABSOLUTE_RE);\n if (!m) {\n throw new Error('Invalid ISO 8601 date time string: ' + value);\n }\n\n let date: Mutable<ZonedDateTime> = new ZonedDateTime(\n parseNumber(m[1], 1, 9999),\n parseNumber(m[2], 1, 12),\n 1,\n timeZone,\n 0,\n m[4] ? parseNumber(m[4], 0, 23) : 0,\n m[5] ? parseNumber(m[5], 0, 59) : 0,\n m[6] ? parseNumber(m[6], 0, 59) : 0,\n m[7] ? parseNumber(m[7], 0, Infinity) * 1000 : 0\n );\n\n date.day = parseNumber(m[3], 0, date.calendar.getDaysInMonth(date));\n\n if (m[8]) {\n date.offset = parseNumber(m[8], -23, 23) * 60 * 60 * 1000 + parseNumber(m[9] ?? '0', 0, 59) * 60 * 1000;\n }\n\n return toTimeZone(date as ZonedDateTime, timeZone);\n}\n\n/**\n * Parses an ISO 8601 date and time string with a UTC offset (e.g. \"2021-11-07T07:45:00Z\"\n * or \"2021-11-07T07:45:00-07:00\"). The result is converted to the user's local time zone.\n */\nexport function parseAbsoluteToLocal(value: string): ZonedDateTime {\n return parseAbsolute(value, getLocalTimeZone());\n}\n\nfunction parseNumber(value: string, min: number, max: number) {\n let val = Number(value);\n if (val < min || val > max) {\n throw new RangeError(`Value out of range: ${min} <= ${val} <= ${max}`);\n }\n\n return val;\n}\n\nexport function timeToString(time: Time): string {\n return `${String(time.hour).padStart(2, '0')}:${String(time.minute).padStart(2, '0')}:${String(time.second).padStart(2, '0')}${time.millisecond ? String(time.millisecond / 1000).slice(1) : ''}`;\n}\n\nexport function dateToString(date: CalendarDate): string {\n let gregorianDate = toCalendar(date, new GregorianCalendar());\n return `${String(gregorianDate.year).padStart(4, '0')}-${String(gregorianDate.month).padStart(2, '0')}-${String(gregorianDate.day).padStart(2, '0')}`;\n}\n\nexport function dateTimeToString(date: AnyDateTime): string {\n // @ts-ignore\n return `${dateToString(date)}T${timeToString(date)}`;\n}\n\nfunction offsetToString(offset: number) {\n let sign = Math.sign(offset) < 0 ? '-' : '+';\n offset = Math.abs(offset);\n let offsetHours = Math.floor(offset / (60 * 60 * 1000));\n let offsetMinutes = (offset % (60 * 60 * 1000)) / (60 * 1000);\n return `${sign}${String(offsetHours).padStart(2, '0')}:${String(offsetMinutes).padStart(2, '0')}`;\n}\n\nexport function zonedDateTimeToString(date: ZonedDateTime): string {\n return `${dateTimeToString(date)}${offsetToString(date.offset)}[${date.timeZone}]`;\n}\n\n/**\n * Parses an ISO 8601 duration string (e.g. \"P3Y6M6W4DT12H30M5S\").\n * @param value An ISO 8601 duration string.\n * @returns A DateTimeDuration object.\n */\nexport function parseDuration(value: string): Required<DateTimeDuration> {\n const match = value.match(DATE_TIME_DURATION_RE);\n\n if (!match) {\n throw new Error(`Invalid ISO 8601 Duration string: ${value}`);\n }\n\n const parseDurationGroup = (\n group: string | undefined,\n isNegative: boolean,\n min: number,\n max: number\n ): number => {\n if (!group) {\n return 0;\n }\n try {\n const sign = isNegative ? -1 : 1;\n return sign * parseNumber(group.replace(',', '.'), min, max);\n } catch {\n throw new Error(`Invalid ISO 8601 Duration string: ${value}`);\n }\n };\n\n const isNegative = !!match.groups?.negative;\n\n const hasRequiredGroups = requiredDurationGroups.some(group => match.groups?.[group]);\n\n if (!hasRequiredGroups) {\n throw new Error(`Invalid ISO 8601 Duration string: ${value}`);\n }\n\n const durationStringIncludesTime = match.groups?.time;\n\n if (durationStringIncludesTime) {\n const hasRequiredDurationTimeGroups = requiredDurationTimeGroups.some(group => match.groups?.[group]);\n if (!hasRequiredDurationTimeGroups) {\n throw new Error(`Invalid ISO 8601 Duration string: ${value}`);\n }\n }\n\n const duration: Mutable<DateTimeDuration> = {\n years: parseDurationGroup(match.groups?.years, isNegative, 0, 9999),\n months: parseDurationGroup(match.groups?.months, isNegative, 0, 12),\n weeks: parseDurationGroup(match.groups?.weeks, isNegative, 0, Infinity),\n days: parseDurationGroup(match.groups?.days, isNegative, 0, 31),\n hours: parseDurationGroup(match.groups?.hours, isNegative, 0, 23),\n minutes: parseDurationGroup(match.groups?.minutes, isNegative, 0, 59),\n seconds: parseDurationGroup(match.groups?.seconds, isNegative, 0, 59)\n };\n\n if (((duration.hours % 1) !== 0) && (duration.minutes || duration.seconds)) {\n throw new Error(`Invalid ISO 8601 Duration string: ${value} - only the smallest unit can be fractional`);\n }\n\n if (((duration.minutes % 1) !== 0) && duration.seconds) {\n throw new Error(`Invalid ISO 8601 Duration string: ${value} - only the smallest unit can be fractional`);\n }\n\n return duration as Required<DateTimeDuration>;\n}\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Portions of the code in this file are based on code from the TC39 Temporal proposal.\n// Original licensing can be found in the NOTICE file in the root directory of this source tree.\n\nimport {AnyCalendarDate} from '../types';\nimport {CalendarDate} from '../CalendarDate';\nimport {GregorianCalendar} from './GregorianCalendar';\nimport {Mutable} from '../utils';\n\nconst ERA_START_DATES = [[1868, 9, 8], [1912, 7, 30], [1926, 12, 25], [1989, 1, 8], [2019, 5, 1]];\nconst ERA_END_DATES = [[1912, 7, 29], [1926, 12, 24], [1989, 1, 7], [2019, 4, 30]];\nconst ERA_ADDENDS = [1867, 1911, 1925, 1988, 2018];\nconst ERA_NAMES = ['meiji', 'taisho', 'showa', 'heisei', 'reiwa'];\n\nfunction findEraFromGregorianDate(date: AnyCalendarDate) {\n const idx = ERA_START_DATES.findIndex(([year, month, day]) => {\n if (date.year < year) {\n return true;\n }\n\n if (date.year === year && date.month < month) {\n return true;\n }\n\n if (date.year === year && date.month === month && date.day < day) {\n return true;\n }\n\n return false;\n });\n\n if (idx === -1) {\n return ERA_START_DATES.length - 1;\n }\n\n if (idx === 0) {\n return 0;\n }\n\n return idx - 1;\n}\n\nfunction toGregorian(date: AnyCalendarDate) {\n let eraAddend = ERA_ADDENDS[ERA_NAMES.indexOf(date.era)];\n if (!eraAddend) {\n throw new Error('Unknown era: ' + date.era);\n }\n\n return new CalendarDate(\n date.year + eraAddend,\n date.month,\n date.day\n );\n}\n\n/**\n * The Japanese calendar is based on the Gregorian calendar, but with eras for the reign of each Japanese emperor.\n * Whenever a new emperor ascends to the throne, a new era begins and the year starts again from 1.\n * Note that eras before 1868 (Gregorian) are not currently supported by this implementation.\n */\nexport class JapaneseCalendar extends GregorianCalendar {\n identifier = 'japanese';\n\n fromJulianDay(jd: number): CalendarDate {\n let date = super.fromJulianDay(jd);\n let era = findEraFromGregorianDate(date);\n\n return new CalendarDate(\n this,\n ERA_NAMES[era],\n date.year - ERA_ADDENDS[era],\n date.month,\n date.day\n );\n }\n\n toJulianDay(date: AnyCalendarDate) {\n return super.toJulianDay(toGregorian(date));\n }\n\n balanceDate(date: Mutable<AnyCalendarDate>) {\n let gregorianDate = toGregorian(date);\n let era = findEraFromGregorianDate(gregorianDate);\n\n if (ERA_NAMES[era] !== date.era) {\n date.era = ERA_NAMES[era];\n date.year = gregorianDate.year - ERA_ADDENDS[era];\n }\n\n // Constrain in case we went before the first supported era.\n this.constrainDate(date);\n }\n\n constrainDate(date: Mutable<AnyCalendarDate>) {\n let idx = ERA_NAMES.indexOf(date.era);\n let end = ERA_END_DATES[idx];\n if (end != null) {\n let [endYear, endMonth, endDay] = end;\n\n // Constrain the year to the maximum possible value in the era.\n // Then constrain the month and day fields within that.\n let maxYear = endYear - ERA_ADDENDS[idx];\n date.year = Math.max(1, Math.min(maxYear, date.year));\n if (date.year === maxYear) {\n date.month = Math.min(endMonth, date.month);\n\n if (date.month === endMonth) {\n date.day = Math.min(endDay, date.day);\n }\n }\n }\n\n if (date.year === 1 && idx >= 0) {\n let [, startMonth, startDay] = ERA_START_DATES[idx];\n date.month = Math.max(startMonth, date.month);\n\n if (date.month === startMonth) {\n date.day = Math.max(startDay, date.day);\n }\n }\n }\n\n getEras() {\n return ERA_NAMES;\n }\n\n getYearsInEra(date: AnyCalendarDate): number {\n // Get the number of years in the era, taking into account the date's month and day fields.\n let era = ERA_NAMES.indexOf(date.era);\n let cur = ERA_START_DATES[era];\n let next = ERA_START_DATES[era + 1];\n if (next == null) {\n // 9999 gregorian is the maximum year allowed.\n return 9999 - cur[0] + 1;\n }\n\n let years = next[0] - cur[0];\n\n if (date.month < next[1] || (date.month === next[1] && date.day < next[2])) {\n years++;\n }\n\n return years;\n }\n\n getDaysInMonth(date: AnyCalendarDate): number {\n return super.getDaysInMonth(toGregorian(date));\n }\n\n getMinimumMonthInYear(date: AnyCalendarDate): number {\n let start = getMinimums(date);\n return start ? start[1] : 1;\n }\n\n getMinimumDayInMonth(date: AnyCalendarDate): number {\n let start = getMinimums(date);\n return start && date.month === start[1] ? start[2] : 1;\n }\n}\n\nfunction getMinimums(date: AnyCalendarDate) {\n if (date.year === 1) {\n let idx = ERA_NAMES.indexOf(date.era);\n return ERA_START_DATES[idx];\n }\n}\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Portions of the code in this file are based on code from ICU.\n// Original licensing can be found in the NOTICE file in the root directory of this source tree.\n\nimport {AnyCalendarDate} from '../types';\nimport {CalendarDate} from '../CalendarDate';\nimport {fromExtendedYear, getExtendedYear, GregorianCalendar} from './GregorianCalendar';\n\nconst BUDDHIST_ERA_START = -543;\n\n/**\n * The Buddhist calendar is the same as the Gregorian calendar, but counts years\n * starting from the birth of Buddha in 543 BC (Gregorian). It supports only one\n * era, identified as 'BE'.\n */\nexport class BuddhistCalendar extends GregorianCalendar {\n identifier = 'buddhist';\n\n fromJulianDay(jd: number): CalendarDate {\n let gregorianDate = super.fromJulianDay(jd);\n let year = getExtendedYear(gregorianDate.era, gregorianDate.year);\n return new CalendarDate(\n this,\n year - BUDDHIST_ERA_START,\n gregorianDate.month,\n gregorianDate.day\n );\n }\n\n toJulianDay(date: AnyCalendarDate) {\n return super.toJulianDay(toGregorian(date));\n }\n\n getEras() {\n return ['BE'];\n }\n\n getDaysInMonth(date: AnyCalendarDate): number {\n return super.getDaysInMonth(toGregorian(date));\n }\n\n balanceDate() {}\n}\n\nfunction toGregorian(date: AnyCalendarDate) {\n let [era, year] = fromExtendedYear(date.year + BUDDHIST_ERA_START);\n return new CalendarDate(\n era,\n year,\n date.month,\n date.day\n );\n}\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Portions of the code in this file are based on code from ICU.\n// Original licensing can be found in the NOTICE file in the root directory of this source tree.\n\nimport {AnyCalendarDate} from '../types';\nimport {CalendarDate} from '../CalendarDate';\nimport {fromExtendedYear, getExtendedYear, GregorianCalendar} from './GregorianCalendar';\nimport {Mutable} from '../utils';\n\nconst TAIWAN_ERA_START = 1911;\n\nfunction gregorianYear(date: AnyCalendarDate) {\n return date.era === 'minguo'\n ? date.year + TAIWAN_ERA_START\n : 1 - date.year + TAIWAN_ERA_START;\n}\n\nfunction gregorianToTaiwan(year: number): [string, number] {\n let y = year - TAIWAN_ERA_START;\n if (y > 0) {\n return ['minguo', y];\n } else {\n return ['before_minguo', 1 - y];\n }\n}\n\n/**\n * The Taiwanese calendar is the same as the Gregorian calendar, but years\n * are numbered starting from 1912 (Gregorian). Two eras are supported:\n * 'before_minguo' and 'minguo'.\n */\nexport class TaiwanCalendar extends GregorianCalendar {\n identifier = 'roc'; // Republic of China\n\n fromJulianDay(jd: number): CalendarDate {\n let date = super.fromJulianDay(jd);\n let extendedYear = getExtendedYear(date.era, date.year);\n let [era, year] = gregorianToTaiwan(extendedYear);\n return new CalendarDate(this, era, year, date.month, date.day);\n }\n\n toJulianDay(date: AnyCalendarDate) {\n return super.toJulianDay(toGregorian(date));\n }\n\n getEras() {\n return ['before_minguo', 'minguo'];\n }\n\n balanceDate(date: Mutable<AnyCalendarDate>) {\n let [era, year] = gregorianToTaiwan(gregorianYear(date));\n date.era = era;\n date.year = year;\n }\n\n isInverseEra(date: AnyCalendarDate): boolean {\n return date.era === 'before_minguo';\n }\n\n getDaysInMonth(date: AnyCalendarDate): number {\n return super.getDaysInMonth(toGregorian(date));\n }\n\n getYearsInEra(date: AnyCalendarDate): number {\n return date.era === 'before_minguo' ? 9999 : 9999 - TAIWAN_ERA_START;\n }\n}\n\nfunction toGregorian(date: AnyCalendarDate) {\n let [era, year] = fromExtendedYear(gregorianYear(date));\n return new CalendarDate(\n era,\n year,\n date.month,\n date.day\n );\n}\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Portions of the code in this file are based on code from ICU.\n// Original licensing can be found in the NOTICE file in the root directory of this source tree.\n\nimport {AnyCalendarDate, Calendar} from '../types';\nimport {CalendarDate} from '../CalendarDate';\nimport {mod} from '../utils';\n\nconst PERSIAN_EPOCH = 1948321; // 622/03/19 Julian C.E.\n\nfunction isLeapYear(year: number): boolean {\n let y0 = year > 0 ? year - 474 : year - 473;\n let y1 = mod(y0, 2820) + 474;\n\n return mod((y1 + 38) * 31, 128) < 31;\n}\n\nfunction persianToJulianDay(year: number, month: number, day: number): number {\n let y0 = year > 0 ? year - 474 : year - 473;\n let y1 = mod(y0, 2820) + 474;\n let offset = month <= 7 ? 31 * (month - 1) : 30 * (month - 1) + 6;\n\n return (\n PERSIAN_EPOCH -\n 1 +\n 1029983 * Math.floor(y0 / 2820) +\n 365 * (y1 - 1) +\n Math.floor((31 * y1 - 5) / 128) +\n offset +\n day\n );\n}\n\n/**\n * The Persian calendar is the main calendar used in Iran and Afghanistan. It has 12 months\n * in each year, the first 6 of which have 31 days, and the next 5 have 30 days. The 12th month\n * has either 29 or 30 days depending on whether it is a leap year. The Persian year starts\n * around the March equinox.\n */\nexport class PersianCalendar implements Calendar {\n identifier = 'persian';\n\n fromJulianDay(jd: number): CalendarDate {\n let d0 = jd - persianToJulianDay(475, 1, 1);\n let n2820 = Math.floor(d0 / 1029983);\n let d1 = mod(d0, 1029983);\n let y2820 = d1 === 1029982 ? 2820 : Math.floor((128 * d1 + 46878) / 46751);\n let year = 474 + 2820 * n2820 + y2820;\n if (year <= 0) {\n year--;\n }\n\n let yDay = jd - persianToJulianDay(year, 1, 1) + 1;\n let month = yDay <= 186 ? Math.ceil(yDay / 31) : Math.ceil((yDay - 6) / 31);\n let day = jd - persianToJulianDay(year, month, 1) + 1;\n\n return new CalendarDate(this, year, month, day);\n }\n\n toJulianDay(date: AnyCalendarDate): number {\n return persianToJulianDay(date.year, date.month, date.day);\n }\n\n getMonthsInYear(): number {\n return 12;\n }\n\n getDaysInMonth(date: AnyCalendarDate): number {\n if (date.month <= 6) {\n return 31;\n }\n\n if (date.month <= 11) {\n return 30;\n }\n\n return isLeapYear(date.year) ? 30 : 29;\n }\n\n getEras() {\n return ['AP'];\n }\n\n getYearsInEra(): number {\n // 9378-10-10 persian is 9999-12-31 gregorian.\n // Round down to 9377 to set the maximum full year.\n return 9377;\n }\n}\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Portions of the code in this file are based on code from ICU.\n// Original licensing can be found in the NOTICE file in the root directory of this source tree.\n\nimport {AnyCalendarDate} from '../types';\nimport {CalendarDate} from '../CalendarDate';\nimport {fromExtendedYear, GregorianCalendar, gregorianToJulianDay, isLeapYear} from './GregorianCalendar';\n\n// Starts in 78 AD,\nconst INDIAN_ERA_START = 78;\n\n// The Indian year starts 80 days later than the Gregorian year.\nconst INDIAN_YEAR_START = 80;\n\n/**\n * The Indian National Calendar is similar to the Gregorian calendar, but with\n * years numbered since the Saka era in 78 AD (Gregorian). There are 12 months\n * in each year, with either 30 or 31 days. Only one era identifier is supported: 'saka'.\n */\nexport class IndianCalendar extends GregorianCalendar {\n identifier = 'indian';\n\n fromJulianDay(jd: number): CalendarDate {\n // Gregorian date for Julian day\n let date = super.fromJulianDay(jd);\n\n // Year in Saka era\n let indianYear = date.year - INDIAN_ERA_START;\n\n // Day number in Gregorian year (starting from 0)\n let yDay = jd - gregorianToJulianDay(date.era, date.year, 1, 1);\n\n let leapMonth: number;\n if (yDay < INDIAN_YEAR_START) {\n // Day is at the end of the preceding Saka year\n indianYear--;\n\n // Days in leapMonth this year, previous Gregorian year\n leapMonth = isLeapYear(date.year - 1) ? 31 : 30;\n yDay += leapMonth + (31 * 5) + (30 * 3) + 10;\n } else {\n // Days in leapMonth this year\n leapMonth = isLeapYear(date.year) ? 31 : 30;\n yDay -= INDIAN_YEAR_START;\n }\n\n let indianMonth: number;\n let indianDay: number;\n if (yDay < leapMonth) {\n indianMonth = 1;\n indianDay = yDay + 1;\n } else {\n let mDay = yDay - leapMonth;\n if (mDay < (31 * 5)) {\n indianMonth = Math.floor(mDay / 31) + 2;\n indianDay = (mDay % 31) + 1;\n } else {\n mDay -= 31 * 5;\n indianMonth = Math.floor(mDay / 30) + 7;\n indianDay = (mDay % 30) + 1;\n }\n }\n\n return new CalendarDate(this, indianYear, indianMonth, indianDay);\n }\n\n toJulianDay(date: AnyCalendarDate) {\n let extendedYear = date.year + INDIAN_ERA_START;\n let [era, year] = fromExtendedYear(extendedYear);\n\n let leapMonth: number;\n let jd: number;\n if (isLeapYear(year)) {\n leapMonth = 31;\n jd = gregorianToJulianDay(era, year, 3, 21);\n } else {\n leapMonth = 30;\n jd = gregorianToJulianDay(era, year, 3, 22);\n }\n\n if (date.month === 1) {\n return jd + date.day - 1;\n }\n\n jd += leapMonth + Math.min(date.month - 2, 5) * 31;\n\n if (date.month >= 8) {\n jd += (date.month - 7) * 30;\n }\n\n jd += date.day - 1;\n return jd;\n }\n\n getDaysInMonth(date: AnyCalendarDate): number {\n if (date.month === 1 && isLeapYear(date.year + INDIAN_ERA_START)) {\n return 31;\n }\n\n if (date.month >= 2 && date.month <= 6) {\n return 31;\n }\n\n return 30;\n }\n\n getYearsInEra(): number {\n // 9999-12-31 gregorian is 9920-10-10 indian.\n // Round down to 9919 for the last full year.\n return 9919;\n }\n\n getEras() {\n return ['saka'];\n }\n\n balanceDate() {}\n}\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Portions of the code in this file are based on code from ICU.\n// Original licensing can be found in the NOTICE file in the root directory of this source tree.\n\nimport {AnyCalendarDate, Calendar} from '../types';\nimport {CalendarDate} from '../CalendarDate';\n\nconst CIVIL_EPOC = 1948440; // CE 622 July 16 Friday (Julian calendar) / CE 622 July 19 (Gregorian calendar)\nconst ASTRONOMICAL_EPOC = 1948439; // CE 622 July 15 Thursday (Julian calendar)\nconst UMALQURA_YEAR_START = 1300;\nconst UMALQURA_YEAR_END = 1600;\nconst UMALQURA_START_DAYS = 460322;\n\nfunction islamicToJulianDay(epoch: number, year: number, month: number, day: number): number {\n return day +\n Math.ceil(29.5 * (month - 1)) +\n (year - 1) * 354 +\n Math.floor((3 + 11 * year) / 30) +\n epoch - 1;\n}\n\nfunction julianDayToIslamic(calendar: Calendar, epoch: number, jd: number) {\n let year = Math.floor((30 * (jd - epoch) + 10646) / 10631);\n let month = Math.min(12, Math.ceil((jd - (29 + islamicToJulianDay(epoch, year, 1, 1))) / 29.5) + 1);\n let day = jd - islamicToJulianDay(epoch, year, month, 1) + 1;\n\n return new CalendarDate(calendar, year, month, day);\n}\n\nfunction isLeapYear(year: number): boolean {\n return (14 + 11 * year) % 30 < 11;\n}\n\n/**\n * The Islamic calendar, also known as the \"Hijri\" calendar, is used throughout much of the Arab world.\n * The civil variant uses simple arithmetic rules rather than astronomical calculations to approximate\n * the traditional calendar, which is based on sighting of the crescent moon. It uses Friday, July 16 622 CE (Julian) as the epoch.\n * Each year has 12 months, with either 354 or 355 days depending on whether it is a leap year.\n * Learn more about the available Islamic calendars [here](https://cldr.unicode.org/development/development-process/design-proposals/islamic-calendar-types).\n */\nexport class IslamicCivilCalendar implements Calendar {\n identifier = 'islamic-civil';\n\n fromJulianDay(jd: number): CalendarDate {\n return julianDayToIslamic(this, CIVIL_EPOC, jd);\n }\n\n toJulianDay(date: AnyCalendarDate) {\n return islamicToJulianDay(CIVIL_EPOC, date.year, date.month, date.day);\n }\n\n getDaysInMonth(date: AnyCalendarDate): number {\n let length = 29 + date.month % 2;\n if (date.month === 12 && isLeapYear(date.year)) {\n length++;\n }\n\n return length;\n }\n\n getMonthsInYear(): number {\n return 12;\n }\n\n getDaysInYear(date: AnyCalendarDate): number {\n return isLeapYear(date.year) ? 355 : 354;\n }\n\n getYearsInEra(): number {\n // 9999 gregorian\n return 9665;\n }\n\n getEras() {\n return ['AH'];\n }\n}\n\n/**\n * The Islamic calendar, also known as the \"Hijri\" calendar, is used throughout much of the Arab world.\n * The tabular variant uses simple arithmetic rules rather than astronomical calculations to approximate\n * the traditional calendar, which is based on sighting of the crescent moon. It uses Thursday, July 15 622 CE (Julian) as the epoch.\n * Each year has 12 months, with either 354 or 355 days depending on whether it is a leap year.\n * Learn more about the available Islamic calendars [here](https://cldr.unicode.org/development/development-process/design-proposals/islamic-calendar-types).\n */\nexport class IslamicTabularCalendar extends IslamicCivilCalendar {\n identifier = 'islamic-tbla';\n\n fromJulianDay(jd: number): CalendarDate {\n return julianDayToIslamic(this, ASTRONOMICAL_EPOC, jd);\n }\n\n toJulianDay(date: AnyCalendarDate) {\n return islamicToJulianDay(ASTRONOMICAL_EPOC, date.year, date.month, date.day);\n }\n}\n\n// Generated by scripts/generate-umalqura.js\nconst UMALQURA_DATA = 'qgpUDckO1AbqBmwDrQpVBakGkgepC9QF2gpcBS0NlQZKB1QLagutBa4ETwoXBYsGpQbVCtYCWwmdBE0KJg2VDawFtgm6AlsKKwWVCsoG6Qr0AnYJtgJWCcoKpAvSC9kF3AJtCU0FpQpSC6ULtAW2CVcFlwJLBaMGUgdlC2oFqworBZUMSg2lDcoF1gpXCasESwmlClILagt1BXYCtwhbBFUFqQW0BdoJ3QRuAjYJqgpUDbIN1QXaAlsJqwRVCkkLZAtxC7QFtQpVCiUNkg7JDtQG6QprCasEkwpJDaQNsg25CroEWworBZUKKgtVC1wFvQQ9Ah0JlQpKC1oLbQW2AjsJmwRVBqkGVAdqC2wFrQpVBSkLkgupC9QF2gpaBasKlQVJB2QHqgu1BbYCVgpNDiULUgtqC60FrgIvCZcESwalBqwG1gpdBZ0ETQoWDZUNqgW1BdoCWwmtBJUFygbkBuoK9QS2AlYJqgpUC9IL2QXqAm0JrQSVCkoLpQuyBbUJ1gSXCkcFkwZJB1ULagVrCisFiwpGDaMNygXWCtsEawJLCaUKUgtpC3UFdgG3CFsCKwVlBbQF2gntBG0BtgimClINqQ3UBdoKWwmrBFMGKQdiB6kLsgW1ClUFJQuSDckO0gbpCmsFqwRVCikNVA2qDbUJugQ7CpsETQqqCtUK2gJdCV4ELgqaDFUNsga5BroEXQotBZUKUguoC7QLuQXaAloJSgukDdEO6AZqC20FNQWVBkoNqA3UDdoGWwWdAisGFQtKC5ULqgWuCi4JjwwnBZUGqgbWCl0FnQI=';\nlet UMALQURA_MONTHLENGTH: Uint16Array;\nlet UMALQURA_YEAR_START_TABLE: Uint32Array;\n\nfunction umalquraYearStart(year: number): number {\n return UMALQURA_START_DAYS + UMALQURA_YEAR_START_TABLE[year - UMALQURA_YEAR_START];\n}\n\nfunction umalquraMonthLength(year: number, month: number): number {\n let idx = (year - UMALQURA_YEAR_START);\n let mask = (0x01 << (11 - (month - 1)));\n if ((UMALQURA_MONTHLENGTH[idx] & mask) === 0) {\n return 29;\n } else {\n return 30;\n }\n}\n\nfunction umalquraMonthStart(year: number, month: number): number {\n let day = umalquraYearStart(year);\n for (let i = 1; i < month; i++) {\n day += umalquraMonthLength(year, i);\n }\n return day;\n}\n\nfunction umalquraYearLength(year: number): number {\n return UMALQURA_YEAR_START_TABLE[year + 1 - UMALQURA_YEAR_START] - UMALQURA_YEAR_START_TABLE[year - UMALQURA_YEAR_START];\n}\n\n/**\n * The Islamic calendar, also known as the \"Hijri\" calendar, is used throughout much of the Arab world.\n * The Umalqura variant is primarily used in Saudi Arabia. It is a lunar calendar, based on astronomical\n * calculations that predict the sighting of a crescent moon. Month and year lengths vary between years\n * depending on these calculations.\n * Learn more about the available Islamic calendars [here](https://cldr.unicode.org/development/development-process/design-proposals/islamic-calendar-types).\n */\nexport class IslamicUmalquraCalendar extends IslamicCivilCalendar {\n identifier = 'islamic-umalqura';\n\n constructor() {\n super();\n if (!UMALQURA_MONTHLENGTH) {\n UMALQURA_MONTHLENGTH = new Uint16Array(Uint8Array.from(atob(UMALQURA_DATA), c => c.charCodeAt(0)).buffer);\n }\n\n if (!UMALQURA_YEAR_START_TABLE) {\n UMALQURA_YEAR_START_TABLE = new Uint32Array(UMALQURA_YEAR_END - UMALQURA_YEAR_START + 1);\n\n let yearStart = 0;\n for (let year = UMALQURA_YEAR_START; year <= UMALQURA_YEAR_END; year++) {\n UMALQURA_YEAR_START_TABLE[year - UMALQURA_YEAR_START] = yearStart;\n for (let i = 1; i <= 12; i++) {\n yearStart += umalquraMonthLength(year, i);\n }\n }\n }\n }\n\n fromJulianDay(jd: number): CalendarDate {\n let days = jd - CIVIL_EPOC;\n let startDays = umalquraYearStart(UMALQURA_YEAR_START);\n let endDays = umalquraYearStart(UMALQURA_YEAR_END);\n if (days < startDays || days > endDays) {\n return super.fromJulianDay(jd);\n } else {\n let y = UMALQURA_YEAR_START - 1;\n let m = 1;\n let d = 1;\n while (d > 0) {\n y++;\n d = days - umalquraYearStart(y) + 1;\n let yearLength = umalquraYearLength(y);\n if (d === yearLength) {\n m = 12;\n break;\n } else if (d < yearLength) {\n let monthLength = umalquraMonthLength(y, m);\n m = 1;\n while (d > monthLength) {\n d -= monthLength;\n m++;\n monthLength = umalquraMonthLength(y, m);\n }\n break;\n }\n }\n\n return new CalendarDate(this, y, m, (days - umalquraMonthStart(y, m) + 1));\n }\n }\n\n toJulianDay(date: AnyCalendarDate): number {\n if (date.year < UMALQURA_YEAR_START || date.year > UMALQURA_YEAR_END) {\n return super.toJulianDay(date);\n }\n\n return CIVIL_EPOC + umalquraMonthStart(date.year, date.month) + (date.day - 1);\n }\n\n getDaysInMonth(date: AnyCalendarDate): number {\n if (date.year < UMALQURA_YEAR_START || date.year > UMALQURA_YEAR_END) {\n return super.getDaysInMonth(date);\n }\n\n return umalquraMonthLength(date.year, date.month);\n }\n\n getDaysInYear(date: AnyCalendarDate): number {\n if (date.year < UMALQURA_YEAR_START || date.year > UMALQURA_YEAR_END) {\n return super.getDaysInYear(date);\n }\n\n return umalquraYearLength(date.year);\n }\n}\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Portions of the code in this file are based on code from ICU.\n// Original licensing can be found in the NOTICE file in the root directory of this source tree.\n\nimport {AnyCalendarDate, Calendar} from '../types';\nimport {CalendarDate} from '../CalendarDate';\nimport {mod, Mutable} from '../utils';\n\nconst HEBREW_EPOCH = 347997;\n\n// Hebrew date calculations are performed in terms of days, hours, and\n// \"parts\" (or halakim), which are 1/1080 of an hour, or 3 1/3 seconds.\nconst HOUR_PARTS = 1080;\nconst DAY_PARTS = 24 * HOUR_PARTS;\n\n// An approximate value for the length of a lunar month.\n// It is used to calculate the approximate year and month of a given\n// absolute date.\nconst MONTH_DAYS = 29;\nconst MONTH_FRACT = 12 * HOUR_PARTS + 793;\nconst MONTH_PARTS = MONTH_DAYS * DAY_PARTS + MONTH_FRACT;\n\nfunction isLeapYear(year: number) {\n return mod(year * 7 + 1, 19) < 7;\n}\n\n// Test for delay of start of new year and to avoid\n// Sunday, Wednesday, and Friday as start of the new year.\nfunction hebrewDelay1(year: number) {\n let months = Math.floor((235 * year - 234) / 19);\n let parts = 12084 + 13753 * months;\n let day = months * 29 + Math.floor(parts / 25920);\n\n if (mod(3 * (day + 1), 7) < 3) {\n day += 1;\n }\n\n return day;\n}\n\n// Check for delay in start of new year due to length of adjacent years\nfunction hebrewDelay2(year: number) {\n let last = hebrewDelay1(year - 1);\n let present = hebrewDelay1(year);\n let next = hebrewDelay1(year + 1);\n\n if (next - present === 356) {\n return 2;\n }\n\n if (present - last === 382) {\n return 1;\n }\n\n return 0;\n}\n\nfunction startOfYear(year: number) {\n return hebrewDelay1(year) + hebrewDelay2(year);\n}\n\nfunction getDaysInYear(year: number) {\n return startOfYear(year + 1) - startOfYear(year);\n}\n\nfunction getYearType(year: number) {\n let yearLength = getDaysInYear(year);\n\n if (yearLength > 380) {\n yearLength -= 30; // Subtract length of leap month.\n }\n\n switch (yearLength) {\n case 353:\n return 0; // deficient\n case 354:\n return 1; // normal\n case 355:\n return 2; // complete\n }\n}\n\nfunction getDaysInMonth(year: number, month: number): number {\n // Normalize month numbers from 1 - 13, even on non-leap years\n if (month >= 6 && !isLeapYear(year)) {\n month++;\n }\n\n // First of all, dispose of fixed-length 29 day months\n if (month === 4 || month === 7 || month === 9 || month === 11 || month === 13) {\n return 29;\n }\n\n let yearType = getYearType(year);\n\n // If it's Heshvan, days depend on length of year\n if (month === 2) {\n return yearType === 2 ? 30 : 29;\n }\n\n // Similarly, Kislev varies with the length of year\n if (month === 3) {\n return yearType === 0 ? 29 : 30;\n }\n\n // Adar I only exists in leap years\n if (month === 6) {\n return isLeapYear(year) ? 30 : 0;\n }\n\n return 30;\n}\n\n/**\n * The Hebrew calendar is used in Israel and around the world by the Jewish faith.\n * Years include either 12 or 13 months depending on whether it is a leap year.\n * In leap years, an extra month is inserted at month 6.\n */\nexport class HebrewCalendar implements Calendar {\n identifier = 'hebrew';\n\n fromJulianDay(jd: number): CalendarDate {\n let d = jd - HEBREW_EPOCH;\n let m = (d * DAY_PARTS) / MONTH_PARTS; // Months (approx)\n let year = Math.floor((19 * m + 234) / 235) + 1; // Years (approx)\n let ys = startOfYear(year); // 1st day of year\n let dayOfYear = Math.floor(d - ys);\n\n // Because of the postponement rules, it's possible to guess wrong. Fix it.\n while (dayOfYear < 1) {\n year--;\n ys = startOfYear(year);\n dayOfYear = Math.floor(d - ys);\n }\n\n // Now figure out which month we're in, and the date within that month\n let month = 1;\n let monthStart = 0;\n while (monthStart < dayOfYear) {\n monthStart += getDaysInMonth(year, month);\n month++;\n }\n\n month--;\n monthStart -= getDaysInMonth(year, month);\n\n let day = dayOfYear - monthStart;\n return new CalendarDate(this, year, month, day);\n }\n\n toJulianDay(date: AnyCalendarDate) {\n let jd = startOfYear(date.year);\n for (let month = 1; month < date.month; month++) {\n jd += getDaysInMonth(date.year, month);\n }\n\n return jd + date.day + HEBREW_EPOCH;\n }\n\n getDaysInMonth(date: AnyCalendarDate): number {\n return getDaysInMonth(date.year, date.month);\n }\n\n getMonthsInYear(date: AnyCalendarDate): number {\n return isLeapYear(date.year) ? 13 : 12;\n }\n\n getDaysInYear(date: AnyCalendarDate): number {\n return getDaysInYear(date.year);\n }\n\n getYearsInEra(): number {\n // 6239 gregorian\n return 9999;\n }\n\n getEras() {\n return ['AM'];\n }\n\n balanceYearMonth(date: Mutable<AnyCalendarDate>, previousDate: AnyCalendarDate) {\n // Keep date in the same month when switching between leap years and non leap years\n if (previousDate.year !== date.year) {\n if (isLeapYear(previousDate.year) && !isLeapYear(date.year) && previousDate.month > 6) {\n date.month--;\n } else if (!isLeapYear(previousDate.year) && isLeapYear(date.year) && previousDate.month > 6) {\n date.month++;\n }\n }\n }\n}\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Portions of the code in this file are based on code from ICU.\n// Original licensing can be found in the NOTICE file in the root directory of this source tree.\n\nimport {AnyCalendarDate, Calendar} from '../types';\nimport {CalendarDate} from '../CalendarDate';\nimport {Mutable} from '../utils';\n\nconst ETHIOPIC_EPOCH = 1723856;\nconst COPTIC_EPOCH = 1824665;\n\n// The delta between Amete Alem 1 and Amete Mihret 1\n// AA 5501 = AM 1\nconst AMETE_MIHRET_DELTA = 5500;\n\nfunction ceToJulianDay(epoch: number, year: number, month: number, day: number): number {\n return (\n epoch // difference from Julian epoch to 1,1,1\n + 365 * year // number of days from years\n + Math.floor(year / 4) // extra day of leap year\n + 30 * (month - 1) // number of days from months (1 based)\n + day - 1 // number of days for present month (1 based)\n );\n}\n\nfunction julianDayToCE(epoch: number, jd: number) {\n let year = Math.floor((4 * (jd - epoch)) / 1461);\n let month = 1 + Math.floor((jd - ceToJulianDay(epoch, year, 1, 1)) / 30);\n let day = jd + 1 - ceToJulianDay(epoch, year, month, 1);\n return [year, month, day];\n}\n\nfunction getLeapDay(year: number) {\n return Math.floor((year % 4) / 3);\n}\n\nfunction getDaysInMonth(year: number, month: number) {\n // The Ethiopian and Coptic calendars have 13 months, 12 of 30 days each and\n // an intercalary month at the end of the year of 5 or 6 days, depending whether\n // the year is a leap year or not. The Leap Year follows the same rules as the\n // Julian Calendar so that the extra month always has six days in the year before\n // a Julian Leap Year.\n if (month % 13 !== 0) {\n // not intercalary month\n return 30;\n } else {\n // intercalary month 5 days + possible leap day\n return getLeapDay(year) + 5;\n }\n}\n\n/**\n * The Ethiopic calendar system is the official calendar used in Ethiopia.\n * It includes 12 months of 30 days each, plus 5 or 6 intercalary days depending\n * on whether it is a leap year. Two eras are supported: 'AA' and 'AM'.\n */\nexport class EthiopicCalendar implements Calendar {\n identifier = 'ethiopic';\n\n fromJulianDay(jd: number): CalendarDate {\n let [year, month, day] = julianDayToCE(ETHIOPIC_EPOCH, jd);\n let era = 'AM';\n if (year <= 0) {\n era = 'AA';\n year += AMETE_MIHRET_DELTA;\n }\n\n return new CalendarDate(this, era, year, month, day);\n }\n\n toJulianDay(date: AnyCalendarDate) {\n let year = date.year;\n if (date.era === 'AA') {\n year -= AMETE_MIHRET_DELTA;\n }\n\n return ceToJulianDay(ETHIOPIC_EPOCH, year, date.month, date.day);\n }\n\n getDaysInMonth(date: AnyCalendarDate): number {\n return getDaysInMonth(date.year, date.month);\n }\n\n getMonthsInYear(): number {\n return 13;\n }\n\n getDaysInYear(date: AnyCalendarDate): number {\n return 365 + getLeapDay(date.year);\n }\n\n getYearsInEra(date: AnyCalendarDate): number {\n // 9999-12-31 gregorian is 9992-20-02 ethiopic.\n // Round down to 9991 for the last full year.\n // AA 9999-01-01 ethiopic is 4506-09-30 gregorian.\n return date.era === 'AA' ? 9999 : 9991;\n }\n\n getEras() {\n return ['AA', 'AM'];\n }\n}\n\n/**\n * The Ethiopic (Amete Alem) calendar is the same as the modern Ethiopic calendar,\n * except years were measured from a different epoch. Only one era is supported: 'AA'.\n */\nexport class EthiopicAmeteAlemCalendar extends EthiopicCalendar {\n identifier = 'ethioaa'; // also known as 'ethiopic-amete-alem' in ICU\n\n fromJulianDay(jd: number): CalendarDate {\n let [year, month, day] = julianDayToCE(ETHIOPIC_EPOCH, jd);\n year += AMETE_MIHRET_DELTA;\n return new CalendarDate(this, 'AA', year, month, day);\n }\n\n getEras() {\n return ['AA'];\n }\n\n getYearsInEra(): number {\n // 9999-13-04 ethioaa is the maximum date, which is equivalent to 4506-09-29 gregorian.\n return 9999;\n }\n}\n\n/**\n * The Coptic calendar is similar to the Ethiopic calendar.\n * It includes 12 months of 30 days each, plus 5 or 6 intercalary days depending\n * on whether it is a leap year. Two eras are supported: 'BCE' and 'CE'.\n */\nexport class CopticCalendar extends EthiopicCalendar {\n identifier = 'coptic';\n\n fromJulianDay(jd: number): CalendarDate {\n let [year, month, day] = julianDayToCE(COPTIC_EPOCH, jd);\n let era = 'CE';\n if (year <= 0) {\n era = 'BCE';\n year = 1 - year;\n }\n\n return new CalendarDate(this, era, year, month, day);\n }\n\n toJulianDay(date: AnyCalendarDate) {\n let year = date.year;\n if (date.era === 'BCE') {\n year = 1 - year;\n }\n\n return ceToJulianDay(COPTIC_EPOCH, year, date.month, date.day);\n }\n\n getDaysInMonth(date: AnyCalendarDate): number {\n let year = date.year;\n if (date.era === 'BCE') {\n year = 1 - year;\n }\n\n return getDaysInMonth(year, date.month);\n }\n\n isInverseEra(date: AnyCalendarDate): boolean {\n return date.era === 'BCE';\n }\n\n balanceDate(date: Mutable<AnyCalendarDate>) {\n if (date.year <= 0) {\n date.era = date.era === 'BCE' ? 'CE' : 'BCE';\n date.year = 1 - date.year;\n }\n }\n\n getEras() {\n return ['BCE', 'CE'];\n }\n\n getYearsInEra(date: AnyCalendarDate): number {\n // 9999-12-30 gregorian is 9716-02-20 coptic.\n // Round down to 9715 for the last full year.\n // BCE 9999-01-01 coptic is BC 9716-06-15 gregorian.\n return date.era === 'BCE' ? 9999 : 9715;\n }\n}\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {BuddhistCalendar} from './calendars/BuddhistCalendar';\nimport {Calendar} from './types';\nimport {CopticCalendar, EthiopicAmeteAlemCalendar, EthiopicCalendar} from './calendars/EthiopicCalendar';\nimport {GregorianCalendar} from './calendars/GregorianCalendar';\nimport {HebrewCalendar} from './calendars/HebrewCalendar';\nimport {IndianCalendar} from './calendars/IndianCalendar';\nimport {IslamicCivilCalendar, IslamicTabularCalendar, IslamicUmalquraCalendar} from './calendars/IslamicCalendar';\nimport {JapaneseCalendar} from './calendars/JapaneseCalendar';\nimport {PersianCalendar} from './calendars/PersianCalendar';\nimport {TaiwanCalendar} from './calendars/TaiwanCalendar';\n\n/** Creates a `Calendar` instance from a Unicode calendar identifier string. */\nexport function createCalendar(name: string): Calendar {\n switch (name) {\n case 'buddhist':\n return new BuddhistCalendar();\n case 'ethiopic':\n return new EthiopicCalendar();\n case 'ethioaa':\n return new EthiopicAmeteAlemCalendar();\n case 'coptic':\n return new CopticCalendar();\n case 'hebrew':\n return new HebrewCalendar();\n case 'indian':\n return new IndianCalendar();\n case 'islamic-civil':\n return new IslamicCivilCalendar();\n case 'islamic-tbla':\n return new IslamicTabularCalendar();\n case 'islamic-umalqura':\n return new IslamicUmalquraCalendar();\n case 'japanese':\n return new JapaneseCalendar();\n case 'persian':\n return new PersianCalendar();\n case 'roc':\n return new TaiwanCalendar();\n case 'gregory':\n default:\n return new GregorianCalendar();\n }\n}\n", "/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nlet formatterCache = new Map<string, Intl.DateTimeFormat>();\n\ninterface ResolvedDateTimeFormatOptions extends Intl.ResolvedDateTimeFormatOptions {\n hourCycle?: Intl.DateTimeFormatOptions['hourCycle']\n}\n\ninterface DateRangeFormatPart extends Intl.DateTimeFormatPart {\n source: 'startRange' | 'endRange' | 'shared'\n}\n\n/** A wrapper around Intl.DateTimeFormat that fixes various browser bugs, and polyfills new features. */\nexport class DateFormatter implements Intl.DateTimeFormat {\n private formatter: Intl.DateTimeFormat;\n private options: Intl.DateTimeFormatOptions;\n private resolvedHourCycle: Intl.DateTimeFormatOptions['hourCycle'];\n\n constructor(locale: string, options: Intl.DateTimeFormatOptions = {}) {\n this.formatter = getCachedDateFormatter(locale, options);\n this.options = options;\n }\n\n /** Formats a date as a string according to the locale and format options passed to the constructor. */\n format(value: Date): string {\n return this.formatter.format(value);\n }\n\n /** Formats a date to an array of parts such as separators, numbers, punctuation, and more. */\n formatToParts(value: Date): Intl.DateTimeFormatPart[] {\n return this.formatter.formatToParts(value);\n }\n\n /** Formats a date range as a string. */\n formatRange(start: Date, end: Date): string {\n // @ts-ignore\n if (typeof this.formatter.formatRange === 'function') {\n // @ts-ignore\n return this.formatter.formatRange(start, end);\n }\n\n if (end < start) {\n throw new RangeError('End date must be >= start date');\n }\n\n // Very basic fallback for old browsers.\n return `${this.formatter.format(start)} – ${this.formatter.format(end)}`;\n }\n\n /** Formats a date range as an array of parts. */\n formatRangeToParts(start: Date, end: Date): DateRangeFormatPart[] {\n // @ts-ignore\n if (typeof this.formatter.formatRangeToParts === 'function') {\n // @ts-ignore\n return this.formatter.formatRangeToParts(start, end);\n }\n\n if (end < start) {\n throw new RangeError('End date must be >= start date');\n }\n\n let startParts = this.formatter.formatToParts(start);\n let endParts = this.formatter.formatToParts(end);\n return [\n ...startParts.map(p => ({...p, source: 'startRange'} as DateRangeFormatPart)),\n {type: 'literal', value: ' – ', source: 'shared'},\n ...endParts.map(p => ({...p, source: 'endRange'} as DateRangeFormatPart))\n ];\n }\n\n /** Returns the resolved formatting options based on the values passed to the constructor. */\n resolvedOptions(): ResolvedDateTimeFormatOptions {\n let resolvedOptions = this.formatter.resolvedOptions() as ResolvedDateTimeFormatOptions;\n if (hasBuggyResolvedHourCycle()) {\n if (!this.resolvedHourCycle) {\n this.resolvedHourCycle = getResolvedHourCycle(resolvedOptions.locale, this.options);\n }\n resolvedOptions.hourCycle = this.resolvedHourCycle;\n resolvedOptions.hour12 = this.resolvedHourCycle === 'h11' || this.resolvedHourCycle === 'h12';\n }\n\n // Safari uses a different name for the Ethiopic (Amete Alem) calendar.\n // https://bugs.webkit.org/show_bug.cgi?id=241564\n if (resolvedOptions.calendar === 'ethiopic-amete-alem') {\n resolvedOptions.calendar = 'ethioaa';\n }\n\n return resolvedOptions;\n }\n}\n\n// There are multiple bugs involving the hour12 and hourCycle options in various browser engines.\n// - Chrome [1] (and the ECMA 402 spec [2]) resolve hour12: false in English and other locales to h24 (24:00 - 23:59)\n// rather than h23 (00:00 - 23:59). Same can happen with hour12: true in French, which Chrome resolves to h11 (00:00 - 11:59)\n// rather than h12 (12:00 - 11:59).\n// - WebKit returns an incorrect hourCycle resolved option in the French locale due to incorrect parsing of 'h' literal\n// in the resolved pattern. It also formats incorrectly when specifying the hourCycle option for the same reason. [3]\n// [1] https://bugs.chromium.org/p/chromium/issues/detail?id=1045791\n// [2] https://github.com/tc39/ecma402/issues/402\n// [3] https://bugs.webkit.org/show_bug.cgi?id=229313\n\n// https://github.com/unicode-org/cldr/blob/018b55eff7ceb389c7e3fc44e2f657eae3b10b38/common/supplemental/supplementalData.xml#L4774-L4802\nconst hour12Preferences = {\n true: {\n // Only Japanese uses the h11 style for 12 hour time. All others use h12.\n ja: 'h11'\n },\n false: {\n // All locales use h23 for 24 hour time. None use h24.\n }\n};\n\nfunction getCachedDateFormatter(locale: string, options: Intl.DateTimeFormatOptions = {}): Intl.DateTimeFormat {\n // Work around buggy hour12 behavior in Chrome / ECMA 402 spec by using hourCycle instead.\n // Only apply the workaround if the issue is detected, because the hourCycle option is buggy in Safari.\n if (typeof options.hour12 === 'boolean' && hasBuggyHour12Behavior()) {\n options = {...options};\n let pref = hour12Preferences[String(options.hour12)][locale.split('-')[0]];\n let defaultHourCycle = options.hour12 ? 'h12' : 'h23';\n options.hourCycle = pref ?? defaultHourCycle;\n delete options.hour12;\n }\n\n let cacheKey = locale + (options ? Object.entries(options).sort((a, b) => a[0] < b[0] ? -1 : 1).join() : '');\n if (formatterCache.has(cacheKey)) {\n return formatterCache.get(cacheKey);\n }\n\n let numberFormatter = new Intl.DateTimeFormat(locale, options);\n formatterCache.set(cacheKey, numberFormatter);\n return numberFormatter;\n}\n\nlet _hasBuggyHour12Behavior: boolean = null;\nfunction hasBuggyHour12Behavior() {\n if (_hasBuggyHour12Behavior == null) {\n _hasBuggyHour12Behavior = new Intl.DateTimeFormat('en-US', {\n hour: 'numeric',\n hour12: false\n }).format(new Date(2020, 2, 3, 0)) === '24';\n }\n\n return _hasBuggyHour12Behavior;\n}\n\nlet _hasBuggyResolvedHourCycle: boolean = null;\nfunction hasBuggyResolvedHourCycle() {\n if (_hasBuggyResolvedHourCycle == null) {\n _hasBuggyResolvedHourCycle = (new Intl.DateTimeFormat('fr', {\n hour: 'numeric',\n hour12: false\n }).resolvedOptions() as ResolvedDateTimeFormatOptions).hourCycle === 'h12';\n }\n\n return _hasBuggyResolvedHourCycle;\n}\n\nfunction getResolvedHourCycle(locale: string, options: Intl.DateTimeFormatOptions) {\n if (!options.timeStyle && !options.hour) {\n return undefined;\n }\n\n // Work around buggy results in resolved hourCycle and hour12 options in WebKit.\n // Format the minimum possible hour and maximum possible hour in a day and parse the results.\n locale = locale.replace(/(-u-)?-nu-[a-zA-Z0-9]+/, '');\n locale += (locale.includes('-u-') ? '' : '-u') + '-nu-latn';\n let formatter = getCachedDateFormatter(locale, {\n ...options,\n timeZone: undefined // use local timezone\n });\n\n let min = parseInt(formatter.formatToParts(new Date(2020, 2, 3, 0)).find(p => p.type === 'hour').value, 10);\n let max = parseInt(formatter.formatToParts(new Date(2020, 2, 3, 23)).find(p => p.type === 'hour').value, 10);\n\n if (min === 0 && max === 23) {\n return 'h23';\n }\n\n if (min === 24 && max === 23) {\n return 'h24';\n }\n\n if (min === 0 && max === 11) {\n return 'h11';\n }\n\n if (min === 12 && max === 11) {\n return 'h12';\n }\n\n throw new Error('Unexpected hour cycle result');\n}\n", "import {\n ColumnDescriptorsByName,\n FilterClause,\n FilterClauseOp,\n} from \"@vuu-ui/vuu-filter-types\";\nimport { ColumnDescriptor } from \"@vuu-ui/vuu-table-types\";\nimport {\n isMultiValueFilter,\n isSingleValueFilter,\n isValidFilterClauseOp,\n} from \"@vuu-ui/vuu-utils\";\n\nimport { SingleSelectionHandler } from \"@vuu-ui/vuu-ui-controls\";\nimport {\n KeyboardEvent,\n KeyboardEventHandler,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\n\nconst cursorAtTextStart = (input: HTMLInputElement) =>\n input.selectionStart === 0;\n\nconst cursorAtTextEnd = (input: HTMLInputElement) =>\n input.selectionStart === input.value.length;\n\nconst getFieldName = (field: HTMLElement) =>\n field?.classList.contains(\"vuuFilterClauseColumn\")\n ? \"column\"\n : field?.classList.contains(\"vuuFilterClauseOperator\")\n ? \"operator\"\n : \"value\";\n\nconst getFocusedField = () => {\n const activeElement = document.activeElement;\n if (activeElement?.classList.contains(\"vuuFilterClause-clearButton\")) {\n return activeElement;\n } else {\n return activeElement?.closest(\".vuuFilterClauseField\") as HTMLElement;\n }\n};\n\nconst focusNextFocusableElement = (direction: \"fwd\" | \"bwd\" = \"fwd\") => {\n const activeField = getFocusedField();\n const filterClause = activeField?.closest(\".vuuFilterClause\");\n if (direction === \"fwd\" && filterClause?.lastChild === activeField) {\n requestAnimationFrame(() => {\n focusNextFocusableElement();\n });\n } else {\n const nextField =\n direction === \"fwd\"\n ? (activeField?.nextElementSibling as HTMLElement)\n : (activeField?.previousElementSibling as HTMLElement);\n\n nextField?.querySelector(\"input\")?.focus();\n }\n};\n\nconst clauseIsNotFirst = (el: HTMLElement) => {\n const clause = el.closest(\"[data-index]\") as HTMLElement;\n if (clause) {\n const index = clause.dataset.index;\n const previousClause = clause?.parentElement?.querySelector(\n `[data-index]:has(.vuuFilterClause):has(+[data-index=\"${index}\"])`\n );\n return previousClause !== null;\n }\n};\n\nconst focusNextElement = () => {\n const filterClauseField = getFocusedField();\n const filterClause = filterClauseField?.closest(\".vuuFilterClause\");\n if (filterClause && filterClauseField) {\n if (filterClauseField.classList.contains(\"vuuFilterClauseValue\")) {\n const clearButton = filterClause.querySelector(\n \".vuuFilterClause-clearButton\"\n ) as HTMLButtonElement;\n clearButton?.focus();\n } else {\n focusNextFocusableElement();\n }\n }\n};\n\n// The logic around preventDefault/stopPragagation is important\n// in this function\nconst navigateToNextInputIfAtBoundary = (\n evt: KeyboardEvent<HTMLInputElement>\n) => {\n const input = evt.target as HTMLInputElement;\n const cursorAtStart = cursorAtTextStart(input);\n const cursorAtEnd = cursorAtTextEnd(input);\n const field = input.closest(\".vuuFilterClauseField\") as HTMLElement;\n if (evt.key === \"ArrowLeft\") {\n if (cursorAtStart) {\n const fieldName = getFieldName(field);\n if (fieldName === \"column\") {\n // Do not preventDefault, stopPropagation\n return;\n } else {\n const nextField = field.previousSibling as HTMLElement;\n const nextInput = nextField?.querySelector(\"input\");\n evt.preventDefault();\n\n nextInput?.focus();\n requestAnimationFrame(() => {\n nextInput?.select();\n });\n }\n }\n // stopPropagation, even if cursor is not at start. We want the arrowLeft to move the cursor\n evt.stopPropagation();\n } else if (evt.key === \"ArrowRight\") {\n if (cursorAtEnd) {\n const fieldName = getFieldName(field);\n if (fieldName === \"value\") {\n // Do not preventDefault, stopPropagation\n return;\n } else {\n const nextField = field.nextSibling as HTMLElement;\n const nextInput = nextField?.querySelector(\"input\");\n evt.preventDefault();\n nextInput?.focus();\n requestAnimationFrame(() => {\n nextInput?.select();\n });\n }\n }\n // stopPropagation, even if cursor is not at end. We want the arrowRight to move the cursor\n evt.stopPropagation();\n }\n};\n\n// TODO boolean[] makes no sense\ntype FilterClauseValue =\n | boolean\n | boolean[]\n | string\n | string[]\n | number\n | number[];\n\nconst getFilterClauseValue = (\n filterClause: Partial<FilterClause>\n): FilterClauseValue | undefined => {\n if (isMultiValueFilter(filterClause)) {\n return filterClause.values;\n } else if (isSingleValueFilter(filterClause)) {\n return filterClause.value;\n } else {\n return undefined;\n }\n};\n\nexport type FilterClauseCancelType = \"Backspace\";\nexport type FilterClauseCancelHandler = (\n reason: FilterClauseCancelType\n) => void;\nexport interface FilterClauseEditorHookProps {\n columnsByName: ColumnDescriptorsByName;\n filterClause: Partial<FilterClause>;\n onCancel?: FilterClauseCancelHandler;\n onChange: (filterClause: Partial<FilterClause>) => void;\n}\n\nexport const useFilterClauseEditor = ({\n filterClause,\n onCancel,\n onChange,\n columnsByName,\n}: FilterClauseEditorHookProps) => {\n const columnRef = useRef<HTMLDivElement>(null);\n const operatorRef = useRef<HTMLDivElement>(null);\n\n const [selectedColumn, setSelectedColumn] = useState<\n ColumnDescriptor | undefined\n >(filterClause.column ? columnsByName[filterClause.column] : undefined);\n const [operator, _setOperator] = useState<FilterClauseOp | undefined>(\n filterClause.op\n );\n\n const setOperator = useCallback((op) => {\n _setOperator(op);\n }, []);\n\n const [value, setValue] = useState<FilterClauseValue | undefined>(\n getFilterClauseValue(filterClause)\n );\n\n const handleColumnSelect = useCallback<\n SingleSelectionHandler<ColumnDescriptor>\n >(\n (_, column) => {\n setSelectedColumn(column ?? undefined);\n setOperator(undefined);\n setValue(undefined);\n setTimeout(() => {\n focusNextElement();\n }, 100);\n },\n [setOperator]\n );\n\n const removeAndNavigateToNextInputIfAtBoundary = useCallback(\n (evt) => {\n const input = evt.target as HTMLInputElement;\n if (input.value === \"\") {\n const field = input.closest(\n \".vuuFilterClauseField,[data-field]\"\n ) as HTMLElement;\n switch (field?.dataset?.field) {\n case \"operator\": {\n setOperator(undefined);\n setSelectedColumn(undefined);\n focusNextFocusableElement(\"bwd\");\n break;\n }\n case \"value\": {\n setOperator(undefined);\n focusNextFocusableElement(\"bwd\");\n break;\n }\n case \"column\": {\n if (clauseIsNotFirst(input)) {\n console.log(\"This is NOT the first clause\");\n onCancel?.(\"Backspace\");\n }\n }\n }\n }\n },\n [onCancel, setOperator]\n );\n\n const handleOperatorSelect = useCallback<SingleSelectionHandler>(\n (_, selected) => {\n const op = selected;\n if (op === undefined || isValidFilterClauseOp(op)) {\n setOperator(op);\n focusNextElement();\n } else {\n throw Error(\n `FilterClauseEditor, invalid value ${op} for filter clause`\n );\n }\n },\n [setOperator]\n );\n\n const handleChangeValue = useCallback(\n (value: string | string[] | number | number[]) => {\n setValue(value);\n if (value !== null && value !== \"\") {\n if (Array.isArray(value)) {\n onChange({\n column: selectedColumn?.name,\n op: operator,\n values: value,\n });\n } else {\n onChange({\n column: selectedColumn?.name,\n op: operator,\n value,\n });\n }\n }\n },\n [onChange, operator, selectedColumn?.name]\n );\n\n const handleDeselectValue = useCallback(() => {\n setValue(undefined);\n }, []);\n\n const handleKeyDownCaptureInput = useCallback(\n (evt: KeyboardEvent<HTMLInputElement>) => {\n if ([\"ArrowLeft\", \"ArrowRight\"].includes(evt.key)) {\n navigateToNextInputIfAtBoundary(evt);\n } else if (evt.key === \"Backspace\") {\n removeAndNavigateToNextInputIfAtBoundary(evt);\n }\n },\n [removeAndNavigateToNextInputIfAtBoundary]\n );\n\n const handleClear = useCallback(\n (e) => {\n const button = e.target as HTMLButtonElement;\n const firstInput = button\n .closest(\".vuuFilterClause\")\n ?.querySelector(\"input\") as HTMLInputElement;\n\n setSelectedColumn(undefined);\n setOperator(undefined);\n setValue(undefined);\n\n setTimeout(() => {\n firstInput.select();\n firstInput?.focus();\n }, 100);\n },\n [setOperator]\n );\n\n const handleClearKeyDown = useCallback<KeyboardEventHandler>((e) => {\n e.stopPropagation();\n if (e.key === \"Backspace\") {\n focusNextFocusableElement(\"bwd\");\n }\n }, []);\n\n const InputProps = useMemo(\n () => ({\n inputProps: {\n onKeyDownCapture: handleKeyDownCaptureInput,\n },\n }),\n [handleKeyDownCaptureInput]\n );\n\n useEffect(() => {\n const columnInput = columnRef.current?.querySelector(\"input\");\n columnInput?.focus();\n }, []);\n\n return {\n InputProps,\n columnRef,\n onChangeValue: handleChangeValue,\n onClear: handleClear,\n onClearKeyDown: handleClearKeyDown,\n onDeselectValue: handleDeselectValue,\n onColumnSelect: handleColumnSelect,\n onOperatorSelect: handleOperatorSelect,\n operator,\n operatorRef,\n selectedColumn,\n value,\n };\n};\n", "import { MenuActionHandler } from \"@vuu-ui/vuu-data-types\";\nimport { ColumnDescriptorsByName, Filter } from \"@vuu-ui/vuu-filter-types\";\nimport { PopupCloseCallback, Tooltip, useTooltip } from \"@vuu-ui/vuu-popups\";\nimport { EditableLabel, EditableLabelProps } from \"@vuu-ui/vuu-ui-controls\";\nimport { useId } from \"@vuu-ui/vuu-utils\";\nimport cx from \"clsx\";\nimport { HTMLAttributes, useCallback, useMemo, useRef } from \"react\";\nimport { FilterPillMenu } from \"../filter-pill-menu\";\nimport { filterAsReactNode } from \"./filterAsReactNode\";\n\nimport \"./FilterPill.css\";\nimport { getFilterLabel } from \"./getFilterLabel\";\n\nconst classBase = \"vuuFilterPill\";\n\nexport interface FilterPillProps\n extends Pick<Partial<EditableLabelProps>, \"onExitEditMode\">,\n HTMLAttributes<HTMLDivElement> {\n columnsByName?: ColumnDescriptorsByName;\n editable?: boolean;\n filter: Filter;\n index?: number;\n onBeginEdit?: (filter: Filter) => void;\n onMenuAction?: MenuActionHandler;\n showMenu?: boolean;\n}\n\nexport const FilterPill = ({\n className: classNameProp,\n columnsByName,\n editable = true,\n filter,\n id: idProp,\n onBeginEdit,\n onExitEditMode,\n onMenuAction,\n showMenu = true,\n ...htmlAttributes\n}: FilterPillProps) => {\n const rootRef = useRef<HTMLDivElement>(null);\n const handleEnterEditMode: EditableLabelProps[\"onEnterEditMode\"] =\n useCallback(() => {\n onBeginEdit?.(filter);\n }, [filter, onBeginEdit]);\n\n const getLabel = getFilterLabel(columnsByName);\n const label = useMemo(\n () => filter.name ?? getLabel(filter),\n [getLabel, filter]\n );\n\n const id = useId(idProp);\n\n const handleMenuClose = useCallback<PopupCloseCallback>((reason) => {\n if (reason?.type === \"escape\") {\n requestAnimationFrame(() => {\n if (rootRef.current) {\n rootRef.current.focus();\n }\n });\n }\n }, []);\n\n // Experiment, to be revisited\n // const tooltipBackground = useRef<string | undefined>();\n // useLayoutEffect(() => {\n // if (rootRef.current) {\n // tooltipBackground.current = getComputedStyle(\n // rootRef.current\n // ).getPropertyValue(\"--vuuTooltip-background\");\n // }\n // }, []);\n\n const { anchorProps, tooltipProps } = useTooltip({\n id,\n placement: \"below\",\n tooltipContent: filterAsReactNode(filter, getLabel),\n });\n\n return (\n <div\n {...anchorProps}\n {...htmlAttributes}\n className={cx(classBase, classNameProp)}\n data-text={label}\n ref={rootRef}\n >\n {editable && onExitEditMode ? (\n <EditableLabel\n defaultValue={label}\n key={label}\n onEnterEditMode={handleEnterEditMode}\n onExitEditMode={onExitEditMode}\n />\n ) : (\n <span className={`${classBase}-label`}>{label}</span>\n )}\n {showMenu && onMenuAction ? (\n <FilterPillMenu\n filter={filter}\n onMenuAction={onMenuAction}\n onMenuClose={handleMenuClose}\n />\n ) : null}\n {tooltipProps && <Tooltip {...tooltipProps} />}\n </div>\n );\n};\n", "import { PopupMenu } from \"@vuu-ui/vuu-popups\";\nimport {\n ContextMenuItemDescriptor,\n MenuActionHandler,\n MenuBuilder,\n} from \"@vuu-ui/vuu-data-types\";\nimport { useMemo } from \"react\";\nimport cx from \"clsx\";\n\nimport \"./FilterPillMenu.css\";\nimport {\n closeCommand,\n deleteCommand,\n editCommand,\n MenuOptions,\n renameCommand,\n} from \"./FilterPillMenuOptions\";\nimport { Filter } from \"@vuu-ui/vuu-filter-types\";\n\nconst classBase = \"vuuFilterPillMenu\";\n\nexport interface FilterMenuOptions extends MenuOptions {\n filter: Filter;\n}\n\nexport interface FilterPillMenuProps {\n allowClose?: boolean;\n allowDelete?: boolean;\n allowEdit?: boolean;\n allowRename?: boolean;\n filter: Filter;\n location?: string;\n onMenuAction: MenuActionHandler;\n onMenuClose?: () => void;\n}\n\nexport const FilterPillMenu = ({\n allowClose = true,\n allowDelete = true,\n allowEdit = true,\n allowRename = true,\n filter,\n location,\n onMenuAction,\n onMenuClose,\n}: FilterPillMenuProps) => {\n const [menuBuilder, menuOptions] = useMemo(\n (): [MenuBuilder, FilterMenuOptions] => [\n (_location, options) => {\n const menuItems: ContextMenuItemDescriptor[] = [];\n if (allowRename) {\n menuItems.push(renameCommand(options as MenuOptions));\n }\n if (allowEdit) {\n menuItems.push(editCommand(options as MenuOptions));\n }\n if (allowClose) {\n menuItems.push(closeCommand(options as MenuOptions));\n }\n if (allowDelete) {\n menuItems.push(deleteCommand(options as MenuOptions));\n }\n return menuItems;\n },\n {\n filter,\n },\n ],\n [allowClose, allowDelete, allowEdit, allowRename, filter]\n );\n\n return (\n <PopupMenu\n className={classBase}\n menuBuilder={menuBuilder}\n menuActionHandler={onMenuAction}\n menuLocation={cx(\"filter\", location)}\n menuOptions={menuOptions}\n onMenuClose={onMenuClose}\n tabIndex={-1}\n />\n );\n};\n", "import { ContextMenuItemDescriptor } from \"@vuu-ui/vuu-data-types\";\n\nexport type MenuOptions = { [key: string]: unknown };\n\nexport interface FilterPillMenuOptions {\n tabIndex: number;\n}\n\nexport const isFilterPillMenuOptions = (\n options: unknown\n): options is FilterPillMenuOptions =>\n typeof options === \"object\" && options !== null && \"filter\" in options;\n\nexport const closeCommand = (options?: MenuOptions) =>\n ({\n label: `Close`,\n location: \"filter\",\n action: `close-filter`,\n options,\n } as ContextMenuItemDescriptor);\n\nexport const deleteCommand = (options?: MenuOptions) =>\n ({\n label: `Delete`,\n location: \"filter\",\n action: `delete-filter`,\n options,\n } as ContextMenuItemDescriptor);\n\nexport const renameCommand = (options?: MenuOptions) =>\n ({\n label: `Rename`,\n location: \"filter\",\n action: `rename-filter`,\n options,\n } as ContextMenuItemDescriptor);\n\nexport const editCommand = (options?: MenuOptions) =>\n ({\n label: `Edit`,\n location: \"filter\",\n action: \"edit-filter\",\n options,\n } as ContextMenuItemDescriptor);\n", "import { isMultiClauseFilter, isMultiValueFilter } from \"@vuu-ui/vuu-utils\";\nimport { Filter } from \"@vuu-ui/vuu-filter-types\";\nimport { ReactNode } from \"react\";\nimport { getFilterLabel } from \"./getFilterLabel\";\n\nexport const filterAsReactNode = (\n f: Filter,\n getLabel: (f: Filter) => string = getFilterLabel()\n): ReactNode => {\n if (isMultiClauseFilter(f)) {\n const heading = f.op === \"and\" ? \"Match all ...\" : \"Match any ...\";\n return (\n <ul>\n <span>{heading}</span>\n {f.filters.map((f, i) => (\n <li key={i}>{filterAsReactNode(f, getLabel)}</li>\n ))}\n </ul>\n );\n } else if (isMultiValueFilter(f)) {\n if (f.values.length > 3) {\n const values = f.values.slice(0, 3);\n return `${getLabel({ ...f, values }).slice(0, -1)},...]`;\n } else {\n return getLabel(f);\n }\n } else {\n return getLabel(f);\n }\n};\n", "import {\n ColumnDescriptorsByName,\n Filter,\n FilterClause,\n MultiValueFilterClause,\n SingleValueFilterClause,\n} from \"@vuu-ui/vuu-filter-types\";\nimport {\n filterAsQuery,\n formatDate,\n isDateTimeColumn,\n isMultiClauseFilter,\n dateTimePattern,\n defaultPatternsByType,\n} from \"@vuu-ui/vuu-utils\";\nimport { filterClauses } from \"../filter-utils\";\n\nfunction applyFormatter<T>(\n filter: SingleValueFilterClause<T> | MultiValueFilterClause<T[]>,\n formatter: (t: T) => string\n): FilterClause {\n if (\"value\" in filter) {\n return { ...filter, value: formatter(filter.value) };\n } else {\n return { ...filter, values: filter.values.map(formatter) };\n }\n}\n\nfunction formatFilterValue(\n filter: FilterClause,\n columnsByName?: ColumnDescriptorsByName\n): FilterClause {\n const column = columnsByName?.[filter.column];\n if (column && isDateTimeColumn(column)) {\n const pattern = dateTimePattern(column.type);\n const formatter = (n: number) =>\n formatDate({ date: pattern.date ?? defaultPatternsByType.date })(\n new Date(n)\n );\n return applyFormatter(\n filter as\n | SingleValueFilterClause<number>\n | MultiValueFilterClause<number[]>,\n formatter\n );\n }\n\n return filter;\n}\n\nexport const getFilterLabel =\n (columnsByName?: ColumnDescriptorsByName) => (filter: Filter) => {\n if (isMultiClauseFilter(filter)) {\n const [firstClause] = filterClauses(filter);\n const formattedFilter = formatFilterValue(\n firstClause as FilterClause,\n columnsByName\n );\n return `${filterAsQuery(formattedFilter)} ${filter.op} ...`;\n } else {\n return filterAsQuery(formatFilterValue(filter, columnsByName));\n }\n };\n", "import { ColumnDescriptor } from \"@vuu-ui/vuu-table-types\";\nimport {\n AndFilter,\n Filter,\n FilterClause,\n FilterCombinatorOp,\n FilterWithPartialClause,\n MultiClauseFilter,\n NumericFilterClauseOp,\n} from \"@vuu-ui/vuu-filter-types\";\nimport {\n extractFilterForColumn,\n isAndFilter,\n isInFilter,\n isMultiClauseFilter,\n isMultiValueFilter,\n isNotNullOrUndefined,\n isOrFilter,\n isSingleValueFilter,\n partition,\n} from \"@vuu-ui/vuu-utils\";\n\nexport const AND = \"and\";\nexport const EQUALS = \"=\";\nexport const GREATER_THAN = \">\";\nexport const LESS_THAN = \"<\";\nexport const OR = \"or\";\nexport const STARTS_WITH = \"starts\";\nexport const ENDS_WITH = \"ends\";\nexport const IN = \"in\";\n\nexport type FilterType =\n | \"and\"\n | \"=\"\n | \">\"\n | \">=\"\n | \"in\"\n | \"<=\"\n | \"<\"\n | \"NOT_IN\"\n | \"NOT_SW\"\n | \"or\"\n | \"SW\";\n\nexport const filterClauses = (\n filter: Partial<Filter> | FilterWithPartialClause | null,\n clauses: Partial<FilterClause>[] = []\n): Partial<FilterClause>[] => {\n if (filter) {\n if (isMultiClauseFilter(filter)) {\n filter.filters.forEach((f) => clauses.push(...filterClauses(f)));\n } else {\n clauses.push(filter as Partial<FilterClause>);\n }\n }\n return clauses;\n};\n\ntype AddFilterOptions = {\n combineWith: FilterCombinatorOp;\n};\n\nconst DEFAULT_ADD_FILTER_OPTS: AddFilterOptions = {\n combineWith: \"and\",\n};\n\nexport const removeLastClause = (filter: MultiClauseFilter) => {\n const { filters } = filter;\n if (filters.length > 2) {\n return {\n ...filter,\n filters: filter.filters.slice(0, -1),\n };\n } else {\n // must be 2, we never have 1\n return filter.filters[0];\n }\n};\n\n/**\n Allows an empty FilterClause to be appended to an existing filter - for use\n in filter editing UI only.\n*/\nexport const addClause = (\n existingFilter: Filter,\n clause: Partial<Filter>,\n { combineWith = AND }: AddFilterOptions = DEFAULT_ADD_FILTER_OPTS\n): FilterWithPartialClause => {\n if (\n isMultiClauseFilter(existingFilter) &&\n existingFilter.op === combineWith\n ) {\n // if (isCompleteFilter(clause)) {\n return {\n ...existingFilter,\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n filters: existingFilter.filters.concat(clause),\n };\n // } else {\n // throw Error(\n // \"filter-utils, replaceFilter, only a valid clause can be added to a filter\"\n // );\n // }\n } else {\n return {\n op: combineWith,\n filters: [existingFilter, clause],\n };\n }\n};\n\nexport const replaceClause = (\n existingFilter: FilterWithPartialClause | Partial<Filter> | undefined,\n clause: Partial<FilterClause>,\n idx: number\n): Filter | Partial<Filter> => {\n if (existingFilter === undefined) return clause;\n return findAndReplaceClauseAtGivenIndex(existingFilter, clause, idx).filter;\n};\n\n/**\n * Given an existing filter and a filter clause, this function replaces the filter\n * clause at the given index `idx`.\n *\n * Indices are defined based on DepthFirstSearch.\n * (reason is that's what we use in `clauseFilters` when converting filter clauses into a flat list)\n *\n * Given a filter the indices are as follows [INDEX]:\n * {\n * op: and,\n * filters: [\n * {\n * op: or,\n * filters: [{op: =, column: currency, value: CAD} [0], {op: =, column: currency, value: USD} [1]]\n * },\n * {op: !=, column: bbg, value: AABC} [2]\n * ]\n * }\n *\n *\n * @param existingFilter - The existing filter\n * @param clause - Filter clause to replace with\n * @param idx - Index of filter clause to replace\n * @returns an object containing resulting filter\n */\nfunction findAndReplaceClauseAtGivenIndex(\n existingFilter: FilterWithPartialClause | Partial<Filter>,\n clause: Partial<FilterClause>,\n idx: number,\n currIdx = 0\n): { filter: Partial<Filter>; nextIdx: number } {\n if (isMultiClauseFilter(existingFilter)) {\n let i = currIdx;\n const filters = existingFilter.filters.map((f) => {\n const res = findAndReplaceClauseAtGivenIndex(f, clause, idx, i);\n i = res.nextIdx;\n return res.filter;\n }) as Filter[];\n return { filter: { ...existingFilter, filters }, nextIdx: i };\n } else if (idx !== currIdx) {\n return { filter: existingFilter as Partial<Filter>, nextIdx: currIdx + 1 };\n } else {\n const { name } = existingFilter;\n return {\n filter: { ...(isNotNullOrUndefined(name) ? { name } : {}), ...clause },\n nextIdx: currIdx + 1,\n };\n }\n}\n\nexport const addFilter = (\n existingFilter: Filter | undefined,\n filter: Filter,\n { combineWith = AND }: AddFilterOptions = DEFAULT_ADD_FILTER_OPTS\n): Filter | undefined => {\n if (includesNoValues(filter)) {\n if (isMultiClauseFilter(filter)) {\n // TODO identify the column that is contributing the no-values filter\n } else {\n existingFilter = removeFilterForColumn(existingFilter, {\n name: filter.column,\n });\n }\n } else if (includesAllValues(filter)) {\n if (isMultiClauseFilter(filter)) {\n // TODO identify the column that is contributing the all-values filter\n }\n return removeFilterForColumn(existingFilter, { name: filter.column ?? \"\" });\n }\n\n if (!existingFilter) {\n return filter;\n }\n if (!filter) {\n return existingFilter;\n }\n if (existingFilter.op === AND && filter.op === AND) {\n return {\n op: AND,\n filters: combine(existingFilter.filters, filter.filters),\n };\n }\n if (existingFilter.op === AND) {\n const filters = replaceOrInsert(existingFilter.filters, filter);\n return filters.length > 1 ? { op: AND, filters } : filters[0];\n }\n if (filter.op === AND) {\n return { op: AND, filters: filter.filters.concat(existingFilter) };\n }\n\n if (filterEquals(existingFilter, filter, true)) {\n return filter;\n }\n\n if (canMerge(existingFilter, filter)) {\n return merge(existingFilter, filter);\n }\n\n return { op: combineWith, filters: [existingFilter, filter] };\n};\n\nconst includesNoValues = (filter?: Filter | null): boolean => {\n if (!filter) {\n return false;\n }\n if (isInFilter(filter) && filter.values.length === 0) {\n return true;\n }\n return isAndFilter(filter) && filter.filters.some((f) => includesNoValues(f));\n};\n\ninterface CommonFilter {\n colName?: string;\n otherColFilters?: Filter[];\n mode?: any;\n value?: any;\n values?: any;\n op?: \"or\" | \"and\";\n column?: string;\n filters?: Filter[];\n}\n\nexport interface OtherFilter extends CommonFilter {\n type: FilterType;\n values?: any[];\n}\n\nconst includesAllValues = (filter?: Filter | null): boolean => {\n if (!filter) {\n return false;\n }\n if (filter.op === STARTS_WITH && filter.value === \"\") {\n return true;\n }\n return filter.op === STARTS_WITH && filter.value === \"\";\n};\n\nconst replaceOrInsert = (filters: Filter[], filter: Filter) => {\n return filters.concat(filter);\n};\n\nconst merge = (f1: Filter, f2: Filter): Filter | undefined => {\n if (includesNoValues(f2)) {\n return f2;\n }\n if (isInFilter(f1) && isInFilter(f2)) {\n return {\n ...f1,\n values: [\n ...f1.values,\n ...(f2.values as any[]).filter(\n (v: string | number) => !(f1.values as any[]).includes(v)\n ),\n ],\n };\n } else if (isInFilter(f1) && f2.op === EQUALS) {\n return {\n ...f1,\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n values: f1.values.concat([f2.value]),\n };\n } else if (f1.op === EQUALS && f2.op === EQUALS) {\n return {\n column: f1.column,\n op: IN,\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n values: [f1.value, f2.value],\n };\n }\n return f2;\n};\n\nconst combine = (existingFilters: Filter[], replacementFilters: Filter[]) => {\n const equivalentType = ({ op: op1 }: Filter, { op: op2 }: Filter) => {\n return (\n op1 === op2 ||\n (op1[0] === \">\" && op2[0] === \">\") ||\n (op1[0] === \"<\" && op2[0] === \"<\")\n );\n };\n const replaces = (existingFilter: Filter, replacementFilter: Filter) => {\n return (\n existingFilter.column === replacementFilter.column &&\n equivalentType(existingFilter, replacementFilter)\n );\n };\n const stillApplicable = (existingFilter: Filter) =>\n replacementFilters.some((replacementFilter) =>\n replaces(existingFilter, replacementFilter)\n ) === false;\n return existingFilters.filter(stillApplicable).concat(replacementFilters);\n};\n\nexport const removeFilter = (sourceFilter: Filter, filterToRemove: Filter) => {\n if (filterEquals(sourceFilter, filterToRemove, true)) {\n return null;\n }\n if (sourceFilter.op !== AND) {\n throw Error(\n `removeFilter cannot remove ${JSON.stringify(\n filterToRemove\n )} from ${JSON.stringify(sourceFilter)}`\n );\n }\n const filters = sourceFilter.filters.filter(\n (f) => !filterEquals(f, filterToRemove)\n );\n return filters.length > 0 ? { type: AND, filters } : null;\n};\n\nexport const splitFilterOnColumn = (\n columnName: string,\n filter?: Filter\n): [Filter | undefined, Filter | undefined] => {\n if (!filter) {\n return [undefined, undefined];\n }\n if (filter.column === columnName) {\n return [filter, undefined];\n }\n if (filter.op !== AND) {\n return [undefined, filter];\n }\n const [[columnFilter = undefined], filters] = partition(\n (filter as AndFilter).filters,\n (f) => f.column === columnName\n );\n return filters.length === 1\n ? [columnFilter, filters[0]]\n : [columnFilter, { op: AND, filters }];\n};\n\nexport const overrideColName = (filter: Filter, column: string): Filter => {\n if (isMultiClauseFilter(filter)) {\n return {\n op: filter.op,\n filters: filter.filters.map((f) => overrideColName(f, column)),\n };\n }\n return { ...filter, column };\n};\n\nexport const filterIncludesColumn = (\n filter: Filter,\n column: ColumnDescriptor\n): boolean => {\n if (!filter) {\n return false;\n }\n const { op, column: filterColName } = filter;\n switch (op) {\n case AND:\n case OR:\n return (\n filter.filters != null &&\n filter.filters.some((f) => filterIncludesColumn(f, column))\n );\n default:\n return filterColName === column.name;\n }\n};\n\nconst removeFilterForColumn = (\n sourceFilter: Filter | undefined,\n column: ColumnDescriptor\n): Filter | undefined => {\n const colName = column.name;\n if (!sourceFilter) {\n return undefined;\n }\n if (sourceFilter.column === colName) {\n return undefined;\n }\n if (isAndFilter(sourceFilter) || isOrFilter(sourceFilter)) {\n const { op } = sourceFilter;\n const filters = sourceFilter.filters;\n const otherColFilters = filters.filter((f) => f.column !== colName);\n switch (otherColFilters.length) {\n case 0:\n return undefined;\n case 1:\n return otherColFilters[0];\n default:\n return { op, filters: otherColFilters };\n }\n }\n return sourceFilter;\n};\n\nconst canMerge = (f1: Filter, f2: Filter) =>\n f1.column === f2.column &&\n (f1.op === \"=\" || f1.op === \"in\") &&\n (f2.op === \"=\" || f2.op === \"in\");\n\nconst sameValues = <T>(arr1: T[], arr2: T[]) => {\n if (arr1 === arr2) {\n return true;\n }\n if (arr1.length === arr2.length) {\n const a = arr1.slice().sort();\n const b = arr2.slice().sort();\n return a.join(\"|\") === b.join(\"|\");\n }\n return false;\n};\n\nexport const filterEquals = (f1?: Filter, f2?: Filter, strict = false) => {\n if (!strict) {\n return true;\n }\n if (f1 && f2 && canMerge(f1, f2)) {\n return (\n f1.op === f2.op &&\n ((isSingleValueFilter(f1) &&\n isSingleValueFilter(f2) &&\n f1.value === f2.value) ||\n (isMultiValueFilter(f1) &&\n isMultiValueFilter(f2) &&\n sameValues(f1.values as any[], f2.values)))\n );\n }\n return false;\n};\n\nexport const updateFilter = (\n filter: Filter | undefined,\n newFilter: Filter | undefined,\n mode: \"add\" | \"replace\"\n): Filter | undefined => {\n if (filter && newFilter) {\n if (mode === \"replace\") {\n return newFilter;\n }\n if (filter.op === \"and\") {\n return {\n ...filter,\n filters: filter.filters.concat(newFilter),\n };\n }\n const { column: columnName } = newFilter;\n if (columnName) {\n const existingClause = newFilter.column\n ? extractFilterForColumn(filter, columnName)\n : undefined;\n if (existingClause && columnName) {\n // The filter already contains a clause for this column, replace\n // with the new clause\n const result = removeFilterForColumn(filter, { name: columnName });\n return updateFilter(result, newFilter, \"add\");\n }\n }\n return {\n op: \"and\",\n filters: [filter, newFilter],\n };\n }\n if (newFilter) {\n return newFilter;\n }\n return filter;\n};\n\nexport const getTypeaheadFilter = (\n column: string,\n filterValues: string[],\n isStartsWithFilter?: boolean\n): Filter | undefined => {\n if (filterValues.length === 0) {\n return undefined;\n }\n\n if (isStartsWithFilter) {\n // multiple starts with filters not currently supported\n const startsWith = filterValues[0].substring(0, filterValues[0].length - 3);\n return {\n column,\n op: \"starts\",\n value: `\"${startsWith}\"`,\n };\n }\n\n return {\n column,\n op: \"in\",\n values: filterValues.map((value) => `\"${value}\"`),\n };\n};\n\nexport const getNumericFilter = (\n column: string,\n op?: NumericFilterClauseOp,\n value?: number\n): FilterClause | undefined => {\n if (op === undefined) return undefined;\n if (value === undefined || isNaN(value)) return undefined;\n return { column, op, value };\n};\n", "import { PopupMenu } from \"@vuu-ui/vuu-popups\";\n\nexport const FilterBarMenu = () => {\n const classBase = \"vuuFilterBarMenu\";\n return (\n <div className={classBase}>\n <PopupMenu icon=\"tune\" menuLocation=\"filter-bar-menu\" tabIndex={-1} />\n </div>\n );\n};\n", "import { MenuActionHandler } from \"@vuu-ui/vuu-data-types\";\nimport { ColumnDescriptor } from \"@vuu-ui/vuu-table-types\";\nimport {\n ColumnDescriptorsByName,\n Filter,\n FilterClause,\n FilterWithPartialClause,\n} from \"@vuu-ui/vuu-filter-types\";\nimport { PromptProps } from \"@vuu-ui/vuu-popups\";\nimport {\n EditableLabelProps,\n NavigationOutOfBoundsHandler,\n} from \"@vuu-ui/vuu-ui-controls\";\nimport { dispatchMouseEvent, isMultiClauseFilter } from \"@vuu-ui/vuu-utils\";\nimport {\n FocusEventHandler,\n KeyboardEvent,\n KeyboardEventHandler,\n RefObject,\n useCallback,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { FilterClauseCancelHandler } from \"../filter-clause/useFilterClauseEditor\";\nimport { FilterPillProps } from \"../filter-pill\";\nimport { FilterMenuOptions } from \"../filter-pill-menu\";\nimport { addClause, removeLastClause, replaceClause } from \"../filter-utils\";\nimport { FilterBarProps } from \"./FilterBar\";\nimport { useFilterState } from \"./useFilterState\";\nimport { useApplyFilterOnChange } from \"./useApplyFilterOnChange\";\n\nexport interface FilterBarHookProps\n extends Pick<\n FilterBarProps,\n | \"columnDescriptors\"\n | \"defaultFilterState\"\n | \"filterState\"\n | \"onApplyFilter\"\n | \"onFilterDeleted\"\n | \"onFilterRenamed\"\n | \"onFilterStateChanged\"\n | \"showMenu\"\n > {\n containerRef: RefObject<HTMLDivElement>;\n}\n\nconst EMPTY_FILTER_CLAUSE: Partial<Filter> = {};\n\nexport const useFilterBar = ({\n columnDescriptors,\n containerRef,\n defaultFilterState,\n filterState,\n onApplyFilter,\n onFilterDeleted,\n onFilterRenamed,\n onFilterStateChanged,\n showMenu: showMenuProp,\n}: FilterBarHookProps) => {\n const addButtonRef = useRef<HTMLButtonElement>(null);\n const editingFilter = useRef<Filter | undefined>();\n const [showMenu, setShowMenu] = useState(showMenuProp);\n const [editFilter, setEditFilter] = useState<\n Partial<Filter> | FilterWithPartialClause | undefined\n >();\n const [promptProps, setPromptProps] = useState<PromptProps | null>(null);\n\n const columnsByName = useMemo(\n () => columnDescriptorsByName(columnDescriptors),\n [columnDescriptors]\n );\n\n const {\n activeFilterIndex,\n filters,\n onAddFilter,\n onChangeFilter,\n onDeleteFilter,\n onRenameFilter,\n onChangeActiveFilterIndex,\n } = useFilterState({\n defaultFilterState,\n filterState,\n onFilterDeleted,\n onFilterRenamed,\n onFilterStateChanged,\n });\n\n useApplyFilterOnChange({\n activeFilterIndex,\n columnsByName,\n filters,\n onApplyFilter,\n });\n\n const editPillLabel = useCallback(\n (index: number) => {\n requestAnimationFrame(() => {\n const pills = containerRef.current?.querySelectorAll(\n \".vuuFilterPill\"\n ) as undefined | HTMLElement[];\n if (pills?.[index]) {\n const editableLabel = pills[index].querySelector(\n \".vuuEditableLabel\"\n ) as HTMLElement;\n if (editableLabel) {\n dispatchMouseEvent(editableLabel, \"dblclick\");\n }\n }\n });\n },\n [containerRef]\n );\n\n const focusFilterClause = useCallback(\n (_ = 0) => {\n requestAnimationFrame(() => {\n const input = containerRef.current?.querySelector(\n \".vuuFilterClause .saltInput-input\"\n ) as undefined | HTMLInputElement;\n if (input) {\n input.focus();\n }\n });\n },\n [containerRef]\n );\n\n const focusFilterPill = useCallback(\n (index?: number) => {\n requestAnimationFrame(() => {\n const target =\n typeof index === \"number\"\n ? (containerRef.current?.querySelector(\n `.vuuOverflowContainer-item[data-index=\"${index}\"] .vuuFilterPill`\n ) as undefined | HTMLInputElement)\n : (containerRef.current?.querySelector(\n \".vuuFilterPill[tabindex]\"\n ) as undefined | HTMLInputElement);\n if (target) {\n target.focus();\n }\n });\n },\n [containerRef]\n );\n\n const deleteConfirmed = useCallback(\n (filter: Filter) => {\n onDeleteFilter(filter);\n\n // TODO move focus to next/previous filter\n requestAnimationFrame(() => {\n if (filters.length) {\n focusFilterPill(0);\n }\n });\n },\n [filters.length, focusFilterPill, onDeleteFilter]\n );\n\n const getDeletePrompt = useMemo(\n () => (filter: Filter) => {\n const close = () => {\n setPromptProps(null);\n focusFilterPill();\n };\n return {\n confirmButtonLabel: \"Remove\",\n icon: \"warn-triangle\",\n onCancel: close,\n onClose: close,\n onConfirm: () => {\n setPromptProps(null);\n deleteConfirmed(filter);\n },\n text: `Are you sure you want to delete ${filter.name}`,\n title: \"Remove Filter\",\n variant: \"warn\",\n } as PromptProps;\n },\n [deleteConfirmed, focusFilterPill]\n );\n\n const deleteFilter = useCallback(\n (filter: Filter, withPrompt: boolean) => {\n if (withPrompt) {\n setPromptProps(getDeletePrompt(filter));\n } else {\n deleteConfirmed(filter);\n }\n },\n [deleteConfirmed, getDeletePrompt]\n );\n\n const handleBeginEditFilterName = useCallback((filter: Filter) => {\n editingFilter.current = filter;\n }, []);\n\n // TODO handle cancel edit name\n const handleExitEditFilterName: EditableLabelProps[\"onExitEditMode\"] =\n useCallback(\n (_, editedValue = \"\") => {\n if (editingFilter.current) {\n const indexOfEditedFilter = onRenameFilter(\n editingFilter.current,\n editedValue\n );\n editingFilter.current = undefined;\n focusFilterPill(indexOfEditedFilter);\n }\n },\n [focusFilterPill, onRenameFilter]\n );\n\n const handlePillMenuAction = useCallback<MenuActionHandler>(\n ({ menuId, options }) => {\n switch (menuId) {\n case \"delete-filter\": {\n const { filter } = options as FilterMenuOptions;\n deleteFilter(filter, true);\n return true;\n }\n case \"rename-filter\": {\n const { filter } = options as FilterMenuOptions;\n const index = filters.indexOf(filter);\n editPillLabel(index);\n return true;\n }\n case \"edit-filter\": {\n const { filter } = options as FilterMenuOptions;\n editingFilter.current = filter;\n setEditFilter(filter);\n focusFilterClause();\n return true;\n }\n default:\n return false;\n }\n },\n [deleteFilter, editPillLabel, filters, focusFilterClause]\n );\n\n const addIfNewElseUpdate = useCallback(\n (edited: Filter, existing: Filter | undefined) => {\n if (existing === undefined) {\n const idx = onAddFilter(edited);\n editPillLabel(idx);\n } else {\n onChangeFilter(existing, edited);\n }\n },\n [editPillLabel, onAddFilter, onChangeFilter]\n );\n\n const handleMenuAction = useCallback<MenuActionHandler>(\n ({ menuId }) => {\n switch (menuId) {\n case \"apply-save\": {\n const editedFilter = editFilter as Filter;\n addIfNewElseUpdate(editedFilter, editingFilter.current);\n setEditFilter(undefined);\n editingFilter.current = undefined;\n setShowMenu(false);\n return true;\n }\n case \"and-clause\": {\n const newFilter = addClause(\n editFilter as Filter,\n EMPTY_FILTER_CLAUSE\n );\n setEditFilter(newFilter);\n setShowMenu(false);\n return true;\n }\n case \"or-clause\":\n setEditFilter((filter) =>\n addClause(filter as Filter, EMPTY_FILTER_CLAUSE, {\n combineWith: \"or\",\n })\n );\n setShowMenu(false);\n return true;\n default:\n return false;\n }\n },\n [editFilter, addIfNewElseUpdate]\n );\n\n const handleClickAddFilter = useCallback(() => {\n setEditFilter({});\n }, [setEditFilter]);\n\n const handleClickRemoveFilter = useCallback(() => {\n setEditFilter(undefined);\n }, []);\n\n const pillProps: Partial<FilterPillProps> = {\n onBeginEdit: handleBeginEditFilterName,\n onMenuAction: handlePillMenuAction,\n onExitEditMode: handleExitEditFilterName,\n };\n\n const handleChangeFilterClause = useCallback(\n (idx: number) => (filterClause: Partial<FilterClause>) => {\n if (filterClause !== undefined) {\n setEditFilter((ef) => replaceClause(ef, filterClause, idx));\n setShowMenu(true);\n }\n },\n []\n );\n\n const handleCancelFilterClause = useCallback<FilterClauseCancelHandler>(\n (reason) => {\n if (reason === \"Backspace\" && isMultiClauseFilter(editFilter)) {\n setEditFilter(removeLastClause(editFilter));\n }\n },\n [editFilter]\n );\n\n const handleBlurFilterClause = useCallback<FocusEventHandler>((e) => {\n const target = e.target as HTMLElement;\n const relatedTarget = e.relatedTarget as HTMLElement;\n const filterClause = target.closest(\".vuuFilterClause\");\n if (filterClause?.contains(relatedTarget)) {\n // do nothing\n } else {\n const dropdownId = target.getAttribute(\"aria-owns\");\n const dropDown = dropdownId ? document.getElementById(dropdownId) : null;\n if (dropDown?.contains(relatedTarget)) {\n // do nothing\n } else {\n // if clause is complete\n setShowMenu(true);\n }\n }\n }, []);\n\n const handleFocusFilterClause = useCallback(() => {\n setShowMenu(false);\n }, []);\n\n const handleKeyDownFilterbar = useCallback(\n (evt: KeyboardEvent) => {\n if (evt.key === \"Escape\" && editFilter !== undefined) {\n // TODO confirm if edits applied ?\n setEditFilter(undefined);\n requestAnimationFrame(() => {\n // focus edited pill\n });\n }\n },\n [editFilter]\n );\n\n const handleKeyDownMenu = useCallback<KeyboardEventHandler>(\n (evt) => {\n const { current: container } = containerRef;\n if (evt.key === \"Backspace\" && container) {\n evt.preventDefault();\n const fields = Array.from(\n container.querySelectorAll(\".vuuFilterClauseField\")\n );\n if (fields.length > 0) {\n const field = fields.at(-1) as HTMLElement;\n field?.querySelector(\"input\")?.focus();\n }\n setShowMenu(false);\n } else if (evt.key === \"Tab\") {\n if (evt.shiftKey && container) {\n const clearButtons = Array.from(\n container.querySelectorAll(\".vuuFilterClause-clearButton\")\n ) as HTMLButtonElement[];\n if (clearButtons.length > 0) {\n const clearButton = clearButtons.at(-1) as HTMLButtonElement;\n setTimeout(() => {\n clearButton.focus();\n }, 100);\n }\n } else {\n console.log(\"apply current selection\");\n }\n }\n },\n [containerRef]\n );\n\n const handleAddButtonKeyDown = useCallback<KeyboardEventHandler>((evt) => {\n if (evt.key === \"ArrowLeft\") {\n console.log(\"navgiate to the Toolbar\");\n }\n }, []);\n\n const handlePillNavigationOutOfBounds =\n useCallback<NavigationOutOfBoundsHandler>((direction) => {\n if (direction === \"end\") {\n addButtonRef.current?.focus();\n }\n }, []);\n\n const addButtonProps = {\n ref: addButtonRef,\n onKeyDown: handleAddButtonKeyDown,\n };\n\n return {\n activeFilterIndex,\n addButtonProps,\n columnsByName,\n editFilter,\n filters,\n onBlurFilterClause: handleBlurFilterClause,\n onCancelFilterClause: handleCancelFilterClause,\n onChangeActiveFilterIndex,\n onClickAddFilter: handleClickAddFilter,\n onClickRemoveFilter: handleClickRemoveFilter,\n onChangeFilterClause: handleChangeFilterClause,\n onFocusFilterClause: handleFocusFilterClause,\n onKeyDownFilterbar: handleKeyDownFilterbar,\n onKeyDownMenu: handleKeyDownMenu,\n onMenuAction: handleMenuAction,\n onNavigateOutOfBounds: handlePillNavigationOutOfBounds,\n pillProps,\n promptProps,\n showMenu,\n };\n};\n\nfunction columnDescriptorsByName(\n columns: ColumnDescriptor[]\n): ColumnDescriptorsByName {\n return columns.reduce((m, col) => ({ ...m, [col.name]: col }), {});\n}\n", "import { useCallback } from \"react\";\nimport { Filter, FilterState } from \"@vuu-ui/vuu-filter-types\";\nimport { useControlled } from \"@vuu-ui/vuu-ui-controls\";\n\nexport interface FiltersHookProps {\n defaultFilterState?: FilterState;\n filterState?: FilterState;\n onFilterDeleted?: (filter: Filter) => void;\n onFilterRenamed?: (filter: Filter, name: string) => void;\n onFilterStateChanged?: (s: FilterState) => void;\n}\n\nexport const useFilterState = ({\n defaultFilterState,\n onFilterDeleted,\n onFilterRenamed,\n onFilterStateChanged,\n filterState: filterStateProp,\n}: FiltersHookProps) => {\n const [filterState, setFilterState] = useControlled<FilterState>({\n controlled: filterStateProp,\n default: defaultFilterState ?? { filters: [], activeIndices: [] },\n name: \"useFilterState\",\n state: \"FilterState\",\n });\n\n const handleFilterStateChange = useCallback(\n (s: FilterState) => {\n setFilterState(s);\n onFilterStateChanged?.(s);\n },\n [onFilterStateChanged, setFilterState]\n );\n\n const handleAddFilter = useCallback(\n (filter: Filter) => {\n const index = filterState.filters.length;\n const newFilters = filterState.filters.concat(filter);\n const newIndices = appendIfNotPresent(filterState.activeIndices, index);\n handleFilterStateChange({\n filters: newFilters,\n activeIndices: newIndices,\n });\n return index;\n },\n [filterState, handleFilterStateChange]\n );\n\n const handleDeleteFilter = useCallback(\n (filter: Filter) => {\n let index = -1;\n const newFilters = filterState.filters.filter((f, i) => {\n if (f !== filter) {\n return true;\n } else {\n index = i;\n return false;\n }\n });\n\n const newIndices = removeIndexAndDecrementLarger(\n filterState.activeIndices,\n index\n );\n\n handleFilterStateChange({\n filters: newFilters,\n activeIndices: newIndices,\n });\n onFilterDeleted?.(filter);\n return index;\n },\n [\n filterState.filters,\n filterState.activeIndices,\n handleFilterStateChange,\n onFilterDeleted,\n ]\n );\n\n const handleRenameFilter = useCallback(\n (filter: Filter, name: string) => {\n let index = -1;\n const newFilters = filterState.filters.map((f, i) => {\n if (f === filter) {\n index = i;\n return { ...filter, name };\n } else {\n return f;\n }\n });\n handleFilterStateChange({ ...filterState, filters: newFilters });\n onFilterRenamed?.(filter, name);\n\n return index;\n },\n [filterState, handleFilterStateChange, onFilterRenamed]\n );\n\n const handleChangeFilter = useCallback(\n (oldFilter: Filter, newFilter: Filter) => {\n let index = -1;\n const newFilters = filterState.filters.map((f, i) => {\n if (f === oldFilter) {\n index = i;\n return newFilter;\n } else {\n return f;\n }\n });\n handleFilterStateChange({ ...filterState, filters: newFilters });\n\n return index;\n },\n [filterState, handleFilterStateChange]\n );\n\n const handleActiveIndicesChange = useCallback(\n (indices: number[]) =>\n handleFilterStateChange({ ...filterState, activeIndices: indices }),\n [filterState, handleFilterStateChange]\n );\n\n return {\n activeFilterIndex: filterState.activeIndices,\n filters: filterState.filters,\n onChangeActiveFilterIndex: handleActiveIndicesChange,\n onAddFilter: handleAddFilter,\n onChangeFilter: handleChangeFilter,\n onDeleteFilter: handleDeleteFilter,\n onRenameFilter: handleRenameFilter,\n };\n};\n\nconst appendIfNotPresent = (ns: number[], n: number) =>\n ns.includes(n) ? ns : ns.concat(n);\n\nconst removeIndexAndDecrementLarger = (\n indices: number[],\n idxToRemove: number\n) => {\n return indices.reduce<number[]>((res, i) => {\n if (i === idxToRemove) return res;\n return res.concat(i > idxToRemove ? i - 1 : i);\n }, []);\n};\n", "import { useCallback, useEffect } from \"react\";\nimport {\n ColumnDescriptorsByName,\n Filter,\n FilterState,\n} from \"@vuu-ui/vuu-filter-types\";\nimport { DataSourceFilter } from \"@vuu-ui/vuu-data-types\";\nimport { filterAsQuery } from \"@vuu-ui/vuu-utils\";\n\ninterface ApplyFilterHookProps {\n activeFilterIndex: FilterState[\"activeIndices\"];\n columnsByName: ColumnDescriptorsByName;\n filters: FilterState[\"filters\"];\n onApplyFilter: (f: DataSourceFilter) => void;\n}\n\nexport function useApplyFilterOnChange({\n activeFilterIndex,\n columnsByName,\n filters,\n onApplyFilter,\n}: ApplyFilterHookProps) {\n const applyFilter = useCallback(\n (filter?: Filter) => {\n const query = filter ? filterAsQuery(filter, { columnsByName }) : \"\";\n onApplyFilter({ filter: query, filterStruct: filter });\n },\n [columnsByName, onApplyFilter]\n );\n\n useEffect(() => {\n const activeFilters = activeFilterIndex.map((i) => filters[i]);\n if (activeFilters.length === 0) {\n applyFilter();\n } else if (activeFilters.length === 1) {\n const [filter] = activeFilters;\n applyFilter(filter);\n } else {\n applyFilter({ op: \"and\", filters: activeFilters });\n }\n }, [activeFilterIndex, applyFilter, filters]);\n}\n", "import { Filter } from \"@vuu-ui/vuu-filter-types\";\nimport { Button } from \"@salt-ds/core\";\nimport { HTMLAttributes } from \"react\";\nimport {\n filterSubmissionHandler,\n SuggestionConsumer,\n useCodeMirrorEditor,\n} from \"./useCodeMirrorEditor\";\n\nimport \"./FilterInput.css\";\n\nconst classBase = \"vuuFilterInput\";\n\nexport interface FilterInputProps\n extends SuggestionConsumer,\n HTMLAttributes<HTMLDivElement> {\n iconName?: string;\n existingFilter?: Filter;\n namedFilters?: Map<string, string>;\n onSubmitFilter?: filterSubmissionHandler;\n}\n\nexport const FilterInput = ({\n existingFilter,\n iconName = \"filter\",\n namedFilters,\n onSubmitFilter,\n suggestionProvider,\n ...props\n}: FilterInputProps) => {\n const { editorRef, clearInput } = useCodeMirrorEditor({\n existingFilter,\n onSubmitFilter,\n suggestionProvider,\n });\n\n return (\n <div {...props} className={classBase}>\n <Button\n className={`${classBase}-FilterButton`}\n data-icon={iconName}\n tabIndex={-1}\n />\n <div className={`${classBase}-Editor`} ref={editorRef} />\n <Button\n className={`${classBase}-ClearButton`}\n data-icon=\"close-circle\"\n onClick={clearInput}\n />\n </div>\n );\n};\n", "import {\n autocompletion,\n Completion,\n defaultKeymap,\n EditorState,\n EditorView,\n ensureSyntaxTree,\n keymap,\n minimalSetup,\n startCompletion,\n VuuCompletion,\n} from \"@vuu-ui/vuu-codemirror\";\nimport { walkTree } from \"@vuu-ui/vuu-filter-parser\";\nimport { Filter } from \"@vuu-ui/vuu-filter-types\";\nimport cx from \"clsx\";\nimport { MutableRefObject, useEffect, useMemo, useRef } from \"react\";\nimport { filterLanguageSupport } from \"./FilterLanguage\";\nimport { vuuHighlighting } from \"./highlighting\";\nimport { vuuTheme } from \"./theme\";\nimport {\n ApplyCompletion,\n FilterSubmissionMode,\n useAutoComplete,\n} from \"./useFilterAutoComplete\";\nimport { FilterSaveOptions } from \"./useFilterSuggestionProvider\";\n\nexport type SuggestionType =\n | \"column\"\n | \"columnValue\"\n | \"operator\"\n | \"save\"\n | \"name\";\n\nexport interface FilterSuggestionOptions {\n quoted?: boolean;\n columnName?: string;\n existingFilter?: Filter;\n filterName?: string;\n onSubmit?: () => void;\n operator?: string;\n startsWith?: string;\n selection?: string[];\n}\n\nexport type getFilterSuggestionsType = (\n suggestionType: SuggestionType,\n options?: FilterSuggestionOptions\n) => Promise<Completion[]>;\n\nexport interface IFilterSuggestionProvider {\n getSuggestions: getFilterSuggestionsType;\n isPartialMatch: (\n valueType: SuggestionType,\n columnName?: string,\n text?: string | undefined\n ) => Promise<boolean>;\n}\n\nexport interface SuggestionConsumer {\n suggestionProvider: IFilterSuggestionProvider;\n}\n\nconst getView = (ref: MutableRefObject<EditorView | undefined>): EditorView => {\n if (ref.current == undefined) {\n throw Error(\"EditorView not defined\");\n }\n return ref.current;\n};\n\nconst getOptionClass = (completion: VuuCompletion) => {\n return cx(\"vuuSuggestion\", {\n vuuIllustration: completion.isIllustration,\n });\n};\n\nconst stripName = (filterQuery: string) => {\n const pos = filterQuery.lastIndexOf(\" as \");\n if (pos !== -1) {\n return filterQuery.slice(0, pos);\n } else {\n return filterQuery;\n }\n};\n\nconst noop = () => console.log(\"noooop\");\n\nexport type filterSubmissionHandler = (\n filter: Filter | undefined,\n filterQuery: string,\n mode?: FilterSubmissionMode,\n filterName?: string\n) => void;\n\nexport interface CodeMirrorEditorProps {\n existingFilter?: Filter;\n onSubmitFilter?: filterSubmissionHandler;\n saveOptions?: FilterSaveOptions;\n suggestionProvider: IFilterSuggestionProvider;\n}\n\nexport const useCodeMirrorEditor = ({\n existingFilter,\n onSubmitFilter,\n suggestionProvider,\n}: CodeMirrorEditorProps) => {\n const editorRef = useRef<HTMLDivElement>(null);\n const onSubmit = useRef<ApplyCompletion>(noop);\n const viewRef = useRef<EditorView>();\n const completionFn = useAutoComplete(\n suggestionProvider,\n onSubmit,\n existingFilter\n );\n\n const [createState, clearInput] = useMemo(() => {\n const parseFilter = ():\n | [Filter, string, string | undefined]\n | [undefined, \"\", undefined] => {\n const view = getView(viewRef);\n const source = view.state.doc.toString();\n const tree = ensureSyntaxTree(view.state, view.state.doc.length, 5000);\n if (tree) {\n const filter = walkTree(tree, source) as Filter;\n return [filter, stripName(source), filter.name];\n } else {\n return [undefined, \"\", undefined];\n }\n };\n\n const clearInput = () => {\n getView(viewRef).setState(createState());\n };\n\n const submitFilterAndClearInput = (mode?: FilterSubmissionMode) => {\n const [filter, filterQuery, filterName] = parseFilter();\n onSubmitFilter?.(filter, filterQuery, mode, filterName);\n clearInput();\n };\n\n const submitFilter = (key: string) => {\n return keymap.of([\n {\n key,\n run() {\n submitFilterAndClearInput();\n return true;\n },\n },\n ]);\n };\n\n const showSuggestions = (key: string) => {\n return keymap.of([\n {\n key,\n run() {\n startCompletion(getView(viewRef));\n return true;\n },\n },\n ]);\n };\n\n const createState = (): EditorState =>\n EditorState.create({\n doc: \"\",\n extensions: [\n minimalSetup,\n autocompletion({\n override: [completionFn],\n optionClass: getOptionClass,\n }),\n filterLanguageSupport(),\n keymap.of(defaultKeymap),\n submitFilter(\"Ctrl-Enter\"),\n showSuggestions(\"ArrowDown\"),\n EditorView.updateListener.of((v) => {\n const view = getView(viewRef);\n if (v.docChanged) {\n startCompletion(view);\n }\n }),\n EditorState.transactionFilter.of((tr) =>\n tr.newDoc.lines > 1 ? [] : tr\n ),\n vuuTheme,\n vuuHighlighting,\n ],\n });\n\n onSubmit.current = (mode?: FilterSubmissionMode) => {\n submitFilterAndClearInput(mode);\n // TODO refocu sthe editor\n setTimeout(() => {\n getView(viewRef).focus();\n }, 100);\n };\n\n return [createState, clearInput];\n }, [completionFn, onSubmitFilter]);\n\n useEffect(() => {\n if (!editorRef.current) {\n throw Error(\"editor not in dom\");\n }\n\n viewRef.current = new EditorView({\n state: createState(),\n parent: editorRef.current,\n });\n\n return () => {\n viewRef.current?.destroy();\n };\n }, [completionFn, createState]);\n\n return { editorRef, clearInput };\n};\n", "// FIXME profile adding a per-Tree TreeNode cache, validating it by\n// parent pointer\n/// The default maximum length of a `TreeBuffer` node.\nconst DefaultBufferLength = 1024;\nlet nextPropID = 0;\nclass Range {\n constructor(from, to) {\n this.from = from;\n this.to = to;\n }\n}\n/// Each [node type](#common.NodeType) or [individual tree](#common.Tree)\n/// can have metadata associated with it in props. Instances of this\n/// class represent prop names.\nclass NodeProp {\n /// Create a new node prop type.\n constructor(config = {}) {\n this.id = nextPropID++;\n this.perNode = !!config.perNode;\n this.deserialize = config.deserialize || (() => {\n throw new Error(\"This node type doesn't define a deserialize function\");\n });\n }\n /// This is meant to be used with\n /// [`NodeSet.extend`](#common.NodeSet.extend) or\n /// [`LRParser.configure`](#lr.ParserConfig.props) to compute\n /// prop values for each node type in the set. Takes a [match\n /// object](#common.NodeType^match) or function that returns undefined\n /// if the node type doesn't get this prop, and the prop's value if\n /// it does.\n add(match) {\n if (this.perNode)\n throw new RangeError(\"Can't add per-node props to node types\");\n if (typeof match != \"function\")\n match = NodeType.match(match);\n return (type) => {\n let result = match(type);\n return result === undefined ? null : [this, result];\n };\n }\n}\n/// Prop that is used to describe matching delimiters. For opening\n/// delimiters, this holds an array of node names (written as a\n/// space-separated string when declaring this prop in a grammar)\n/// for the node types of closing delimiters that match it.\nNodeProp.closedBy = new NodeProp({ deserialize: str => str.split(\" \") });\n/// The inverse of [`closedBy`](#common.NodeProp^closedBy). This is\n/// attached to closing delimiters, holding an array of node names\n/// of types of matching opening delimiters.\nNodeProp.openedBy = new NodeProp({ deserialize: str => str.split(\" \") });\n/// Used to assign node types to groups (for example, all node\n/// types that represent an expression could be tagged with an\n/// `\"Expression\"` group).\nNodeProp.group = new NodeProp({ deserialize: str => str.split(\" \") });\n/// The hash of the [context](#lr.ContextTracker.constructor)\n/// that the node was parsed in, if any. Used to limit reuse of\n/// contextual nodes.\nNodeProp.contextHash = new NodeProp({ perNode: true });\n/// The distance beyond the end of the node that the tokenizer\n/// looked ahead for any of the tokens inside the node. (The LR\n/// parser only stores this when it is larger than 25, for\n/// efficiency reasons.)\nNodeProp.lookAhead = new NodeProp({ perNode: true });\n/// This per-node prop is used to replace a given node, or part of a\n/// node, with another tree. This is useful to include trees from\n/// different languages in mixed-language parsers.\nNodeProp.mounted = new NodeProp({ perNode: true });\n/// A mounted tree, which can be [stored](#common.NodeProp^mounted) on\n/// a tree node to indicate that parts of its content are\n/// represented by another tree.\nclass MountedTree {\n constructor(\n /// The inner tree.\n tree, \n /// If this is null, this tree replaces the entire node (it will\n /// be included in the regular iteration instead of its host\n /// node). If not, only the given ranges are considered to be\n /// covered by this tree. This is used for trees that are mixed in\n /// a way that isn't strictly hierarchical. Such mounted trees are\n /// only entered by [`resolveInner`](#common.Tree.resolveInner)\n /// and [`enter`](#common.SyntaxNode.enter).\n overlay, \n /// The parser used to create this subtree.\n parser) {\n this.tree = tree;\n this.overlay = overlay;\n this.parser = parser;\n }\n}\nconst noProps = Object.create(null);\n/// Each node in a syntax tree has a node type associated with it.\nclass NodeType {\n /// @internal\n constructor(\n /// The name of the node type. Not necessarily unique, but if the\n /// grammar was written properly, different node types with the\n /// same name within a node set should play the same semantic\n /// role.\n name, \n /// @internal\n props, \n /// The id of this node in its set. Corresponds to the term ids\n /// used in the parser.\n id, \n /// @internal\n flags = 0) {\n this.name = name;\n this.props = props;\n this.id = id;\n this.flags = flags;\n }\n /// Define a node type.\n static define(spec) {\n let props = spec.props && spec.props.length ? Object.create(null) : noProps;\n let flags = (spec.top ? 1 /* NodeFlag.Top */ : 0) | (spec.skipped ? 2 /* NodeFlag.Skipped */ : 0) |\n (spec.error ? 4 /* NodeFlag.Error */ : 0) | (spec.name == null ? 8 /* NodeFlag.Anonymous */ : 0);\n let type = new NodeType(spec.name || \"\", props, spec.id, flags);\n if (spec.props)\n for (let src of spec.props) {\n if (!Array.isArray(src))\n src = src(type);\n if (src) {\n if (src[0].perNode)\n throw new RangeError(\"Can't store a per-node prop on a node type\");\n props[src[0].id] = src[1];\n }\n }\n return type;\n }\n /// Retrieves a node prop for this type. Will return `undefined` if\n /// the prop isn't present on this node.\n prop(prop) { return this.props[prop.id]; }\n /// True when this is the top node of a grammar.\n get isTop() { return (this.flags & 1 /* NodeFlag.Top */) > 0; }\n /// True when this node is produced by a skip rule.\n get isSkipped() { return (this.flags & 2 /* NodeFlag.Skipped */) > 0; }\n /// Indicates whether this is an error node.\n get isError() { return (this.flags & 4 /* NodeFlag.Error */) > 0; }\n /// When true, this node type doesn't correspond to a user-declared\n /// named node, for example because it is used to cache repetition.\n get isAnonymous() { return (this.flags & 8 /* NodeFlag.Anonymous */) > 0; }\n /// Returns true when this node's name or one of its\n /// [groups](#common.NodeProp^group) matches the given string.\n is(name) {\n if (typeof name == 'string') {\n if (this.name == name)\n return true;\n let group = this.prop(NodeProp.group);\n return group ? group.indexOf(name) > -1 : false;\n }\n return this.id == name;\n }\n /// Create a function from node types to arbitrary values by\n /// specifying an object whose property names are node or\n /// [group](#common.NodeProp^group) names. Often useful with\n /// [`NodeProp.add`](#common.NodeProp.add). You can put multiple\n /// names, separated by spaces, in a single property name to map\n /// multiple node names to a single value.\n static match(map) {\n let direct = Object.create(null);\n for (let prop in map)\n for (let name of prop.split(\" \"))\n direct[name] = map[prop];\n return (node) => {\n for (let groups = node.prop(NodeProp.group), i = -1; i < (groups ? groups.length : 0); i++) {\n let found = direct[i < 0 ? node.name : groups[i]];\n if (found)\n return found;\n }\n };\n }\n}\n/// An empty dummy node type to use when no actual type is available.\nNodeType.none = new NodeType(\"\", Object.create(null), 0, 8 /* NodeFlag.Anonymous */);\n/// A node set holds a collection of node types. It is used to\n/// compactly represent trees by storing their type ids, rather than a\n/// full pointer to the type object, in a numeric array. Each parser\n/// [has](#lr.LRParser.nodeSet) a node set, and [tree\n/// buffers](#common.TreeBuffer) can only store collections of nodes\n/// from the same set. A set can have a maximum of 2**16 (65536) node\n/// types in it, so that the ids fit into 16-bit typed array slots.\nclass NodeSet {\n /// Create a set with the given types. The `id` property of each\n /// type should correspond to its position within the array.\n constructor(\n /// The node types in this set, by id.\n types) {\n this.types = types;\n for (let i = 0; i < types.length; i++)\n if (types[i].id != i)\n throw new RangeError(\"Node type ids should correspond to array positions when creating a node set\");\n }\n /// Create a copy of this set with some node properties added. The\n /// arguments to this method can be created with\n /// [`NodeProp.add`](#common.NodeProp.add).\n extend(...props) {\n let newTypes = [];\n for (let type of this.types) {\n let newProps = null;\n for (let source of props) {\n let add = source(type);\n if (add) {\n if (!newProps)\n newProps = Object.assign({}, type.props);\n newProps[add[0].id] = add[1];\n }\n }\n newTypes.push(newProps ? new NodeType(type.name, newProps, type.id, type.flags) : type);\n }\n return new NodeSet(newTypes);\n }\n}\nconst CachedNode = new WeakMap(), CachedInnerNode = new WeakMap();\n/// Options that control iteration. Can be combined with the `|`\n/// operator to enable multiple ones.\nvar IterMode;\n(function (IterMode) {\n /// When enabled, iteration will only visit [`Tree`](#common.Tree)\n /// objects, not nodes packed into\n /// [`TreeBuffer`](#common.TreeBuffer)s.\n IterMode[IterMode[\"ExcludeBuffers\"] = 1] = \"ExcludeBuffers\";\n /// Enable this to make iteration include anonymous nodes (such as\n /// the nodes that wrap repeated grammar constructs into a balanced\n /// tree).\n IterMode[IterMode[\"IncludeAnonymous\"] = 2] = \"IncludeAnonymous\";\n /// By default, regular [mounted](#common.NodeProp^mounted) nodes\n /// replace their base node in iteration. Enable this to ignore them\n /// instead.\n IterMode[IterMode[\"IgnoreMounts\"] = 4] = \"IgnoreMounts\";\n /// This option only applies in\n /// [`enter`](#common.SyntaxNode.enter)-style methods. It tells the\n /// library to not enter mounted overlays if one covers the given\n /// position.\n IterMode[IterMode[\"IgnoreOverlays\"] = 8] = \"IgnoreOverlays\";\n})(IterMode || (IterMode = {}));\n/// A piece of syntax tree. There are two ways to approach these\n/// trees: the way they are actually stored in memory, and the\n/// convenient way.\n///\n/// Syntax trees are stored as a tree of `Tree` and `TreeBuffer`\n/// objects. By packing detail information into `TreeBuffer` leaf\n/// nodes, the representation is made a lot more memory-efficient.\n///\n/// However, when you want to actually work with tree nodes, this\n/// representation is very awkward, so most client code will want to\n/// use the [`TreeCursor`](#common.TreeCursor) or\n/// [`SyntaxNode`](#common.SyntaxNode) interface instead, which provides\n/// a view on some part of this data structure, and can be used to\n/// move around to adjacent nodes.\nclass Tree {\n /// Construct a new tree. See also [`Tree.build`](#common.Tree^build).\n constructor(\n /// The type of the top node.\n type, \n /// This node's child nodes.\n children, \n /// The positions (offsets relative to the start of this tree) of\n /// the children.\n positions, \n /// The total length of this tree\n length, \n /// Per-node [node props](#common.NodeProp) to associate with this node.\n props) {\n this.type = type;\n this.children = children;\n this.positions = positions;\n this.length = length;\n /// @internal\n this.props = null;\n if (props && props.length) {\n this.props = Object.create(null);\n for (let [prop, value] of props)\n this.props[typeof prop == \"number\" ? prop : prop.id] = value;\n }\n }\n /// @internal\n toString() {\n let mounted = this.prop(NodeProp.mounted);\n if (mounted && !mounted.overlay)\n return mounted.tree.toString();\n let children = \"\";\n for (let ch of this.children) {\n let str = ch.toString();\n if (str) {\n if (children)\n children += \",\";\n children += str;\n }\n }\n return !this.type.name ? children :\n (/\\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) +\n (children.length ? \"(\" + children + \")\" : \"\");\n }\n /// Get a [tree cursor](#common.TreeCursor) positioned at the top of\n /// the tree. Mode can be used to [control](#common.IterMode) which\n /// nodes the cursor visits.\n cursor(mode = 0) {\n return new TreeCursor(this.topNode, mode);\n }\n /// Get a [tree cursor](#common.TreeCursor) pointing into this tree\n /// at the given position and side (see\n /// [`moveTo`](#common.TreeCursor.moveTo).\n cursorAt(pos, side = 0, mode = 0) {\n let scope = CachedNode.get(this) || this.topNode;\n let cursor = new TreeCursor(scope);\n cursor.moveTo(pos, side);\n CachedNode.set(this, cursor._tree);\n return cursor;\n }\n /// Get a [syntax node](#common.SyntaxNode) object for the top of the\n /// tree.\n get topNode() {\n return new TreeNode(this, 0, 0, null);\n }\n /// Get the [syntax node](#common.SyntaxNode) at the given position.\n /// If `side` is -1, this will move into nodes that end at the\n /// position. If 1, it'll move into nodes that start at the\n /// position. With 0, it'll only enter nodes that cover the position\n /// from both sides.\n ///\n /// Note that this will not enter\n /// [overlays](#common.MountedTree.overlay), and you often want\n /// [`resolveInner`](#common.Tree.resolveInner) instead.\n resolve(pos, side = 0) {\n let node = resolveNode(CachedNode.get(this) || this.topNode, pos, side, false);\n CachedNode.set(this, node);\n return node;\n }\n /// Like [`resolve`](#common.Tree.resolve), but will enter\n /// [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node\n /// pointing into the innermost overlaid tree at the given position\n /// (with parent links going through all parent structure, including\n /// the host trees).\n resolveInner(pos, side = 0) {\n let node = resolveNode(CachedInnerNode.get(this) || this.topNode, pos, side, true);\n CachedInnerNode.set(this, node);\n return node;\n }\n /// Iterate over the tree and its children, calling `enter` for any\n /// node that touches the `from`/`to` region (if given) before\n /// running over such a node's children, and `leave` (if given) when\n /// leaving the node. When `enter` returns `false`, that node will\n /// not have its children iterated over (or `leave` called).\n iterate(spec) {\n let { enter, leave, from = 0, to = this.length } = spec;\n let mode = spec.mode || 0, anon = (mode & IterMode.IncludeAnonymous) > 0;\n for (let c = this.cursor(mode | IterMode.IncludeAnonymous);;) {\n let entered = false;\n if (c.from <= to && c.to >= from && (!anon && c.type.isAnonymous || enter(c) !== false)) {\n if (c.firstChild())\n continue;\n entered = true;\n }\n for (;;) {\n if (entered && leave && (anon || !c.type.isAnonymous))\n leave(c);\n if (c.nextSibling())\n break;\n if (!c.parent())\n return;\n entered = true;\n }\n }\n }\n /// Get the value of the given [node prop](#common.NodeProp) for this\n /// node. Works with both per-node and per-type props.\n prop(prop) {\n return !prop.perNode ? this.type.prop(prop) : this.props ? this.props[prop.id] : undefined;\n }\n /// Returns the node's [per-node props](#common.NodeProp.perNode) in a\n /// format that can be passed to the [`Tree`](#common.Tree)\n /// constructor.\n get propValues() {\n let result = [];\n if (this.props)\n for (let id in this.props)\n result.push([+id, this.props[id]]);\n return result;\n }\n /// Balance the direct children of this tree, producing a copy of\n /// which may have children grouped into subtrees with type\n /// [`NodeType.none`](#common.NodeType^none).\n balance(config = {}) {\n return this.children.length <= 8 /* Balance.BranchFactor */ ? this :\n balanceRange(NodeType.none, this.children, this.positions, 0, this.children.length, 0, this.length, (children, positions, length) => new Tree(this.type, children, positions, length, this.propValues), config.makeTree || ((children, positions, length) => new Tree(NodeType.none, children, positions, length)));\n }\n /// Build a tree from a postfix-ordered buffer of node information,\n /// or a cursor over such a buffer.\n static build(data) { return buildTree(data); }\n}\n/// The empty tree\nTree.empty = new Tree(NodeType.none, [], [], 0);\nclass FlatBufferCursor {\n constructor(buffer, index) {\n this.buffer = buffer;\n this.index = index;\n }\n get id() { return this.buffer[this.index - 4]; }\n get start() { return this.buffer[this.index - 3]; }\n get end() { return this.buffer[this.index - 2]; }\n get size() { return this.buffer[this.index - 1]; }\n get pos() { return this.index; }\n next() { this.index -= 4; }\n fork() { return new FlatBufferCursor(this.buffer, this.index); }\n}\n/// Tree buffers contain (type, start, end, endIndex) quads for each\n/// node. In such a buffer, nodes are stored in prefix order (parents\n/// before children, with the endIndex of the parent indicating which\n/// children belong to it).\nclass TreeBuffer {\n /// Create a tree buffer.\n constructor(\n /// The buffer's content.\n buffer, \n /// The total length of the group of nodes in the buffer.\n length, \n /// The node set used in this buffer.\n set) {\n this.buffer = buffer;\n this.length = length;\n this.set = set;\n }\n /// @internal\n get type() { return NodeType.none; }\n /// @internal\n toString() {\n let result = [];\n for (let index = 0; index < this.buffer.length;) {\n result.push(this.childString(index));\n index = this.buffer[index + 3];\n }\n return result.join(\",\");\n }\n /// @internal\n childString(index) {\n let id = this.buffer[index], endIndex = this.buffer[index + 3];\n let type = this.set.types[id], result = type.name;\n if (/\\W/.test(result) && !type.isError)\n result = JSON.stringify(result);\n index += 4;\n if (endIndex == index)\n return result;\n let children = [];\n while (index < endIndex) {\n children.push(this.childString(index));\n index = this.buffer[index + 3];\n }\n return result + \"(\" + children.join(\",\") + \")\";\n }\n /// @internal\n findChild(startIndex, endIndex, dir, pos, side) {\n let { buffer } = this, pick = -1;\n for (let i = startIndex; i != endIndex; i = buffer[i + 3]) {\n if (checkSide(side, pos, buffer[i + 1], buffer[i + 2])) {\n pick = i;\n if (dir > 0)\n break;\n }\n }\n return pick;\n }\n /// @internal\n slice(startI, endI, from) {\n let b = this.buffer;\n let copy = new Uint16Array(endI - startI), len = 0;\n for (let i = startI, j = 0; i < endI;) {\n copy[j++] = b[i++];\n copy[j++] = b[i++] - from;\n let to = copy[j++] = b[i++] - from;\n copy[j++] = b[i++] - startI;\n len = Math.max(len, to);\n }\n return new TreeBuffer(copy, len, this.set);\n }\n}\nfunction checkSide(side, pos, from, to) {\n switch (side) {\n case -2 /* Side.Before */: return from < pos;\n case -1 /* Side.AtOrBefore */: return to >= pos && from < pos;\n case 0 /* Side.Around */: return from < pos && to > pos;\n case 1 /* Side.AtOrAfter */: return from <= pos && to > pos;\n case 2 /* Side.After */: return to > pos;\n case 4 /* Side.DontCare */: return true;\n }\n}\nfunction enterUnfinishedNodesBefore(node, pos) {\n let scan = node.childBefore(pos);\n while (scan) {\n let last = scan.lastChild;\n if (!last || last.to != scan.to)\n break;\n if (last.type.isError && last.from == last.to) {\n node = scan;\n scan = last.prevSibling;\n }\n else {\n scan = last;\n }\n }\n return node;\n}\nfunction resolveNode(node, pos, side, overlays) {\n var _a;\n // Move up to a node that actually holds the position, if possible\n while (node.from == node.to ||\n (side < 1 ? node.from >= pos : node.from > pos) ||\n (side > -1 ? node.to <= pos : node.to < pos)) {\n let parent = !overlays && node instanceof TreeNode && node.index < 0 ? null : node.parent;\n if (!parent)\n return node;\n node = parent;\n }\n let mode = overlays ? 0 : IterMode.IgnoreOverlays;\n // Must go up out of overlays when those do not overlap with pos\n if (overlays)\n for (let scan = node, parent = scan.parent; parent; scan = parent, parent = scan.parent) {\n if (scan instanceof TreeNode && scan.index < 0 && ((_a = parent.enter(pos, side, mode)) === null || _a === void 0 ? void 0 : _a.from) != scan.from)\n node = parent;\n }\n for (;;) {\n let inner = node.enter(pos, side, mode);\n if (!inner)\n return node;\n node = inner;\n }\n}\nclass TreeNode {\n constructor(_tree, from, \n // Index in parent node, set to -1 if the node is not a direct child of _parent.node (overlay)\n index, _parent) {\n this._tree = _tree;\n this.from = from;\n this.index = index;\n this._parent = _parent;\n }\n get type() { return this._tree.type; }\n get name() { return this._tree.type.name; }\n get to() { return this.from + this._tree.length; }\n nextChild(i, dir, pos, side, mode = 0) {\n for (let parent = this;;) {\n for (let { children, positions } = parent._tree, e = dir > 0 ? children.length : -1; i != e; i += dir) {\n let next = children[i], start = positions[i] + parent.from;\n if (!checkSide(side, pos, start, start + next.length))\n continue;\n if (next instanceof TreeBuffer) {\n if (mode & IterMode.ExcludeBuffers)\n continue;\n let index = next.findChild(0, next.buffer.length, dir, pos - start, side);\n if (index > -1)\n return new BufferNode(new BufferContext(parent, next, i, start), null, index);\n }\n else if ((mode & IterMode.IncludeAnonymous) || (!next.type.isAnonymous || hasChild(next))) {\n let mounted;\n if (!(mode & IterMode.IgnoreMounts) &&\n next.props && (mounted = next.prop(NodeProp.mounted)) && !mounted.overlay)\n return new TreeNode(mounted.tree, start, i, parent);\n let inner = new TreeNode(next, start, i, parent);\n return (mode & IterMode.IncludeAnonymous) || !inner.type.isAnonymous ? inner\n : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side);\n }\n }\n if ((mode & IterMode.IncludeAnonymous) || !parent.type.isAnonymous)\n return null;\n if (parent.index >= 0)\n i = parent.index + dir;\n else\n i = dir < 0 ? -1 : parent._parent._tree.children.length;\n parent = parent._parent;\n if (!parent)\n return null;\n }\n }\n get firstChild() { return this.nextChild(0, 1, 0, 4 /* Side.DontCare */); }\n get lastChild() { return this.nextChild(this._tree.children.length - 1, -1, 0, 4 /* Side.DontCare */); }\n childAfter(pos) { return this.nextChild(0, 1, pos, 2 /* Side.After */); }\n childBefore(pos) { return this.nextChild(this._tree.children.length - 1, -1, pos, -2 /* Side.Before */); }\n enter(pos, side, mode = 0) {\n let mounted;\n if (!(mode & IterMode.IgnoreOverlays) && (mounted = this._tree.prop(NodeProp.mounted)) && mounted.overlay) {\n let rPos = pos - this.from;\n for (let { from, to } of mounted.overlay) {\n if ((side > 0 ? from <= rPos : from < rPos) &&\n (side < 0 ? to >= rPos : to > rPos))\n return new TreeNode(mounted.tree, mounted.overlay[0].from + this.from, -1, this);\n }\n }\n return this.nextChild(0, 1, pos, side, mode);\n }\n nextSignificantParent() {\n let val = this;\n while (val.type.isAnonymous && val._parent)\n val = val._parent;\n return val;\n }\n get parent() {\n return this._parent ? this._parent.nextSignificantParent() : null;\n }\n get nextSibling() {\n return this._parent && this.index >= 0 ? this._parent.nextChild(this.index + 1, 1, 0, 4 /* Side.DontCare */) : null;\n }\n get prevSibling() {\n return this._parent && this.index >= 0 ? this._parent.nextChild(this.index - 1, -1, 0, 4 /* Side.DontCare */) : null;\n }\n cursor(mode = 0) { return new TreeCursor(this, mode); }\n get tree() { return this._tree; }\n toTree() { return this._tree; }\n resolve(pos, side = 0) {\n return resolveNode(this, pos, side, false);\n }\n resolveInner(pos, side = 0) {\n return resolveNode(this, pos, side, true);\n }\n enterUnfinishedNodesBefore(pos) { return enterUnfinishedNodesBefore(this, pos); }\n getChild(type, before = null, after = null) {\n let r = getChildren(this, type, before, after);\n return r.length ? r[0] : null;\n }\n getChildren(type, before = null, after = null) {\n return getChildren(this, type, before, after);\n }\n /// @internal\n toString() { return this._tree.toString(); }\n get node() { return this; }\n matchContext(context) { return matchNodeContext(this, context); }\n}\nfunction getChildren(node, type, before, after) {\n let cur = node.cursor(), result = [];\n if (!cur.firstChild())\n return result;\n if (before != null)\n while (!cur.type.is(before))\n if (!cur.nextSibling())\n return result;\n for (;;) {\n if (after != null && cur.type.is(after))\n return result;\n if (cur.type.is(type))\n result.push(cur.node);\n if (!cur.nextSibling())\n return after == null ? result : [];\n }\n}\nfunction matchNodeContext(node, context, i = context.length - 1) {\n for (let p = node.parent; i >= 0; p = p.parent) {\n if (!p)\n return false;\n if (!p.type.isAnonymous) {\n if (context[i] && context[i] != p.name)\n return false;\n i--;\n }\n }\n return true;\n}\nclass BufferContext {\n constructor(parent, buffer, index, start) {\n this.parent = parent;\n this.buffer = buffer;\n this.index = index;\n this.start = start;\n }\n}\nclass BufferNode {\n get name() { return this.type.name; }\n get from() { return this.context.start + this.context.buffer.buffer[this.index + 1]; }\n get to() { return this.context.start + this.context.buffer.buffer[this.index + 2]; }\n constructor(context, _parent, index) {\n this.context = context;\n this._parent = _parent;\n this.index = index;\n this.type = context.buffer.set.types[context.buffer.buffer[index]];\n }\n child(dir, pos, side) {\n let { buffer } = this.context;\n let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side);\n return index < 0 ? null : new BufferNode(this.context, this, index);\n }\n get firstChild() { return this.child(1, 0, 4 /* Side.DontCare */); }\n get lastChild() { return this.child(-1, 0, 4 /* Side.DontCare */); }\n childAfter(pos) { return this.child(1, pos, 2 /* Side.After */); }\n childBefore(pos) { return this.child(-1, pos, -2 /* Side.Before */); }\n enter(pos, side, mode = 0) {\n if (mode & IterMode.ExcludeBuffers)\n return null;\n let { buffer } = this.context;\n let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side);\n return index < 0 ? null : new BufferNode(this.context, this, index);\n }\n get parent() {\n return this._parent || this.context.parent.nextSignificantParent();\n }\n externalSibling(dir) {\n return this._parent ? null : this.context.parent.nextChild(this.context.index + dir, dir, 0, 4 /* Side.DontCare */);\n }\n get nextSibling() {\n let { buffer } = this.context;\n let after = buffer.buffer[this.index + 3];\n if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length))\n return new BufferNode(this.context, this._parent, after);\n return this.externalSibling(1);\n }\n get prevSibling() {\n let { buffer } = this.context;\n let parentStart = this._parent ? this._parent.index + 4 : 0;\n if (this.index == parentStart)\n return this.externalSibling(-1);\n return new BufferNode(this.context, this._parent, buffer.findChild(parentStart, this.index, -1, 0, 4 /* Side.DontCare */));\n }\n cursor(mode = 0) { return new TreeCursor(this, mode); }\n get tree() { return null; }\n toTree() {\n let children = [], positions = [];\n let { buffer } = this.context;\n let startI = this.index + 4, endI = buffer.buffer[this.index + 3];\n if (endI > startI) {\n let from = buffer.buffer[this.index + 1];\n children.push(buffer.slice(startI, endI, from));\n positions.push(0);\n }\n return new Tree(this.type, children, positions, this.to - this.from);\n }\n resolve(pos, side = 0) {\n return resolveNode(this, pos, side, false);\n }\n resolveInner(pos, side = 0) {\n return resolveNode(this, pos, side, true);\n }\n enterUnfinishedNodesBefore(pos) { return enterUnfinishedNodesBefore(this, pos); }\n /// @internal\n toString() { return this.context.buffer.childString(this.index); }\n getChild(type, before = null, after = null) {\n let r = getChildren(this, type, before, after);\n return r.length ? r[0] : null;\n }\n getChildren(type, before = null, after = null) {\n return getChildren(this, type, before, after);\n }\n get node() { return this; }\n matchContext(context) { return matchNodeContext(this, context); }\n}\n/// A tree cursor object focuses on a given node in a syntax tree, and\n/// allows you to move to adjacent nodes.\nclass TreeCursor {\n /// Shorthand for `.type.name`.\n get name() { return this.type.name; }\n /// @internal\n constructor(node, \n /// @internal\n mode = 0) {\n this.mode = mode;\n /// @internal\n this.buffer = null;\n this.stack = [];\n /// @internal\n this.index = 0;\n this.bufferNode = null;\n if (node instanceof TreeNode) {\n this.yieldNode(node);\n }\n else {\n this._tree = node.context.parent;\n this.buffer = node.context;\n for (let n = node._parent; n; n = n._parent)\n this.stack.unshift(n.index);\n this.bufferNode = node;\n this.yieldBuf(node.index);\n }\n }\n yieldNode(node) {\n if (!node)\n return false;\n this._tree = node;\n this.type = node.type;\n this.from = node.from;\n this.to = node.to;\n return true;\n }\n yieldBuf(index, type) {\n this.index = index;\n let { start, buffer } = this.buffer;\n this.type = type || buffer.set.types[buffer.buffer[index]];\n this.from = start + buffer.buffer[index + 1];\n this.to = start + buffer.buffer[index + 2];\n return true;\n }\n yield(node) {\n if (!node)\n return false;\n if (node instanceof TreeNode) {\n this.buffer = null;\n return this.yieldNode(node);\n }\n this.buffer = node.context;\n return this.yieldBuf(node.index, node.type);\n }\n /// @internal\n toString() {\n return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString();\n }\n /// @internal\n enterChild(dir, pos, side) {\n if (!this.buffer)\n return this.yield(this._tree.nextChild(dir < 0 ? this._tree._tree.children.length - 1 : 0, dir, pos, side, this.mode));\n let { buffer } = this.buffer;\n let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side);\n if (index < 0)\n return false;\n this.stack.push(this.index);\n return this.yieldBuf(index);\n }\n /// Move the cursor to this node's first child. When this returns\n /// false, the node has no child, and the cursor has not been moved.\n firstChild() { return this.enterChild(1, 0, 4 /* Side.DontCare */); }\n /// Move the cursor to this node's last child.\n lastChild() { return this.enterChild(-1, 0, 4 /* Side.DontCare */); }\n /// Move the cursor to the first child that ends after `pos`.\n childAfter(pos) { return this.enterChild(1, pos, 2 /* Side.After */); }\n /// Move to the last child that starts before `pos`.\n childBefore(pos) { return this.enterChild(-1, pos, -2 /* Side.Before */); }\n /// Move the cursor to the child around `pos`. If side is -1 the\n /// child may end at that position, when 1 it may start there. This\n /// will also enter [overlaid](#common.MountedTree.overlay)\n /// [mounted](#common.NodeProp^mounted) trees unless `overlays` is\n /// set to false.\n enter(pos, side, mode = this.mode) {\n if (!this.buffer)\n return this.yield(this._tree.enter(pos, side, mode));\n return mode & IterMode.ExcludeBuffers ? false : this.enterChild(1, pos, side);\n }\n /// Move to the node's parent node, if this isn't the top node.\n parent() {\n if (!this.buffer)\n return this.yieldNode((this.mode & IterMode.IncludeAnonymous) ? this._tree._parent : this._tree.parent);\n if (this.stack.length)\n return this.yieldBuf(this.stack.pop());\n let parent = (this.mode & IterMode.IncludeAnonymous) ? this.buffer.parent : this.buffer.parent.nextSignificantParent();\n this.buffer = null;\n return this.yieldNode(parent);\n }\n /// @internal\n sibling(dir) {\n if (!this.buffer)\n return !this._tree._parent ? false\n : this.yield(this._tree.index < 0 ? null\n : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4 /* Side.DontCare */, this.mode));\n let { buffer } = this.buffer, d = this.stack.length - 1;\n if (dir < 0) {\n let parentStart = d < 0 ? 0 : this.stack[d] + 4;\n if (this.index != parentStart)\n return this.yieldBuf(buffer.findChild(parentStart, this.index, -1, 0, 4 /* Side.DontCare */));\n }\n else {\n let after = buffer.buffer[this.index + 3];\n if (after < (d < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d] + 3]))\n return this.yieldBuf(after);\n }\n return d < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4 /* Side.DontCare */, this.mode)) : false;\n }\n /// Move to this node's next sibling, if any.\n nextSibling() { return this.sibling(1); }\n /// Move to this node's previous sibling, if any.\n prevSibling() { return this.sibling(-1); }\n atLastNode(dir) {\n let index, parent, { buffer } = this;\n if (buffer) {\n if (dir > 0) {\n if (this.index < buffer.buffer.buffer.length)\n return false;\n }\n else {\n for (let i = 0; i < this.index; i++)\n if (buffer.buffer.buffer[i + 3] < this.index)\n return false;\n }\n ({ index, parent } = buffer);\n }\n else {\n ({ index, _parent: parent } = this._tree);\n }\n for (; parent; { index, _parent: parent } = parent) {\n if (index > -1)\n for (let i = index + dir, e = dir < 0 ? -1 : parent._tree.children.length; i != e; i += dir) {\n let child = parent._tree.children[i];\n if ((this.mode & IterMode.IncludeAnonymous) ||\n child instanceof TreeBuffer ||\n !child.type.isAnonymous ||\n hasChild(child))\n return false;\n }\n }\n return true;\n }\n move(dir, enter) {\n if (enter && this.enterChild(dir, 0, 4 /* Side.DontCare */))\n return true;\n for (;;) {\n if (this.sibling(dir))\n return true;\n if (this.atLastNode(dir) || !this.parent())\n return false;\n }\n }\n /// Move to the next node in a\n /// [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR)\n /// traversal, going from a node to its first child or, if the\n /// current node is empty or `enter` is false, its next sibling or\n /// the next sibling of the first parent node that has one.\n next(enter = true) { return this.move(1, enter); }\n /// Move to the next node in a last-to-first pre-order traveral. A\n /// node is followed by its last child or, if it has none, its\n /// previous sibling or the previous sibling of the first parent\n /// node that has one.\n prev(enter = true) { return this.move(-1, enter); }\n /// Move the cursor to the innermost node that covers `pos`. If\n /// `side` is -1, it will enter nodes that end at `pos`. If it is 1,\n /// it will enter nodes that start at `pos`.\n moveTo(pos, side = 0) {\n // Move up to a node that actually holds the position, if possible\n while (this.from == this.to ||\n (side < 1 ? this.from >= pos : this.from > pos) ||\n (side > -1 ? this.to <= pos : this.to < pos))\n if (!this.parent())\n break;\n // Then scan down into child nodes as far as possible\n while (this.enterChild(1, pos, side)) { }\n return this;\n }\n /// Get a [syntax node](#common.SyntaxNode) at the cursor's current\n /// position.\n get node() {\n if (!this.buffer)\n return this._tree;\n let cache = this.bufferNode, result = null, depth = 0;\n if (cache && cache.context == this.buffer) {\n scan: for (let index = this.index, d = this.stack.length; d >= 0;) {\n for (let c = cache; c; c = c._parent)\n if (c.index == index) {\n if (index == this.index)\n return c;\n result = c;\n depth = d + 1;\n break scan;\n }\n index = this.stack[--d];\n }\n }\n for (let i = depth; i < this.stack.length; i++)\n result = new BufferNode(this.buffer, result, this.stack[i]);\n return this.bufferNode = new BufferNode(this.buffer, result, this.index);\n }\n /// Get the [tree](#common.Tree) that represents the current node, if\n /// any. Will return null when the node is in a [tree\n /// buffer](#common.TreeBuffer).\n get tree() {\n return this.buffer ? null : this._tree._tree;\n }\n /// Iterate over the current node and all its descendants, calling\n /// `enter` when entering a node and `leave`, if given, when leaving\n /// one. When `enter` returns `false`, any children of that node are\n /// skipped, and `leave` isn't called for it.\n iterate(enter, leave) {\n for (let depth = 0;;) {\n let mustLeave = false;\n if (this.type.isAnonymous || enter(this) !== false) {\n if (this.firstChild()) {\n depth++;\n continue;\n }\n if (!this.type.isAnonymous)\n mustLeave = true;\n }\n for (;;) {\n if (mustLeave && leave)\n leave(this);\n mustLeave = this.type.isAnonymous;\n if (this.nextSibling())\n break;\n if (!depth)\n return;\n this.parent();\n depth--;\n mustLeave = true;\n }\n }\n }\n /// Test whether the current node matches a given context\u2014a sequence\n /// of direct parent node names. Empty strings in the context array\n /// are treated as wildcards.\n matchContext(context) {\n if (!this.buffer)\n return matchNodeContext(this.node, context);\n let { buffer } = this.buffer, { types } = buffer.set;\n for (let i = context.length - 1, d = this.stack.length - 1; i >= 0; d--) {\n if (d < 0)\n return matchNodeContext(this.node, context, i);\n let type = types[buffer.buffer[this.stack[d]]];\n if (!type.isAnonymous) {\n if (context[i] && context[i] != type.name)\n return false;\n i--;\n }\n }\n return true;\n }\n}\nfunction hasChild(tree) {\n return tree.children.some(ch => ch instanceof TreeBuffer || !ch.type.isAnonymous || hasChild(ch));\n}\nfunction buildTree(data) {\n var _a;\n let { buffer, nodeSet, maxBufferLength = DefaultBufferLength, reused = [], minRepeatType = nodeSet.types.length } = data;\n let cursor = Array.isArray(buffer) ? new FlatBufferCursor(buffer, buffer.length) : buffer;\n let types = nodeSet.types;\n let contextHash = 0, lookAhead = 0;\n function takeNode(parentStart, minPos, children, positions, inRepeat) {\n let { id, start, end, size } = cursor;\n let lookAheadAtStart = lookAhead;\n while (size < 0) {\n cursor.next();\n if (size == -1 /* SpecialRecord.Reuse */) {\n let node = reused[id];\n children.push(node);\n positions.push(start - parentStart);\n return;\n }\n else if (size == -3 /* SpecialRecord.ContextChange */) { // Context change\n contextHash = id;\n return;\n }\n else if (size == -4 /* SpecialRecord.LookAhead */) {\n lookAhead = id;\n return;\n }\n else {\n throw new RangeError(`Unrecognized record size: ${size}`);\n }\n }\n let type = types[id], node, buffer;\n let startPos = start - parentStart;\n if (end - start <= maxBufferLength && (buffer = findBufferSize(cursor.pos - minPos, inRepeat))) {\n // Small enough for a buffer, and no reused nodes inside\n let data = new Uint16Array(buffer.size - buffer.skip);\n let endPos = cursor.pos - buffer.size, index = data.length;\n while (cursor.pos > endPos)\n index = copyToBuffer(buffer.start, data, index);\n node = new TreeBuffer(data, end - buffer.start, nodeSet);\n startPos = buffer.start - parentStart;\n }\n else { // Make it a node\n let endPos = cursor.pos - size;\n cursor.next();\n let localChildren = [], localPositions = [];\n let localInRepeat = id >= minRepeatType ? id : -1;\n let lastGroup = 0, lastEnd = end;\n while (cursor.pos > endPos) {\n if (localInRepeat >= 0 && cursor.id == localInRepeat && cursor.size >= 0) {\n if (cursor.end <= lastEnd - maxBufferLength) {\n makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor.end, lastEnd, localInRepeat, lookAheadAtStart);\n lastGroup = localChildren.length;\n lastEnd = cursor.end;\n }\n cursor.next();\n }\n else {\n takeNode(start, endPos, localChildren, localPositions, localInRepeat);\n }\n }\n if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length)\n makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart);\n localChildren.reverse();\n localPositions.reverse();\n if (localInRepeat > -1 && lastGroup > 0) {\n let make = makeBalanced(type);\n node = balanceRange(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make);\n }\n else {\n node = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end);\n }\n }\n children.push(node);\n positions.push(startPos);\n }\n function makeBalanced(type) {\n return (children, positions, length) => {\n let lookAhead = 0, lastI = children.length - 1, last, lookAheadProp;\n if (lastI >= 0 && (last = children[lastI]) instanceof Tree) {\n if (!lastI && last.type == type && last.length == length)\n return last;\n if (lookAheadProp = last.prop(NodeProp.lookAhead))\n lookAhead = positions[lastI] + last.length + lookAheadProp;\n }\n return makeTree(type, children, positions, length, lookAhead);\n };\n }\n function makeRepeatLeaf(children, positions, base, i, from, to, type, lookAhead) {\n let localChildren = [], localPositions = [];\n while (children.length > i) {\n localChildren.push(children.pop());\n localPositions.push(positions.pop() + base - from);\n }\n children.push(makeTree(nodeSet.types[type], localChildren, localPositions, to - from, lookAhead - to));\n positions.push(from - base);\n }\n function makeTree(type, children, positions, length, lookAhead = 0, props) {\n if (contextHash) {\n let pair = [NodeProp.contextHash, contextHash];\n props = props ? [pair].concat(props) : [pair];\n }\n if (lookAhead > 25) {\n let pair = [NodeProp.lookAhead, lookAhead];\n props = props ? [pair].concat(props) : [pair];\n }\n return new Tree(type, children, positions, length, props);\n }\n function findBufferSize(maxSize, inRepeat) {\n // Scan through the buffer to find previous siblings that fit\n // together in a TreeBuffer, and don't contain any reused nodes\n // (which can't be stored in a buffer).\n // If `inRepeat` is > -1, ignore node boundaries of that type for\n // nesting, but make sure the end falls either at the start\n // (`maxSize`) or before such a node.\n let fork = cursor.fork();\n let size = 0, start = 0, skip = 0, minStart = fork.end - maxBufferLength;\n let result = { size: 0, start: 0, skip: 0 };\n scan: for (let minPos = fork.pos - maxSize; fork.pos > minPos;) {\n let nodeSize = fork.size;\n // Pretend nested repeat nodes of the same type don't exist\n if (fork.id == inRepeat && nodeSize >= 0) {\n // Except that we store the current state as a valid return\n // value.\n result.size = size;\n result.start = start;\n result.skip = skip;\n skip += 4;\n size += 4;\n fork.next();\n continue;\n }\n let startPos = fork.pos - nodeSize;\n if (nodeSize < 0 || startPos < minPos || fork.start < minStart)\n break;\n let localSkipped = fork.id >= minRepeatType ? 4 : 0;\n let nodeStart = fork.start;\n fork.next();\n while (fork.pos > startPos) {\n if (fork.size < 0) {\n if (fork.size == -3 /* SpecialRecord.ContextChange */)\n localSkipped += 4;\n else\n break scan;\n }\n else if (fork.id >= minRepeatType) {\n localSkipped += 4;\n }\n fork.next();\n }\n start = nodeStart;\n size += nodeSize;\n skip += localSkipped;\n }\n if (inRepeat < 0 || size == maxSize) {\n result.size = size;\n result.start = start;\n result.skip = skip;\n }\n return result.size > 4 ? result : undefined;\n }\n function copyToBuffer(bufferStart, buffer, index) {\n let { id, start, end, size } = cursor;\n cursor.next();\n if (size >= 0 && id < minRepeatType) {\n let startIndex = index;\n if (size > 4) {\n let endPos = cursor.pos - (size - 4);\n while (cursor.pos > endPos)\n index = copyToBuffer(bufferStart, buffer, index);\n }\n buffer[--index] = startIndex;\n buffer[--index] = end - bufferStart;\n buffer[--index] = start - bufferStart;\n buffer[--index] = id;\n }\n else if (size == -3 /* SpecialRecord.ContextChange */) {\n contextHash = id;\n }\n else if (size == -4 /* SpecialRecord.LookAhead */) {\n lookAhead = id;\n }\n return index;\n }\n let children = [], positions = [];\n while (cursor.pos > 0)\n takeNode(data.start || 0, data.bufferStart || 0, children, positions, -1);\n let length = (_a = data.length) !== null && _a !== void 0 ? _a : (children.length ? positions[0] + children[0].length : 0);\n return new Tree(types[data.topID], children.reverse(), positions.reverse(), length);\n}\nconst nodeSizeCache = new WeakMap;\nfunction nodeSize(balanceType, node) {\n if (!balanceType.isAnonymous || node instanceof TreeBuffer || node.type != balanceType)\n return 1;\n let size = nodeSizeCache.get(node);\n if (size == null) {\n size = 1;\n for (let child of node.children) {\n if (child.type != balanceType || !(child instanceof Tree)) {\n size = 1;\n break;\n }\n size += nodeSize(balanceType, child);\n }\n nodeSizeCache.set(node, size);\n }\n return size;\n}\nfunction balanceRange(\n// The type the balanced tree's inner nodes.\nbalanceType, \n// The direct children and their positions\nchildren, positions, \n// The index range in children/positions to use\nfrom, to, \n// The start position of the nodes, relative to their parent.\nstart, \n// Length of the outer node\nlength, \n// Function to build the top node of the balanced tree\nmkTop, \n// Function to build internal nodes for the balanced tree\nmkTree) {\n let total = 0;\n for (let i = from; i < to; i++)\n total += nodeSize(balanceType, children[i]);\n let maxChild = Math.ceil((total * 1.5) / 8 /* Balance.BranchFactor */);\n let localChildren = [], localPositions = [];\n function divide(children, positions, from, to, offset) {\n for (let i = from; i < to;) {\n let groupFrom = i, groupStart = positions[i], groupSize = nodeSize(balanceType, children[i]);\n i++;\n for (; i < to; i++) {\n let nextSize = nodeSize(balanceType, children[i]);\n if (groupSize + nextSize >= maxChild)\n break;\n groupSize += nextSize;\n }\n if (i == groupFrom + 1) {\n if (groupSize > maxChild) {\n let only = children[groupFrom]; // Only trees can have a size > 1\n divide(only.children, only.positions, 0, only.children.length, positions[groupFrom] + offset);\n continue;\n }\n localChildren.push(children[groupFrom]);\n }\n else {\n let length = positions[i - 1] + children[i - 1].length - groupStart;\n localChildren.push(balanceRange(balanceType, children, positions, groupFrom, i, groupStart, length, null, mkTree));\n }\n localPositions.push(groupStart + offset - start);\n }\n }\n divide(children, positions, from, to, 0);\n return (mkTop || mkTree)(localChildren, localPositions, length);\n}\n/// Provides a way to associate values with pieces of trees. As long\n/// as that part of the tree is reused, the associated values can be\n/// retrieved from an updated tree.\nclass NodeWeakMap {\n constructor() {\n this.map = new WeakMap();\n }\n setBuffer(buffer, index, value) {\n let inner = this.map.get(buffer);\n if (!inner)\n this.map.set(buffer, inner = new Map);\n inner.set(index, value);\n }\n getBuffer(buffer, index) {\n let inner = this.map.get(buffer);\n return inner && inner.get(index);\n }\n /// Set the value for this syntax node.\n set(node, value) {\n if (node instanceof BufferNode)\n this.setBuffer(node.context.buffer, node.index, value);\n else if (node instanceof TreeNode)\n this.map.set(node.tree, value);\n }\n /// Retrieve value for this syntax node, if it exists in the map.\n get(node) {\n return node instanceof BufferNode ? this.getBuffer(node.context.buffer, node.index)\n : node instanceof TreeNode ? this.map.get(node.tree) : undefined;\n }\n /// Set the value for the node that a cursor currently points to.\n cursorSet(cursor, value) {\n if (cursor.buffer)\n this.setBuffer(cursor.buffer.buffer, cursor.index, value);\n else\n this.map.set(cursor.tree, value);\n }\n /// Retrieve the value for the node that a cursor currently points\n /// to.\n cursorGet(cursor) {\n return cursor.buffer ? this.getBuffer(cursor.buffer.buffer, cursor.index) : this.map.get(cursor.tree);\n }\n}\n\n/// Tree fragments are used during [incremental\n/// parsing](#common.Parser.startParse) to track parts of old trees\n/// that can be reused in a new parse. An array of fragments is used\n/// to track regions of an old tree whose nodes might be reused in new\n/// parses. Use the static\n/// [`applyChanges`](#common.TreeFragment^applyChanges) method to\n/// update fragments for document changes.\nclass TreeFragment {\n /// Construct a tree fragment. You'll usually want to use\n /// [`addTree`](#common.TreeFragment^addTree) and\n /// [`applyChanges`](#common.TreeFragment^applyChanges) instead of\n /// calling this directly.\n constructor(\n /// The start of the unchanged range pointed to by this fragment.\n /// This refers to an offset in the _updated_ document (as opposed\n /// to the original tree).\n from, \n /// The end of the unchanged range.\n to, \n /// The tree that this fragment is based on.\n tree, \n /// The offset between the fragment's tree and the document that\n /// this fragment can be used against. Add this when going from\n /// document to tree positions, subtract it to go from tree to\n /// document positions.\n offset, openStart = false, openEnd = false) {\n this.from = from;\n this.to = to;\n this.tree = tree;\n this.offset = offset;\n this.open = (openStart ? 1 /* Open.Start */ : 0) | (openEnd ? 2 /* Open.End */ : 0);\n }\n /// Whether the start of the fragment represents the start of a\n /// parse, or the end of a change. (In the second case, it may not\n /// be safe to reuse some nodes at the start, depending on the\n /// parsing algorithm.)\n get openStart() { return (this.open & 1 /* Open.Start */) > 0; }\n /// Whether the end of the fragment represents the end of a\n /// full-document parse, or the start of a change.\n get openEnd() { return (this.open & 2 /* Open.End */) > 0; }\n /// Create a set of fragments from a freshly parsed tree, or update\n /// an existing set of fragments by replacing the ones that overlap\n /// with a tree with content from the new tree. When `partial` is\n /// true, the parse is treated as incomplete, and the resulting\n /// fragment has [`openEnd`](#common.TreeFragment.openEnd) set to\n /// true.\n static addTree(tree, fragments = [], partial = false) {\n let result = [new TreeFragment(0, tree.length, tree, 0, false, partial)];\n for (let f of fragments)\n if (f.to > tree.length)\n result.push(f);\n return result;\n }\n /// Apply a set of edits to an array of fragments, removing or\n /// splitting fragments as necessary to remove edited ranges, and\n /// adjusting offsets for fragments that moved.\n static applyChanges(fragments, changes, minGap = 128) {\n if (!changes.length)\n return fragments;\n let result = [];\n let fI = 1, nextF = fragments.length ? fragments[0] : null;\n for (let cI = 0, pos = 0, off = 0;; cI++) {\n let nextC = cI < changes.length ? changes[cI] : null;\n let nextPos = nextC ? nextC.fromA : 1e9;\n if (nextPos - pos >= minGap)\n while (nextF && nextF.from < nextPos) {\n let cut = nextF;\n if (pos >= cut.from || nextPos <= cut.to || off) {\n let fFrom = Math.max(cut.from, pos) - off, fTo = Math.min(cut.to, nextPos) - off;\n cut = fFrom >= fTo ? null : new TreeFragment(fFrom, fTo, cut.tree, cut.offset + off, cI > 0, !!nextC);\n }\n if (cut)\n result.push(cut);\n if (nextF.to > nextPos)\n break;\n nextF = fI < fragments.length ? fragments[fI++] : null;\n }\n if (!nextC)\n break;\n pos = nextC.toA;\n off = nextC.toA - nextC.toB;\n }\n return result;\n }\n}\n/// A superclass that parsers should extend.\nclass Parser {\n /// Start a parse, returning a [partial parse](#common.PartialParse)\n /// object. [`fragments`](#common.TreeFragment) can be passed in to\n /// make the parse incremental.\n ///\n /// By default, the entire input is parsed. You can pass `ranges`,\n /// which should be a sorted array of non-empty, non-overlapping\n /// ranges, to parse only those ranges. The tree returned in that\n /// case will start at `ranges[0].from`.\n startParse(input, fragments, ranges) {\n if (typeof input == \"string\")\n input = new StringInput(input);\n ranges = !ranges ? [new Range(0, input.length)] : ranges.length ? ranges.map(r => new Range(r.from, r.to)) : [new Range(0, 0)];\n return this.createParse(input, fragments || [], ranges);\n }\n /// Run a full parse, returning the resulting tree.\n parse(input, fragments, ranges) {\n let parse = this.startParse(input, fragments, ranges);\n for (;;) {\n let done = parse.advance();\n if (done)\n return done;\n }\n }\n}\nclass StringInput {\n constructor(string) {\n this.string = string;\n }\n get length() { return this.string.length; }\n chunk(from) { return this.string.slice(from); }\n get lineChunks() { return false; }\n read(from, to) { return this.string.slice(from, to); }\n}\n\n/// Create a parse wrapper that, after the inner parse completes,\n/// scans its tree for mixed language regions with the `nest`\n/// function, runs the resulting [inner parses](#common.NestedParse),\n/// and then [mounts](#common.NodeProp^mounted) their results onto the\n/// tree.\nfunction parseMixed(nest) {\n return (parse, input, fragments, ranges) => new MixedParse(parse, nest, input, fragments, ranges);\n}\nclass InnerParse {\n constructor(parser, parse, overlay, target, ranges) {\n this.parser = parser;\n this.parse = parse;\n this.overlay = overlay;\n this.target = target;\n this.ranges = ranges;\n if (!ranges.length || ranges.some(r => r.from >= r.to))\n throw new RangeError(\"Invalid inner parse ranges given: \" + JSON.stringify(ranges));\n }\n}\nclass ActiveOverlay {\n constructor(parser, predicate, mounts, index, start, target, prev) {\n this.parser = parser;\n this.predicate = predicate;\n this.mounts = mounts;\n this.index = index;\n this.start = start;\n this.target = target;\n this.prev = prev;\n this.depth = 0;\n this.ranges = [];\n }\n}\nconst stoppedInner = new NodeProp({ perNode: true });\nclass MixedParse {\n constructor(base, nest, input, fragments, ranges) {\n this.nest = nest;\n this.input = input;\n this.fragments = fragments;\n this.ranges = ranges;\n this.inner = [];\n this.innerDone = 0;\n this.baseTree = null;\n this.stoppedAt = null;\n this.baseParse = base;\n }\n advance() {\n if (this.baseParse) {\n let done = this.baseParse.advance();\n if (!done)\n return null;\n this.baseParse = null;\n this.baseTree = done;\n this.startInner();\n if (this.stoppedAt != null)\n for (let inner of this.inner)\n inner.parse.stopAt(this.stoppedAt);\n }\n if (this.innerDone == this.inner.length) {\n let result = this.baseTree;\n if (this.stoppedAt != null)\n result = new Tree(result.type, result.children, result.positions, result.length, result.propValues.concat([[stoppedInner, this.stoppedAt]]));\n return result;\n }\n let inner = this.inner[this.innerDone], done = inner.parse.advance();\n if (done) {\n this.innerDone++;\n // This is a somewhat dodgy but super helpful hack where we\n // patch up nodes created by the inner parse (and thus\n // presumably not aliased anywhere else) to hold the information\n // about the inner parse.\n let props = Object.assign(Object.create(null), inner.target.props);\n props[NodeProp.mounted.id] = new MountedTree(done, inner.overlay, inner.parser);\n inner.target.props = props;\n }\n return null;\n }\n get parsedPos() {\n if (this.baseParse)\n return 0;\n let pos = this.input.length;\n for (let i = this.innerDone; i < this.inner.length; i++) {\n if (this.inner[i].ranges[0].from < pos)\n pos = Math.min(pos, this.inner[i].parse.parsedPos);\n }\n return pos;\n }\n stopAt(pos) {\n this.stoppedAt = pos;\n if (this.baseParse)\n this.baseParse.stopAt(pos);\n else\n for (let i = this.innerDone; i < this.inner.length; i++)\n this.inner[i].parse.stopAt(pos);\n }\n startInner() {\n let fragmentCursor = new FragmentCursor(this.fragments);\n let overlay = null;\n let covered = null;\n let cursor = new TreeCursor(new TreeNode(this.baseTree, this.ranges[0].from, 0, null), IterMode.IncludeAnonymous | IterMode.IgnoreMounts);\n scan: for (let nest, isCovered; this.stoppedAt == null || cursor.from < this.stoppedAt;) {\n let enter = true, range;\n if (fragmentCursor.hasNode(cursor)) {\n if (overlay) {\n let match = overlay.mounts.find(m => m.frag.from <= cursor.from && m.frag.to >= cursor.to && m.mount.overlay);\n if (match)\n for (let r of match.mount.overlay) {\n let from = r.from + match.pos, to = r.to + match.pos;\n if (from >= cursor.from && to <= cursor.to && !overlay.ranges.some(r => r.from < to && r.to > from))\n overlay.ranges.push({ from, to });\n }\n }\n enter = false;\n }\n else if (covered && (isCovered = checkCover(covered.ranges, cursor.from, cursor.to))) {\n enter = isCovered != 2 /* Cover.Full */;\n }\n else if (!cursor.type.isAnonymous && cursor.from < cursor.to && (nest = this.nest(cursor, this.input))) {\n if (!cursor.tree)\n materialize(cursor);\n let oldMounts = fragmentCursor.findMounts(cursor.from, nest.parser);\n if (typeof nest.overlay == \"function\") {\n overlay = new ActiveOverlay(nest.parser, nest.overlay, oldMounts, this.inner.length, cursor.from, cursor.tree, overlay);\n }\n else {\n let ranges = punchRanges(this.ranges, nest.overlay || [new Range(cursor.from, cursor.to)]);\n if (ranges.length)\n this.inner.push(new InnerParse(nest.parser, nest.parser.startParse(this.input, enterFragments(oldMounts, ranges), ranges), nest.overlay ? nest.overlay.map(r => new Range(r.from - cursor.from, r.to - cursor.from)) : null, cursor.tree, ranges));\n if (!nest.overlay)\n enter = false;\n else if (ranges.length)\n covered = { ranges, depth: 0, prev: covered };\n }\n }\n else if (overlay && (range = overlay.predicate(cursor))) {\n if (range === true)\n range = new Range(cursor.from, cursor.to);\n if (range.from < range.to)\n overlay.ranges.push(range);\n }\n if (enter && cursor.firstChild()) {\n if (overlay)\n overlay.depth++;\n if (covered)\n covered.depth++;\n }\n else {\n for (;;) {\n if (cursor.nextSibling())\n break;\n if (!cursor.parent())\n break scan;\n if (overlay && !--overlay.depth) {\n let ranges = punchRanges(this.ranges, overlay.ranges);\n if (ranges.length)\n this.inner.splice(overlay.index, 0, new InnerParse(overlay.parser, overlay.parser.startParse(this.input, enterFragments(overlay.mounts, ranges), ranges), overlay.ranges.map(r => new Range(r.from - overlay.start, r.to - overlay.start)), overlay.target, ranges));\n overlay = overlay.prev;\n }\n if (covered && !--covered.depth)\n covered = covered.prev;\n }\n }\n }\n }\n}\nfunction checkCover(covered, from, to) {\n for (let range of covered) {\n if (range.from >= to)\n break;\n if (range.to > from)\n return range.from <= from && range.to >= to ? 2 /* Cover.Full */ : 1 /* Cover.Partial */;\n }\n return 0 /* Cover.None */;\n}\n// Take a piece of buffer and convert it into a stand-alone\n// TreeBuffer.\nfunction sliceBuf(buf, startI, endI, nodes, positions, off) {\n if (startI < endI) {\n let from = buf.buffer[startI + 1];\n nodes.push(buf.slice(startI, endI, from));\n positions.push(from - off);\n }\n}\n// This function takes a node that's in a buffer, and converts it, and\n// its parent buffer nodes, into a Tree. This is again acting on the\n// assumption that the trees and buffers have been constructed by the\n// parse that was ran via the mix parser, and thus aren't shared with\n// any other code, making violations of the immutability safe.\nfunction materialize(cursor) {\n let { node } = cursor, depth = 0;\n // Scan up to the nearest tree\n do {\n cursor.parent();\n depth++;\n } while (!cursor.tree);\n // Find the index of the buffer in that tree\n let i = 0, base = cursor.tree, off = 0;\n for (;; i++) {\n off = base.positions[i] + cursor.from;\n if (off <= node.from && off + base.children[i].length >= node.to)\n break;\n }\n let buf = base.children[i], b = buf.buffer;\n // Split a level in the buffer, putting the nodes before and after\n // the child that contains `node` into new buffers.\n function split(startI, endI, type, innerOffset, length) {\n let i = startI;\n while (b[i + 2] + off <= node.from)\n i = b[i + 3];\n let children = [], positions = [];\n sliceBuf(buf, startI, i, children, positions, innerOffset);\n let from = b[i + 1], to = b[i + 2];\n let isTarget = from + off == node.from && to + off == node.to && b[i] == node.type.id;\n children.push(isTarget ? node.toTree() : split(i + 4, b[i + 3], buf.set.types[b[i]], from, to - from));\n positions.push(from - innerOffset);\n sliceBuf(buf, b[i + 3], endI, children, positions, innerOffset);\n return new Tree(type, children, positions, length);\n }\n base.children[i] = split(0, b.length, NodeType.none, 0, buf.length);\n // Move the cursor back to the target node\n for (let d = 0; d <= depth; d++)\n cursor.childAfter(node.from);\n}\nclass StructureCursor {\n constructor(root, offset) {\n this.offset = offset;\n this.done = false;\n this.cursor = root.cursor(IterMode.IncludeAnonymous | IterMode.IgnoreMounts);\n }\n // Move to the first node (in pre-order) that starts at or after `pos`.\n moveTo(pos) {\n let { cursor } = this, p = pos - this.offset;\n while (!this.done && cursor.from < p) {\n if (cursor.to >= pos && cursor.enter(p, 1, IterMode.IgnoreOverlays | IterMode.ExcludeBuffers)) ;\n else if (!cursor.next(false))\n this.done = true;\n }\n }\n hasNode(cursor) {\n this.moveTo(cursor.from);\n if (!this.done && this.cursor.from + this.offset == cursor.from && this.cursor.tree) {\n for (let tree = this.cursor.tree;;) {\n if (tree == cursor.tree)\n return true;\n if (tree.children.length && tree.positions[0] == 0 && tree.children[0] instanceof Tree)\n tree = tree.children[0];\n else\n break;\n }\n }\n return false;\n }\n}\nclass FragmentCursor {\n constructor(fragments) {\n var _a;\n this.fragments = fragments;\n this.curTo = 0;\n this.fragI = 0;\n if (fragments.length) {\n let first = this.curFrag = fragments[0];\n this.curTo = (_a = first.tree.prop(stoppedInner)) !== null && _a !== void 0 ? _a : first.to;\n this.inner = new StructureCursor(first.tree, -first.offset);\n }\n else {\n this.curFrag = this.inner = null;\n }\n }\n hasNode(node) {\n while (this.curFrag && node.from >= this.curTo)\n this.nextFrag();\n return this.curFrag && this.curFrag.from <= node.from && this.curTo >= node.to && this.inner.hasNode(node);\n }\n nextFrag() {\n var _a;\n this.fragI++;\n if (this.fragI == this.fragments.length) {\n this.curFrag = this.inner = null;\n }\n else {\n let frag = this.curFrag = this.fragments[this.fragI];\n this.curTo = (_a = frag.tree.prop(stoppedInner)) !== null && _a !== void 0 ? _a : frag.to;\n this.inner = new StructureCursor(frag.tree, -frag.offset);\n }\n }\n findMounts(pos, parser) {\n var _a;\n let result = [];\n if (this.inner) {\n this.inner.cursor.moveTo(pos, 1);\n for (let pos = this.inner.cursor.node; pos; pos = pos.parent) {\n let mount = (_a = pos.tree) === null || _a === void 0 ? void 0 : _a.prop(NodeProp.mounted);\n if (mount && mount.parser == parser) {\n for (let i = this.fragI; i < this.fragments.length; i++) {\n let frag = this.fragments[i];\n if (frag.from >= pos.to)\n break;\n if (frag.tree == this.curFrag.tree)\n result.push({\n frag,\n pos: pos.from - frag.offset,\n mount\n });\n }\n }\n }\n }\n return result;\n }\n}\nfunction punchRanges(outer, ranges) {\n let copy = null, current = ranges;\n for (let i = 1, j = 0; i < outer.length; i++) {\n let gapFrom = outer[i - 1].to, gapTo = outer[i].from;\n for (; j < current.length; j++) {\n let r = current[j];\n if (r.from >= gapTo)\n break;\n if (r.to <= gapFrom)\n continue;\n if (!copy)\n current = copy = ranges.slice();\n if (r.from < gapFrom) {\n copy[j] = new Range(r.from, gapFrom);\n if (r.to > gapTo)\n copy.splice(j + 1, 0, new Range(gapTo, r.to));\n }\n else if (r.to > gapTo) {\n copy[j--] = new Range(gapTo, r.to);\n }\n else {\n copy.splice(j--, 1);\n }\n }\n }\n return current;\n}\nfunction findCoverChanges(a, b, from, to) {\n let iA = 0, iB = 0, inA = false, inB = false, pos = -1e9;\n let result = [];\n for (;;) {\n let nextA = iA == a.length ? 1e9 : inA ? a[iA].to : a[iA].from;\n let nextB = iB == b.length ? 1e9 : inB ? b[iB].to : b[iB].from;\n if (inA != inB) {\n let start = Math.max(pos, from), end = Math.min(nextA, nextB, to);\n if (start < end)\n result.push(new Range(start, end));\n }\n pos = Math.min(nextA, nextB);\n if (pos == 1e9)\n break;\n if (nextA == pos) {\n if (!inA)\n inA = true;\n else {\n inA = false;\n iA++;\n }\n }\n if (nextB == pos) {\n if (!inB)\n inB = true;\n else {\n inB = false;\n iB++;\n }\n }\n }\n return result;\n}\n// Given a number of fragments for the outer tree, and a set of ranges\n// to parse, find fragments for inner trees mounted around those\n// ranges, if any.\nfunction enterFragments(mounts, ranges) {\n let result = [];\n for (let { pos, mount, frag } of mounts) {\n let startPos = pos + (mount.overlay ? mount.overlay[0].from : 0), endPos = startPos + mount.tree.length;\n let from = Math.max(frag.from, startPos), to = Math.min(frag.to, endPos);\n if (mount.overlay) {\n let overlay = mount.overlay.map(r => new Range(r.from + pos, r.to + pos));\n let changes = findCoverChanges(ranges, overlay, from, to);\n for (let i = 0, pos = from;; i++) {\n let last = i == changes.length, end = last ? to : changes[i].from;\n if (end > pos)\n result.push(new TreeFragment(pos, end, mount.tree, -startPos, frag.from >= pos || frag.openStart, frag.to <= end || frag.openEnd));\n if (last)\n break;\n pos = changes[i].to;\n }\n }\n else {\n result.push(new TreeFragment(from, to, mount.tree, -startPos, frag.from >= startPos || frag.openStart, frag.to <= endPos || frag.openEnd));\n }\n }\n return result;\n}\n\nexport { DefaultBufferLength, IterMode, MountedTree, NodeProp, NodeSet, NodeType, NodeWeakMap, Parser, Tree, TreeBuffer, TreeCursor, TreeFragment, parseMixed };\n", "import { Parser, NodeProp, NodeSet, NodeType, DefaultBufferLength, Tree, IterMode } from '@lezer/common';\n\n/// A parse stack. These are used internally by the parser to track\n/// parsing progress. They also provide some properties and methods\n/// that external code such as a tokenizer can use to get information\n/// about the parse state.\nclass Stack {\n /// @internal\n constructor(\n /// The parse that this stack is part of @internal\n p, \n /// Holds state, input pos, buffer index triplets for all but the\n /// top state @internal\n stack, \n /// The current parse state @internal\n state, \n // The position at which the next reduce should take place. This\n // can be less than `this.pos` when skipped expressions have been\n // added to the stack (which should be moved outside of the next\n // reduction)\n /// @internal\n reducePos, \n /// The input position up to which this stack has parsed.\n pos, \n /// The dynamic score of the stack, including dynamic precedence\n /// and error-recovery penalties\n /// @internal\n score, \n // The output buffer. Holds (type, start, end, size) quads\n // representing nodes created by the parser, where `size` is\n // amount of buffer array entries covered by this node.\n /// @internal\n buffer, \n // The base offset of the buffer. When stacks are split, the split\n // instance shared the buffer history with its parent up to\n // `bufferBase`, which is the absolute offset (including the\n // offset of previous splits) into the buffer at which this stack\n // starts writing.\n /// @internal\n bufferBase, \n /// @internal\n curContext, \n /// @internal\n lookAhead = 0, \n // A parent stack from which this was split off, if any. This is\n // set up so that it always points to a stack that has some\n // additional buffer content, never to a stack with an equal\n // `bufferBase`.\n /// @internal\n parent) {\n this.p = p;\n this.stack = stack;\n this.state = state;\n this.reducePos = reducePos;\n this.pos = pos;\n this.score = score;\n this.buffer = buffer;\n this.bufferBase = bufferBase;\n this.curContext = curContext;\n this.lookAhead = lookAhead;\n this.parent = parent;\n }\n /// @internal\n toString() {\n return `[${this.stack.filter((_, i) => i % 3 == 0).concat(this.state)}]@${this.pos}${this.score ? \"!\" + this.score : \"\"}`;\n }\n // Start an empty stack\n /// @internal\n static start(p, state, pos = 0) {\n let cx = p.parser.context;\n return new Stack(p, [], state, pos, pos, 0, [], 0, cx ? new StackContext(cx, cx.start) : null, 0, null);\n }\n /// The stack's current [context](#lr.ContextTracker) value, if\n /// any. Its type will depend on the context tracker's type\n /// parameter, or it will be `null` if there is no context\n /// tracker.\n get context() { return this.curContext ? this.curContext.context : null; }\n // Push a state onto the stack, tracking its start position as well\n // as the buffer base at that point.\n /// @internal\n pushState(state, start) {\n this.stack.push(this.state, start, this.bufferBase + this.buffer.length);\n this.state = state;\n }\n // Apply a reduce action\n /// @internal\n reduce(action) {\n var _a;\n let depth = action >> 19 /* Action.ReduceDepthShift */, type = action & 65535 /* Action.ValueMask */;\n let { parser } = this.p;\n let dPrec = parser.dynamicPrecedence(type);\n if (dPrec)\n this.score += dPrec;\n if (depth == 0) {\n this.pushState(parser.getGoto(this.state, type, true), this.reducePos);\n // Zero-depth reductions are a special case\u2014they add stuff to\n // the stack without popping anything off.\n if (type < parser.minRepeatTerm)\n this.storeNode(type, this.reducePos, this.reducePos, 4, true);\n this.reduceContext(type, this.reducePos);\n return;\n }\n // Find the base index into `this.stack`, content after which will\n // be dropped. Note that with `StayFlag` reductions we need to\n // consume two extra frames (the dummy parent node for the skipped\n // expression and the state that we'll be staying in, which should\n // be moved to `this.state`).\n let base = this.stack.length - ((depth - 1) * 3) - (action & 262144 /* Action.StayFlag */ ? 6 : 0);\n let start = base ? this.stack[base - 2] : this.p.ranges[0].from, size = this.reducePos - start;\n // This is a kludge to try and detect overly deep left-associative\n // trees, which will not increase the parse stack depth and thus\n // won't be caught by the regular stack-depth limit check.\n if (size >= 2000 /* Recover.MinBigReduction */ && !((_a = this.p.parser.nodeSet.types[type]) === null || _a === void 0 ? void 0 : _a.isAnonymous)) {\n if (start == this.p.lastBigReductionStart) {\n this.p.bigReductionCount++;\n this.p.lastBigReductionSize = size;\n }\n else if (this.p.lastBigReductionSize < size) {\n this.p.bigReductionCount = 1;\n this.p.lastBigReductionStart = start;\n this.p.lastBigReductionSize = size;\n }\n }\n let bufferBase = base ? this.stack[base - 1] : 0, count = this.bufferBase + this.buffer.length - bufferBase;\n // Store normal terms or `R -> R R` repeat reductions\n if (type < parser.minRepeatTerm || (action & 131072 /* Action.RepeatFlag */)) {\n let pos = parser.stateFlag(this.state, 1 /* StateFlag.Skipped */) ? this.pos : this.reducePos;\n this.storeNode(type, start, pos, count + 4, true);\n }\n if (action & 262144 /* Action.StayFlag */) {\n this.state = this.stack[base];\n }\n else {\n let baseStateID = this.stack[base - 3];\n this.state = parser.getGoto(baseStateID, type, true);\n }\n while (this.stack.length > base)\n this.stack.pop();\n this.reduceContext(type, start);\n }\n // Shift a value into the buffer\n /// @internal\n storeNode(term, start, end, size = 4, isReduce = false) {\n if (term == 0 /* Term.Err */ &&\n (!this.stack.length || this.stack[this.stack.length - 1] < this.buffer.length + this.bufferBase)) {\n // Try to omit/merge adjacent error nodes\n let cur = this, top = this.buffer.length;\n if (top == 0 && cur.parent) {\n top = cur.bufferBase - cur.parent.bufferBase;\n cur = cur.parent;\n }\n if (top > 0 && cur.buffer[top - 4] == 0 /* Term.Err */ && cur.buffer[top - 1] > -1) {\n if (start == end)\n return;\n if (cur.buffer[top - 2] >= start) {\n cur.buffer[top - 2] = end;\n return;\n }\n }\n }\n if (!isReduce || this.pos == end) { // Simple case, just append\n this.buffer.push(term, start, end, size);\n }\n else { // There may be skipped nodes that have to be moved forward\n let index = this.buffer.length;\n if (index > 0 && this.buffer[index - 4] != 0 /* Term.Err */)\n while (index > 0 && this.buffer[index - 2] > end) {\n // Move this record forward\n this.buffer[index] = this.buffer[index - 4];\n this.buffer[index + 1] = this.buffer[index - 3];\n this.buffer[index + 2] = this.buffer[index - 2];\n this.buffer[index + 3] = this.buffer[index - 1];\n index -= 4;\n if (size > 4)\n size -= 4;\n }\n this.buffer[index] = term;\n this.buffer[index + 1] = start;\n this.buffer[index + 2] = end;\n this.buffer[index + 3] = size;\n }\n }\n // Apply a shift action\n /// @internal\n shift(action, next, nextEnd) {\n let start = this.pos;\n if (action & 131072 /* Action.GotoFlag */) {\n this.pushState(action & 65535 /* Action.ValueMask */, this.pos);\n }\n else if ((action & 262144 /* Action.StayFlag */) == 0) { // Regular shift\n let nextState = action, { parser } = this.p;\n if (nextEnd > this.pos || next <= parser.maxNode) {\n this.pos = nextEnd;\n if (!parser.stateFlag(nextState, 1 /* StateFlag.Skipped */))\n this.reducePos = nextEnd;\n }\n this.pushState(nextState, start);\n this.shiftContext(next, start);\n if (next <= parser.maxNode)\n this.buffer.push(next, start, nextEnd, 4);\n }\n else { // Shift-and-stay, which means this is a skipped token\n this.pos = nextEnd;\n this.shiftContext(next, start);\n if (next <= this.p.parser.maxNode)\n this.buffer.push(next, start, nextEnd, 4);\n }\n }\n // Apply an action\n /// @internal\n apply(action, next, nextEnd) {\n if (action & 65536 /* Action.ReduceFlag */)\n this.reduce(action);\n else\n this.shift(action, next, nextEnd);\n }\n // Add a prebuilt (reused) node into the buffer.\n /// @internal\n useNode(value, next) {\n let index = this.p.reused.length - 1;\n if (index < 0 || this.p.reused[index] != value) {\n this.p.reused.push(value);\n index++;\n }\n let start = this.pos;\n this.reducePos = this.pos = start + value.length;\n this.pushState(next, start);\n this.buffer.push(index, start, this.reducePos, -1 /* size == -1 means this is a reused value */);\n if (this.curContext)\n this.updateContext(this.curContext.tracker.reuse(this.curContext.context, value, this, this.p.stream.reset(this.pos - value.length)));\n }\n // Split the stack. Due to the buffer sharing and the fact\n // that `this.stack` tends to stay quite shallow, this isn't very\n // expensive.\n /// @internal\n split() {\n let parent = this;\n let off = parent.buffer.length;\n // Because the top of the buffer (after this.pos) may be mutated\n // to reorder reductions and skipped tokens, and shared buffers\n // should be immutable, this copies any outstanding skipped tokens\n // to the new buffer, and puts the base pointer before them.\n while (off > 0 && parent.buffer[off - 2] > parent.reducePos)\n off -= 4;\n let buffer = parent.buffer.slice(off), base = parent.bufferBase + off;\n // Make sure parent points to an actual parent with content, if there is such a parent.\n while (parent && base == parent.bufferBase)\n parent = parent.parent;\n return new Stack(this.p, this.stack.slice(), this.state, this.reducePos, this.pos, this.score, buffer, base, this.curContext, this.lookAhead, parent);\n }\n // Try to recover from an error by 'deleting' (ignoring) one token.\n /// @internal\n recoverByDelete(next, nextEnd) {\n let isNode = next <= this.p.parser.maxNode;\n if (isNode)\n this.storeNode(next, this.pos, nextEnd, 4);\n this.storeNode(0 /* Term.Err */, this.pos, nextEnd, isNode ? 8 : 4);\n this.pos = this.reducePos = nextEnd;\n this.score -= 190 /* Recover.Delete */;\n }\n /// Check if the given term would be able to be shifted (optionally\n /// after some reductions) on this stack. This can be useful for\n /// external tokenizers that want to make sure they only provide a\n /// given token when it applies.\n canShift(term) {\n for (let sim = new SimulatedStack(this);;) {\n let action = this.p.parser.stateSlot(sim.state, 4 /* ParseState.DefaultReduce */) || this.p.parser.hasAction(sim.state, term);\n if (action == 0)\n return false;\n if ((action & 65536 /* Action.ReduceFlag */) == 0)\n return true;\n sim.reduce(action);\n }\n }\n // Apply up to Recover.MaxNext recovery actions that conceptually\n // inserts some missing token or rule.\n /// @internal\n recoverByInsert(next) {\n if (this.stack.length >= 300 /* Recover.MaxInsertStackDepth */)\n return [];\n let nextStates = this.p.parser.nextStates(this.state);\n if (nextStates.length > 4 /* Recover.MaxNext */ << 1 || this.stack.length >= 120 /* Recover.DampenInsertStackDepth */) {\n let best = [];\n for (let i = 0, s; i < nextStates.length; i += 2) {\n if ((s = nextStates[i + 1]) != this.state && this.p.parser.hasAction(s, next))\n best.push(nextStates[i], s);\n }\n if (this.stack.length < 120 /* Recover.DampenInsertStackDepth */)\n for (let i = 0; best.length < 4 /* Recover.MaxNext */ << 1 && i < nextStates.length; i += 2) {\n let s = nextStates[i + 1];\n if (!best.some((v, i) => (i & 1) && v == s))\n best.push(nextStates[i], s);\n }\n nextStates = best;\n }\n let result = [];\n for (let i = 0; i < nextStates.length && result.length < 4 /* Recover.MaxNext */; i += 2) {\n let s = nextStates[i + 1];\n if (s == this.state)\n continue;\n let stack = this.split();\n stack.pushState(s, this.pos);\n stack.storeNode(0 /* Term.Err */, stack.pos, stack.pos, 4, true);\n stack.shiftContext(nextStates[i], this.pos);\n stack.score -= 200 /* Recover.Insert */;\n result.push(stack);\n }\n return result;\n }\n // Force a reduce, if possible. Return false if that can't\n // be done.\n /// @internal\n forceReduce() {\n let { parser } = this.p;\n let reduce = parser.stateSlot(this.state, 5 /* ParseState.ForcedReduce */);\n if ((reduce & 65536 /* Action.ReduceFlag */) == 0)\n return false;\n if (!parser.validAction(this.state, reduce)) {\n let depth = reduce >> 19 /* Action.ReduceDepthShift */, term = reduce & 65535 /* Action.ValueMask */;\n let target = this.stack.length - depth * 3;\n if (target < 0 || parser.getGoto(this.stack[target], term, false) < 0) {\n let backup = this.findForcedReduction();\n if (backup == null)\n return false;\n reduce = backup;\n }\n this.storeNode(0 /* Term.Err */, this.pos, this.pos, 4, true);\n this.score -= 100 /* Recover.Reduce */;\n }\n this.reducePos = this.pos;\n this.reduce(reduce);\n return true;\n }\n /// Try to scan through the automaton to find some kind of reduction\n /// that can be applied. Used when the regular ForcedReduce field\n /// isn't a valid action. @internal\n findForcedReduction() {\n let { parser } = this.p, seen = [];\n let explore = (state, depth) => {\n if (seen.includes(state))\n return;\n seen.push(state);\n return parser.allActions(state, (action) => {\n if (action & (262144 /* Action.StayFlag */ | 131072 /* Action.GotoFlag */)) ;\n else if (action & 65536 /* Action.ReduceFlag */) {\n let rDepth = (action >> 19 /* Action.ReduceDepthShift */) - depth;\n if (rDepth > 1) {\n let term = action & 65535 /* Action.ValueMask */, target = this.stack.length - rDepth * 3;\n if (target >= 0 && parser.getGoto(this.stack[target], term, false) >= 0)\n return (rDepth << 19 /* Action.ReduceDepthShift */) | 65536 /* Action.ReduceFlag */ | term;\n }\n }\n else {\n let found = explore(action, depth + 1);\n if (found != null)\n return found;\n }\n });\n };\n return explore(this.state, 0);\n }\n /// @internal\n forceAll() {\n while (!this.p.parser.stateFlag(this.state, 2 /* StateFlag.Accepting */)) {\n if (!this.forceReduce()) {\n this.storeNode(0 /* Term.Err */, this.pos, this.pos, 4, true);\n break;\n }\n }\n return this;\n }\n /// Check whether this state has no further actions (assumed to be a direct descendant of the\n /// top state, since any other states must be able to continue\n /// somehow). @internal\n get deadEnd() {\n if (this.stack.length != 3)\n return false;\n let { parser } = this.p;\n return parser.data[parser.stateSlot(this.state, 1 /* ParseState.Actions */)] == 65535 /* Seq.End */ &&\n !parser.stateSlot(this.state, 4 /* ParseState.DefaultReduce */);\n }\n /// Restart the stack (put it back in its start state). Only safe\n /// when this.stack.length == 3 (state is directly below the top\n /// state). @internal\n restart() {\n this.state = this.stack[0];\n this.stack.length = 0;\n }\n /// @internal\n sameState(other) {\n if (this.state != other.state || this.stack.length != other.stack.length)\n return false;\n for (let i = 0; i < this.stack.length; i += 3)\n if (this.stack[i] != other.stack[i])\n return false;\n return true;\n }\n /// Get the parser used by this stack.\n get parser() { return this.p.parser; }\n /// Test whether a given dialect (by numeric ID, as exported from\n /// the terms file) is enabled.\n dialectEnabled(dialectID) { return this.p.parser.dialect.flags[dialectID]; }\n shiftContext(term, start) {\n if (this.curContext)\n this.updateContext(this.curContext.tracker.shift(this.curContext.context, term, this, this.p.stream.reset(start)));\n }\n reduceContext(term, start) {\n if (this.curContext)\n this.updateContext(this.curContext.tracker.reduce(this.curContext.context, term, this, this.p.stream.reset(start)));\n }\n /// @internal\n emitContext() {\n let last = this.buffer.length - 1;\n if (last < 0 || this.buffer[last] != -3)\n this.buffer.push(this.curContext.hash, this.pos, this.pos, -3);\n }\n /// @internal\n emitLookAhead() {\n let last = this.buffer.length - 1;\n if (last < 0 || this.buffer[last] != -4)\n this.buffer.push(this.lookAhead, this.pos, this.pos, -4);\n }\n updateContext(context) {\n if (context != this.curContext.context) {\n let newCx = new StackContext(this.curContext.tracker, context);\n if (newCx.hash != this.curContext.hash)\n this.emitContext();\n this.curContext = newCx;\n }\n }\n /// @internal\n setLookAhead(lookAhead) {\n if (lookAhead > this.lookAhead) {\n this.emitLookAhead();\n this.lookAhead = lookAhead;\n }\n }\n /// @internal\n close() {\n if (this.curContext && this.curContext.tracker.strict)\n this.emitContext();\n if (this.lookAhead > 0)\n this.emitLookAhead();\n }\n}\nclass StackContext {\n constructor(tracker, context) {\n this.tracker = tracker;\n this.context = context;\n this.hash = tracker.strict ? tracker.hash(context) : 0;\n }\n}\nvar Recover;\n(function (Recover) {\n Recover[Recover[\"Insert\"] = 200] = \"Insert\";\n Recover[Recover[\"Delete\"] = 190] = \"Delete\";\n Recover[Recover[\"Reduce\"] = 100] = \"Reduce\";\n Recover[Recover[\"MaxNext\"] = 4] = \"MaxNext\";\n Recover[Recover[\"MaxInsertStackDepth\"] = 300] = \"MaxInsertStackDepth\";\n Recover[Recover[\"DampenInsertStackDepth\"] = 120] = \"DampenInsertStackDepth\";\n Recover[Recover[\"MinBigReduction\"] = 2000] = \"MinBigReduction\";\n})(Recover || (Recover = {}));\n// Used to cheaply run some reductions to scan ahead without mutating\n// an entire stack\nclass SimulatedStack {\n constructor(start) {\n this.start = start;\n this.state = start.state;\n this.stack = start.stack;\n this.base = this.stack.length;\n }\n reduce(action) {\n let term = action & 65535 /* Action.ValueMask */, depth = action >> 19 /* Action.ReduceDepthShift */;\n if (depth == 0) {\n if (this.stack == this.start.stack)\n this.stack = this.stack.slice();\n this.stack.push(this.state, 0, 0);\n this.base += 3;\n }\n else {\n this.base -= (depth - 1) * 3;\n }\n let goto = this.start.p.parser.getGoto(this.stack[this.base - 3], term, true);\n this.state = goto;\n }\n}\n// This is given to `Tree.build` to build a buffer, and encapsulates\n// the parent-stack-walking necessary to read the nodes.\nclass StackBufferCursor {\n constructor(stack, pos, index) {\n this.stack = stack;\n this.pos = pos;\n this.index = index;\n this.buffer = stack.buffer;\n if (this.index == 0)\n this.maybeNext();\n }\n static create(stack, pos = stack.bufferBase + stack.buffer.length) {\n return new StackBufferCursor(stack, pos, pos - stack.bufferBase);\n }\n maybeNext() {\n let next = this.stack.parent;\n if (next != null) {\n this.index = this.stack.bufferBase - next.bufferBase;\n this.stack = next;\n this.buffer = next.buffer;\n }\n }\n get id() { return this.buffer[this.index - 4]; }\n get start() { return this.buffer[this.index - 3]; }\n get end() { return this.buffer[this.index - 2]; }\n get size() { return this.buffer[this.index - 1]; }\n next() {\n this.index -= 4;\n this.pos -= 4;\n if (this.index == 0)\n this.maybeNext();\n }\n fork() {\n return new StackBufferCursor(this.stack, this.pos, this.index);\n }\n}\n\n// See lezer-generator/src/encode.ts for comments about the encoding\n// used here\nfunction decodeArray(input, Type = Uint16Array) {\n if (typeof input != \"string\")\n return input;\n let array = null;\n for (let pos = 0, out = 0; pos < input.length;) {\n let value = 0;\n for (;;) {\n let next = input.charCodeAt(pos++), stop = false;\n if (next == 126 /* Encode.BigValCode */) {\n value = 65535 /* Encode.BigVal */;\n break;\n }\n if (next >= 92 /* Encode.Gap2 */)\n next--;\n if (next >= 34 /* Encode.Gap1 */)\n next--;\n let digit = next - 32 /* Encode.Start */;\n if (digit >= 46 /* Encode.Base */) {\n digit -= 46 /* Encode.Base */;\n stop = true;\n }\n value += digit;\n if (stop)\n break;\n value *= 46 /* Encode.Base */;\n }\n if (array)\n array[out++] = value;\n else\n array = new Type(value);\n }\n return array;\n}\n\nclass CachedToken {\n constructor() {\n this.start = -1;\n this.value = -1;\n this.end = -1;\n this.extended = -1;\n this.lookAhead = 0;\n this.mask = 0;\n this.context = 0;\n }\n}\nconst nullToken = new CachedToken;\n/// [Tokenizers](#lr.ExternalTokenizer) interact with the input\n/// through this interface. It presents the input as a stream of\n/// characters, tracking lookahead and hiding the complexity of\n/// [ranges](#common.Parser.parse^ranges) from tokenizer code.\nclass InputStream {\n /// @internal\n constructor(\n /// @internal\n input, \n /// @internal\n ranges) {\n this.input = input;\n this.ranges = ranges;\n /// @internal\n this.chunk = \"\";\n /// @internal\n this.chunkOff = 0;\n /// Backup chunk\n this.chunk2 = \"\";\n this.chunk2Pos = 0;\n /// The character code of the next code unit in the input, or -1\n /// when the stream is at the end of the input.\n this.next = -1;\n /// @internal\n this.token = nullToken;\n this.rangeIndex = 0;\n this.pos = this.chunkPos = ranges[0].from;\n this.range = ranges[0];\n this.end = ranges[ranges.length - 1].to;\n this.readNext();\n }\n /// @internal\n resolveOffset(offset, assoc) {\n let range = this.range, index = this.rangeIndex;\n let pos = this.pos + offset;\n while (pos < range.from) {\n if (!index)\n return null;\n let next = this.ranges[--index];\n pos -= range.from - next.to;\n range = next;\n }\n while (assoc < 0 ? pos > range.to : pos >= range.to) {\n if (index == this.ranges.length - 1)\n return null;\n let next = this.ranges[++index];\n pos += next.from - range.to;\n range = next;\n }\n return pos;\n }\n /// @internal\n clipPos(pos) {\n if (pos >= this.range.from && pos < this.range.to)\n return pos;\n for (let range of this.ranges)\n if (range.to > pos)\n return Math.max(pos, range.from);\n return this.end;\n }\n /// Look at a code unit near the stream position. `.peek(0)` equals\n /// `.next`, `.peek(-1)` gives you the previous character, and so\n /// on.\n ///\n /// Note that looking around during tokenizing creates dependencies\n /// on potentially far-away content, which may reduce the\n /// effectiveness incremental parsing\u2014when looking forward\u2014or even\n /// cause invalid reparses when looking backward more than 25 code\n /// units, since the library does not track lookbehind.\n peek(offset) {\n let idx = this.chunkOff + offset, pos, result;\n if (idx >= 0 && idx < this.chunk.length) {\n pos = this.pos + offset;\n result = this.chunk.charCodeAt(idx);\n }\n else {\n let resolved = this.resolveOffset(offset, 1);\n if (resolved == null)\n return -1;\n pos = resolved;\n if (pos >= this.chunk2Pos && pos < this.chunk2Pos + this.chunk2.length) {\n result = this.chunk2.charCodeAt(pos - this.chunk2Pos);\n }\n else {\n let i = this.rangeIndex, range = this.range;\n while (range.to <= pos)\n range = this.ranges[++i];\n this.chunk2 = this.input.chunk(this.chunk2Pos = pos);\n if (pos + this.chunk2.length > range.to)\n this.chunk2 = this.chunk2.slice(0, range.to - pos);\n result = this.chunk2.charCodeAt(0);\n }\n }\n if (pos >= this.token.lookAhead)\n this.token.lookAhead = pos + 1;\n return result;\n }\n /// Accept a token. By default, the end of the token is set to the\n /// current stream position, but you can pass an offset (relative to\n /// the stream position) to change that.\n acceptToken(token, endOffset = 0) {\n let end = endOffset ? this.resolveOffset(endOffset, -1) : this.pos;\n if (end == null || end < this.token.start)\n throw new RangeError(\"Token end out of bounds\");\n this.token.value = token;\n this.token.end = end;\n }\n getChunk() {\n if (this.pos >= this.chunk2Pos && this.pos < this.chunk2Pos + this.chunk2.length) {\n let { chunk, chunkPos } = this;\n this.chunk = this.chunk2;\n this.chunkPos = this.chunk2Pos;\n this.chunk2 = chunk;\n this.chunk2Pos = chunkPos;\n this.chunkOff = this.pos - this.chunkPos;\n }\n else {\n this.chunk2 = this.chunk;\n this.chunk2Pos = this.chunkPos;\n let nextChunk = this.input.chunk(this.pos);\n let end = this.pos + nextChunk.length;\n this.chunk = end > this.range.to ? nextChunk.slice(0, this.range.to - this.pos) : nextChunk;\n this.chunkPos = this.pos;\n this.chunkOff = 0;\n }\n }\n readNext() {\n if (this.chunkOff >= this.chunk.length) {\n this.getChunk();\n if (this.chunkOff == this.chunk.length)\n return this.next = -1;\n }\n return this.next = this.chunk.charCodeAt(this.chunkOff);\n }\n /// Move the stream forward N (defaults to 1) code units. Returns\n /// the new value of [`next`](#lr.InputStream.next).\n advance(n = 1) {\n this.chunkOff += n;\n while (this.pos + n >= this.range.to) {\n if (this.rangeIndex == this.ranges.length - 1)\n return this.setDone();\n n -= this.range.to - this.pos;\n this.range = this.ranges[++this.rangeIndex];\n this.pos = this.range.from;\n }\n this.pos += n;\n if (this.pos >= this.token.lookAhead)\n this.token.lookAhead = this.pos + 1;\n return this.readNext();\n }\n setDone() {\n this.pos = this.chunkPos = this.end;\n this.range = this.ranges[this.rangeIndex = this.ranges.length - 1];\n this.chunk = \"\";\n return this.next = -1;\n }\n /// @internal\n reset(pos, token) {\n if (token) {\n this.token = token;\n token.start = pos;\n token.lookAhead = pos + 1;\n token.value = token.extended = -1;\n }\n else {\n this.token = nullToken;\n }\n if (this.pos != pos) {\n this.pos = pos;\n if (pos == this.end) {\n this.setDone();\n return this;\n }\n while (pos < this.range.from)\n this.range = this.ranges[--this.rangeIndex];\n while (pos >= this.range.to)\n this.range = this.ranges[++this.rangeIndex];\n if (pos >= this.chunkPos && pos < this.chunkPos + this.chunk.length) {\n this.chunkOff = pos - this.chunkPos;\n }\n else {\n this.chunk = \"\";\n this.chunkOff = 0;\n }\n this.readNext();\n }\n return this;\n }\n /// @internal\n read(from, to) {\n if (from >= this.chunkPos && to <= this.chunkPos + this.chunk.length)\n return this.chunk.slice(from - this.chunkPos, to - this.chunkPos);\n if (from >= this.chunk2Pos && to <= this.chunk2Pos + this.chunk2.length)\n return this.chunk2.slice(from - this.chunk2Pos, to - this.chunk2Pos);\n if (from >= this.range.from && to <= this.range.to)\n return this.input.read(from, to);\n let result = \"\";\n for (let r of this.ranges) {\n if (r.from >= to)\n break;\n if (r.to > from)\n result += this.input.read(Math.max(r.from, from), Math.min(r.to, to));\n }\n return result;\n }\n}\n/// @internal\nclass TokenGroup {\n constructor(data, id) {\n this.data = data;\n this.id = id;\n }\n token(input, stack) {\n let { parser } = stack.p;\n readToken(this.data, input, stack, this.id, parser.data, parser.tokenPrecTable);\n }\n}\nTokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;\n/// @hide\nclass LocalTokenGroup {\n constructor(data, precTable, elseToken) {\n this.precTable = precTable;\n this.elseToken = elseToken;\n this.data = typeof data == \"string\" ? decodeArray(data) : data;\n }\n token(input, stack) {\n let start = input.pos, skipped = 0;\n for (;;) {\n let atEof = input.next < 0, nextPos = input.resolveOffset(1, 1);\n readToken(this.data, input, stack, 0, this.data, this.precTable);\n if (input.token.value > -1)\n break;\n if (this.elseToken == null)\n return;\n if (!atEof)\n skipped++;\n if (nextPos == null)\n break;\n input.reset(nextPos, input.token);\n }\n if (skipped) {\n input.reset(start, input.token);\n input.acceptToken(this.elseToken, skipped);\n }\n }\n}\nLocalTokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;\n/// `@external tokens` declarations in the grammar should resolve to\n/// an instance of this class.\nclass ExternalTokenizer {\n /// Create a tokenizer. The first argument is the function that,\n /// given an input stream, scans for the types of tokens it\n /// recognizes at the stream's position, and calls\n /// [`acceptToken`](#lr.InputStream.acceptToken) when it finds\n /// one.\n constructor(\n /// @internal\n token, options = {}) {\n this.token = token;\n this.contextual = !!options.contextual;\n this.fallback = !!options.fallback;\n this.extend = !!options.extend;\n }\n}\n// Tokenizer data is stored a big uint16 array containing, for each\n// state:\n//\n// - A group bitmask, indicating what token groups are reachable from\n// this state, so that paths that can only lead to tokens not in\n// any of the current groups can be cut off early.\n//\n// - The position of the end of the state's sequence of accepting\n// tokens\n//\n// - The number of outgoing edges for the state\n//\n// - The accepting tokens, as (token id, group mask) pairs\n//\n// - The outgoing edges, as (start character, end character, state\n// index) triples, with end character being exclusive\n//\n// This function interprets that data, running through a stream as\n// long as new states with the a matching group mask can be reached,\n// and updating `input.token` when it matches a token.\nfunction readToken(data, input, stack, group, precTable, precOffset) {\n let state = 0, groupMask = 1 << group, { dialect } = stack.p.parser;\n scan: for (;;) {\n if ((groupMask & data[state]) == 0)\n break;\n let accEnd = data[state + 1];\n // Check whether this state can lead to a token in the current group\n // Accept tokens in this state, possibly overwriting\n // lower-precedence / shorter tokens\n for (let i = state + 3; i < accEnd; i += 2)\n if ((data[i + 1] & groupMask) > 0) {\n let term = data[i];\n if (dialect.allows(term) &&\n (input.token.value == -1 || input.token.value == term ||\n overrides(term, input.token.value, precTable, precOffset))) {\n input.acceptToken(term);\n break;\n }\n }\n let next = input.next, low = 0, high = data[state + 2];\n // Special case for EOF\n if (input.next < 0 && high > low && data[accEnd + high * 3 - 3] == 65535 /* Seq.End */ && data[accEnd + high * 3 - 3] == 65535 /* Seq.End */) {\n state = data[accEnd + high * 3 - 1];\n continue scan;\n }\n // Do a binary search on the state's edges\n for (; low < high;) {\n let mid = (low + high) >> 1;\n let index = accEnd + mid + (mid << 1);\n let from = data[index], to = data[index + 1] || 0x10000;\n if (next < from)\n high = mid;\n else if (next >= to)\n low = mid + 1;\n else {\n state = data[index + 2];\n input.advance();\n continue scan;\n }\n }\n break;\n }\n}\nfunction findOffset(data, start, term) {\n for (let i = start, next; (next = data[i]) != 65535 /* Seq.End */; i++)\n if (next == term)\n return i - start;\n return -1;\n}\nfunction overrides(token, prev, tableData, tableOffset) {\n let iPrev = findOffset(tableData, tableOffset, prev);\n return iPrev < 0 || findOffset(tableData, tableOffset, token) < iPrev;\n}\n\n// Environment variable used to control console output\nconst verbose = typeof process != \"undefined\" && process.env && /\\bparse\\b/.test(process.env.LOG);\nlet stackIDs = null;\nvar Safety;\n(function (Safety) {\n Safety[Safety[\"Margin\"] = 25] = \"Margin\";\n})(Safety || (Safety = {}));\nfunction cutAt(tree, pos, side) {\n let cursor = tree.cursor(IterMode.IncludeAnonymous);\n cursor.moveTo(pos);\n for (;;) {\n if (!(side < 0 ? cursor.childBefore(pos) : cursor.childAfter(pos)))\n for (;;) {\n if ((side < 0 ? cursor.to < pos : cursor.from > pos) && !cursor.type.isError)\n return side < 0 ? Math.max(0, Math.min(cursor.to - 1, pos - 25 /* Safety.Margin */))\n : Math.min(tree.length, Math.max(cursor.from + 1, pos + 25 /* Safety.Margin */));\n if (side < 0 ? cursor.prevSibling() : cursor.nextSibling())\n break;\n if (!cursor.parent())\n return side < 0 ? 0 : tree.length;\n }\n }\n}\nclass FragmentCursor {\n constructor(fragments, nodeSet) {\n this.fragments = fragments;\n this.nodeSet = nodeSet;\n this.i = 0;\n this.fragment = null;\n this.safeFrom = -1;\n this.safeTo = -1;\n this.trees = [];\n this.start = [];\n this.index = [];\n this.nextFragment();\n }\n nextFragment() {\n let fr = this.fragment = this.i == this.fragments.length ? null : this.fragments[this.i++];\n if (fr) {\n this.safeFrom = fr.openStart ? cutAt(fr.tree, fr.from + fr.offset, 1) - fr.offset : fr.from;\n this.safeTo = fr.openEnd ? cutAt(fr.tree, fr.to + fr.offset, -1) - fr.offset : fr.to;\n while (this.trees.length) {\n this.trees.pop();\n this.start.pop();\n this.index.pop();\n }\n this.trees.push(fr.tree);\n this.start.push(-fr.offset);\n this.index.push(0);\n this.nextStart = this.safeFrom;\n }\n else {\n this.nextStart = 1e9;\n }\n }\n // `pos` must be >= any previously given `pos` for this cursor\n nodeAt(pos) {\n if (pos < this.nextStart)\n return null;\n while (this.fragment && this.safeTo <= pos)\n this.nextFragment();\n if (!this.fragment)\n return null;\n for (;;) {\n let last = this.trees.length - 1;\n if (last < 0) { // End of tree\n this.nextFragment();\n return null;\n }\n let top = this.trees[last], index = this.index[last];\n if (index == top.children.length) {\n this.trees.pop();\n this.start.pop();\n this.index.pop();\n continue;\n }\n let next = top.children[index];\n let start = this.start[last] + top.positions[index];\n if (start > pos) {\n this.nextStart = start;\n return null;\n }\n if (next instanceof Tree) {\n if (start == pos) {\n if (start < this.safeFrom)\n return null;\n let end = start + next.length;\n if (end <= this.safeTo) {\n let lookAhead = next.prop(NodeProp.lookAhead);\n if (!lookAhead || end + lookAhead < this.fragment.to)\n return next;\n }\n }\n this.index[last]++;\n if (start + next.length >= Math.max(this.safeFrom, pos)) { // Enter this node\n this.trees.push(next);\n this.start.push(start);\n this.index.push(0);\n }\n }\n else {\n this.index[last]++;\n this.nextStart = start + next.length;\n }\n }\n }\n}\nclass TokenCache {\n constructor(parser, stream) {\n this.stream = stream;\n this.tokens = [];\n this.mainToken = null;\n this.actions = [];\n this.tokens = parser.tokenizers.map(_ => new CachedToken);\n }\n getActions(stack) {\n let actionIndex = 0;\n let main = null;\n let { parser } = stack.p, { tokenizers } = parser;\n let mask = parser.stateSlot(stack.state, 3 /* ParseState.TokenizerMask */);\n let context = stack.curContext ? stack.curContext.hash : 0;\n let lookAhead = 0;\n for (let i = 0; i < tokenizers.length; i++) {\n if (((1 << i) & mask) == 0)\n continue;\n let tokenizer = tokenizers[i], token = this.tokens[i];\n if (main && !tokenizer.fallback)\n continue;\n if (tokenizer.contextual || token.start != stack.pos || token.mask != mask || token.context != context) {\n this.updateCachedToken(token, tokenizer, stack);\n token.mask = mask;\n token.context = context;\n }\n if (token.lookAhead > token.end + 25 /* Safety.Margin */)\n lookAhead = Math.max(token.lookAhead, lookAhead);\n if (token.value != 0 /* Term.Err */) {\n let startIndex = actionIndex;\n if (token.extended > -1)\n actionIndex = this.addActions(stack, token.extended, token.end, actionIndex);\n actionIndex = this.addActions(stack, token.value, token.end, actionIndex);\n if (!tokenizer.extend) {\n main = token;\n if (actionIndex > startIndex)\n break;\n }\n }\n }\n while (this.actions.length > actionIndex)\n this.actions.pop();\n if (lookAhead)\n stack.setLookAhead(lookAhead);\n if (!main && stack.pos == this.stream.end) {\n main = new CachedToken;\n main.value = stack.p.parser.eofTerm;\n main.start = main.end = stack.pos;\n actionIndex = this.addActions(stack, main.value, main.end, actionIndex);\n }\n this.mainToken = main;\n return this.actions;\n }\n getMainToken(stack) {\n if (this.mainToken)\n return this.mainToken;\n let main = new CachedToken, { pos, p } = stack;\n main.start = pos;\n main.end = Math.min(pos + 1, p.stream.end);\n main.value = pos == p.stream.end ? p.parser.eofTerm : 0 /* Term.Err */;\n return main;\n }\n updateCachedToken(token, tokenizer, stack) {\n let start = this.stream.clipPos(stack.pos);\n tokenizer.token(this.stream.reset(start, token), stack);\n if (token.value > -1) {\n let { parser } = stack.p;\n for (let i = 0; i < parser.specialized.length; i++)\n if (parser.specialized[i] == token.value) {\n let result = parser.specializers[i](this.stream.read(token.start, token.end), stack);\n if (result >= 0 && stack.p.parser.dialect.allows(result >> 1)) {\n if ((result & 1) == 0 /* Specialize.Specialize */)\n token.value = result >> 1;\n else\n token.extended = result >> 1;\n break;\n }\n }\n }\n else {\n token.value = 0 /* Term.Err */;\n token.end = this.stream.clipPos(start + 1);\n }\n }\n putAction(action, token, end, index) {\n // Don't add duplicate actions\n for (let i = 0; i < index; i += 3)\n if (this.actions[i] == action)\n return index;\n this.actions[index++] = action;\n this.actions[index++] = token;\n this.actions[index++] = end;\n return index;\n }\n addActions(stack, token, end, index) {\n let { state } = stack, { parser } = stack.p, { data } = parser;\n for (let set = 0; set < 2; set++) {\n for (let i = parser.stateSlot(state, set ? 2 /* ParseState.Skip */ : 1 /* ParseState.Actions */);; i += 3) {\n if (data[i] == 65535 /* Seq.End */) {\n if (data[i + 1] == 1 /* Seq.Next */) {\n i = pair(data, i + 2);\n }\n else {\n if (index == 0 && data[i + 1] == 2 /* Seq.Other */)\n index = this.putAction(pair(data, i + 2), token, end, index);\n break;\n }\n }\n if (data[i] == token)\n index = this.putAction(pair(data, i + 1), token, end, index);\n }\n }\n return index;\n }\n}\nvar Rec;\n(function (Rec) {\n Rec[Rec[\"Distance\"] = 5] = \"Distance\";\n Rec[Rec[\"MaxRemainingPerStep\"] = 3] = \"MaxRemainingPerStep\";\n // When two stacks have been running independently long enough to\n // add this many elements to their buffers, prune one.\n Rec[Rec[\"MinBufferLengthPrune\"] = 500] = \"MinBufferLengthPrune\";\n Rec[Rec[\"ForceReduceLimit\"] = 10] = \"ForceReduceLimit\";\n // Once a stack reaches this depth (in .stack.length) force-reduce\n // it back to CutTo to avoid creating trees that overflow the stack\n // on recursive traversal.\n Rec[Rec[\"CutDepth\"] = 15000] = \"CutDepth\";\n Rec[Rec[\"CutTo\"] = 9000] = \"CutTo\";\n Rec[Rec[\"MaxLeftAssociativeReductionCount\"] = 300] = \"MaxLeftAssociativeReductionCount\";\n // The maximum number of non-recovering stacks to explore (to avoid\n // getting bogged down with exponentially multiplying stacks in\n // ambiguous content)\n Rec[Rec[\"MaxStackCount\"] = 12] = \"MaxStackCount\";\n})(Rec || (Rec = {}));\nclass Parse {\n constructor(parser, input, fragments, ranges) {\n this.parser = parser;\n this.input = input;\n this.ranges = ranges;\n this.recovering = 0;\n this.nextStackID = 0x2654; // \u2654, \u2655, \u2656, \u2657, \u2658, \u2659, \u2660, \u2661, \u2662, \u2663, \u2664, \u2665, \u2666, \u2667\n this.minStackPos = 0;\n this.reused = [];\n this.stoppedAt = null;\n this.lastBigReductionStart = -1;\n this.lastBigReductionSize = 0;\n this.bigReductionCount = 0;\n this.stream = new InputStream(input, ranges);\n this.tokens = new TokenCache(parser, this.stream);\n this.topTerm = parser.top[1];\n let { from } = ranges[0];\n this.stacks = [Stack.start(this, parser.top[0], from)];\n this.fragments = fragments.length && this.stream.end - from > parser.bufferLength * 4\n ? new FragmentCursor(fragments, parser.nodeSet) : null;\n }\n get parsedPos() {\n return this.minStackPos;\n }\n // Move the parser forward. This will process all parse stacks at\n // `this.pos` and try to advance them to a further position. If no\n // stack for such a position is found, it'll start error-recovery.\n //\n // When the parse is finished, this will return a syntax tree. When\n // not, it returns `null`.\n advance() {\n let stacks = this.stacks, pos = this.minStackPos;\n // This will hold stacks beyond `pos`.\n let newStacks = this.stacks = [];\n let stopped, stoppedTokens;\n // If a large amount of reductions happened with the same start\n // position, force the stack out of that production in order to\n // avoid creating a tree too deep to recurse through.\n // (This is an ugly kludge, because unfortunately there is no\n // straightforward, cheap way to check for this happening, due to\n // the history of reductions only being available in an\n // expensive-to-access format in the stack buffers.)\n if (this.bigReductionCount > 300 /* Rec.MaxLeftAssociativeReductionCount */ && stacks.length == 1) {\n let [s] = stacks;\n while (s.forceReduce() && s.stack.length && s.stack[s.stack.length - 2] >= this.lastBigReductionStart) { }\n this.bigReductionCount = this.lastBigReductionSize = 0;\n }\n // Keep advancing any stacks at `pos` until they either move\n // forward or can't be advanced. Gather stacks that can't be\n // advanced further in `stopped`.\n for (let i = 0; i < stacks.length; i++) {\n let stack = stacks[i];\n for (;;) {\n this.tokens.mainToken = null;\n if (stack.pos > pos) {\n newStacks.push(stack);\n }\n else if (this.advanceStack(stack, newStacks, stacks)) {\n continue;\n }\n else {\n if (!stopped) {\n stopped = [];\n stoppedTokens = [];\n }\n stopped.push(stack);\n let tok = this.tokens.getMainToken(stack);\n stoppedTokens.push(tok.value, tok.end);\n }\n break;\n }\n }\n if (!newStacks.length) {\n let finished = stopped && findFinished(stopped);\n if (finished)\n return this.stackToTree(finished);\n if (this.parser.strict) {\n if (verbose && stopped)\n console.log(\"Stuck with token \" + (this.tokens.mainToken ? this.parser.getName(this.tokens.mainToken.value) : \"none\"));\n throw new SyntaxError(\"No parse at \" + pos);\n }\n if (!this.recovering)\n this.recovering = 5 /* Rec.Distance */;\n }\n if (this.recovering && stopped) {\n let finished = this.stoppedAt != null && stopped[0].pos > this.stoppedAt ? stopped[0]\n : this.runRecovery(stopped, stoppedTokens, newStacks);\n if (finished)\n return this.stackToTree(finished.forceAll());\n }\n if (this.recovering) {\n let maxRemaining = this.recovering == 1 ? 1 : this.recovering * 3 /* Rec.MaxRemainingPerStep */;\n if (newStacks.length > maxRemaining) {\n newStacks.sort((a, b) => b.score - a.score);\n while (newStacks.length > maxRemaining)\n newStacks.pop();\n }\n if (newStacks.some(s => s.reducePos > pos))\n this.recovering--;\n }\n else if (newStacks.length > 1) {\n // Prune stacks that are in the same state, or that have been\n // running without splitting for a while, to avoid getting stuck\n // with multiple successful stacks running endlessly on.\n outer: for (let i = 0; i < newStacks.length - 1; i++) {\n let stack = newStacks[i];\n for (let j = i + 1; j < newStacks.length; j++) {\n let other = newStacks[j];\n if (stack.sameState(other) ||\n stack.buffer.length > 500 /* Rec.MinBufferLengthPrune */ && other.buffer.length > 500 /* Rec.MinBufferLengthPrune */) {\n if (((stack.score - other.score) || (stack.buffer.length - other.buffer.length)) > 0) {\n newStacks.splice(j--, 1);\n }\n else {\n newStacks.splice(i--, 1);\n continue outer;\n }\n }\n }\n }\n if (newStacks.length > 12 /* Rec.MaxStackCount */)\n newStacks.splice(12 /* Rec.MaxStackCount */, newStacks.length - 12 /* Rec.MaxStackCount */);\n }\n this.minStackPos = newStacks[0].pos;\n for (let i = 1; i < newStacks.length; i++)\n if (newStacks[i].pos < this.minStackPos)\n this.minStackPos = newStacks[i].pos;\n return null;\n }\n stopAt(pos) {\n if (this.stoppedAt != null && this.stoppedAt < pos)\n throw new RangeError(\"Can't move stoppedAt forward\");\n this.stoppedAt = pos;\n }\n // Returns an updated version of the given stack, or null if the\n // stack can't advance normally. When `split` and `stacks` are\n // given, stacks split off by ambiguous operations will be pushed to\n // `split`, or added to `stacks` if they move `pos` forward.\n advanceStack(stack, stacks, split) {\n let start = stack.pos, { parser } = this;\n let base = verbose ? this.stackID(stack) + \" -> \" : \"\";\n if (this.stoppedAt != null && start > this.stoppedAt)\n return stack.forceReduce() ? stack : null;\n if (this.fragments) {\n let strictCx = stack.curContext && stack.curContext.tracker.strict, cxHash = strictCx ? stack.curContext.hash : 0;\n for (let cached = this.fragments.nodeAt(start); cached;) {\n let match = this.parser.nodeSet.types[cached.type.id] == cached.type ? parser.getGoto(stack.state, cached.type.id) : -1;\n if (match > -1 && cached.length && (!strictCx || (cached.prop(NodeProp.contextHash) || 0) == cxHash)) {\n stack.useNode(cached, match);\n if (verbose)\n console.log(base + this.stackID(stack) + ` (via reuse of ${parser.getName(cached.type.id)})`);\n return true;\n }\n if (!(cached instanceof Tree) || cached.children.length == 0 || cached.positions[0] > 0)\n break;\n let inner = cached.children[0];\n if (inner instanceof Tree && cached.positions[0] == 0)\n cached = inner;\n else\n break;\n }\n }\n let defaultReduce = parser.stateSlot(stack.state, 4 /* ParseState.DefaultReduce */);\n if (defaultReduce > 0) {\n stack.reduce(defaultReduce);\n if (verbose)\n console.log(base + this.stackID(stack) + ` (via always-reduce ${parser.getName(defaultReduce & 65535 /* Action.ValueMask */)})`);\n return true;\n }\n if (stack.stack.length >= 15000 /* Rec.CutDepth */) {\n while (stack.stack.length > 9000 /* Rec.CutTo */ && stack.forceReduce()) { }\n }\n let actions = this.tokens.getActions(stack);\n for (let i = 0; i < actions.length;) {\n let action = actions[i++], term = actions[i++], end = actions[i++];\n let last = i == actions.length || !split;\n let localStack = last ? stack : stack.split();\n localStack.apply(action, term, end);\n if (verbose)\n console.log(base + this.stackID(localStack) + ` (via ${(action & 65536 /* Action.ReduceFlag */) == 0 ? \"shift\"\n : `reduce of ${parser.getName(action & 65535 /* Action.ValueMask */)}`} for ${parser.getName(term)} @ ${start}${localStack == stack ? \"\" : \", split\"})`);\n if (last)\n return true;\n else if (localStack.pos > start)\n stacks.push(localStack);\n else\n split.push(localStack);\n }\n return false;\n }\n // Advance a given stack forward as far as it will go. Returns the\n // (possibly updated) stack if it got stuck, or null if it moved\n // forward and was given to `pushStackDedup`.\n advanceFully(stack, newStacks) {\n let pos = stack.pos;\n for (;;) {\n if (!this.advanceStack(stack, null, null))\n return false;\n if (stack.pos > pos) {\n pushStackDedup(stack, newStacks);\n return true;\n }\n }\n }\n runRecovery(stacks, tokens, newStacks) {\n let finished = null, restarted = false;\n for (let i = 0; i < stacks.length; i++) {\n let stack = stacks[i], token = tokens[i << 1], tokenEnd = tokens[(i << 1) + 1];\n let base = verbose ? this.stackID(stack) + \" -> \" : \"\";\n if (stack.deadEnd) {\n if (restarted)\n continue;\n restarted = true;\n stack.restart();\n if (verbose)\n console.log(base + this.stackID(stack) + \" (restarted)\");\n let done = this.advanceFully(stack, newStacks);\n if (done)\n continue;\n }\n let force = stack.split(), forceBase = base;\n for (let j = 0; force.forceReduce() && j < 10 /* Rec.ForceReduceLimit */; j++) {\n if (verbose)\n console.log(forceBase + this.stackID(force) + \" (via force-reduce)\");\n let done = this.advanceFully(force, newStacks);\n if (done)\n break;\n if (verbose)\n forceBase = this.stackID(force) + \" -> \";\n }\n for (let insert of stack.recoverByInsert(token)) {\n if (verbose)\n console.log(base + this.stackID(insert) + \" (via recover-insert)\");\n this.advanceFully(insert, newStacks);\n }\n if (this.stream.end > stack.pos) {\n if (tokenEnd == stack.pos) {\n tokenEnd++;\n token = 0 /* Term.Err */;\n }\n stack.recoverByDelete(token, tokenEnd);\n if (verbose)\n console.log(base + this.stackID(stack) + ` (via recover-delete ${this.parser.getName(token)})`);\n pushStackDedup(stack, newStacks);\n }\n else if (!finished || finished.score < stack.score) {\n finished = stack;\n }\n }\n return finished;\n }\n // Convert the stack's buffer to a syntax tree.\n stackToTree(stack) {\n stack.close();\n return Tree.build({ buffer: StackBufferCursor.create(stack),\n nodeSet: this.parser.nodeSet,\n topID: this.topTerm,\n maxBufferLength: this.parser.bufferLength,\n reused: this.reused,\n start: this.ranges[0].from,\n length: stack.pos - this.ranges[0].from,\n minRepeatType: this.parser.minRepeatTerm });\n }\n stackID(stack) {\n let id = (stackIDs || (stackIDs = new WeakMap)).get(stack);\n if (!id)\n stackIDs.set(stack, id = String.fromCodePoint(this.nextStackID++));\n return id + stack;\n }\n}\nfunction pushStackDedup(stack, newStacks) {\n for (let i = 0; i < newStacks.length; i++) {\n let other = newStacks[i];\n if (other.pos == stack.pos && other.sameState(stack)) {\n if (newStacks[i].score < stack.score)\n newStacks[i] = stack;\n return;\n }\n }\n newStacks.push(stack);\n}\nclass Dialect {\n constructor(source, flags, disabled) {\n this.source = source;\n this.flags = flags;\n this.disabled = disabled;\n }\n allows(term) { return !this.disabled || this.disabled[term] == 0; }\n}\nconst id = x => x;\n/// Context trackers are used to track stateful context (such as\n/// indentation in the Python grammar, or parent elements in the XML\n/// grammar) needed by external tokenizers. You declare them in a\n/// grammar file as `@context exportName from \"module\"`.\n///\n/// Context values should be immutable, and can be updated (replaced)\n/// on shift or reduce actions.\n///\n/// The export used in a `@context` declaration should be of this\n/// type.\nclass ContextTracker {\n /// Define a context tracker.\n constructor(spec) {\n this.start = spec.start;\n this.shift = spec.shift || id;\n this.reduce = spec.reduce || id;\n this.reuse = spec.reuse || id;\n this.hash = spec.hash || (() => 0);\n this.strict = spec.strict !== false;\n }\n}\n/// Holds the parse tables for a given grammar, as generated by\n/// `lezer-generator`, and provides [methods](#common.Parser) to parse\n/// content with.\nclass LRParser extends Parser {\n /// @internal\n constructor(spec) {\n super();\n /// @internal\n this.wrappers = [];\n if (spec.version != 14 /* File.Version */)\n throw new RangeError(`Parser version (${spec.version}) doesn't match runtime version (${14 /* File.Version */})`);\n let nodeNames = spec.nodeNames.split(\" \");\n this.minRepeatTerm = nodeNames.length;\n for (let i = 0; i < spec.repeatNodeCount; i++)\n nodeNames.push(\"\");\n let topTerms = Object.keys(spec.topRules).map(r => spec.topRules[r][1]);\n let nodeProps = [];\n for (let i = 0; i < nodeNames.length; i++)\n nodeProps.push([]);\n function setProp(nodeID, prop, value) {\n nodeProps[nodeID].push([prop, prop.deserialize(String(value))]);\n }\n if (spec.nodeProps)\n for (let propSpec of spec.nodeProps) {\n let prop = propSpec[0];\n if (typeof prop == \"string\")\n prop = NodeProp[prop];\n for (let i = 1; i < propSpec.length;) {\n let next = propSpec[i++];\n if (next >= 0) {\n setProp(next, prop, propSpec[i++]);\n }\n else {\n let value = propSpec[i + -next];\n for (let j = -next; j > 0; j--)\n setProp(propSpec[i++], prop, value);\n i++;\n }\n }\n }\n this.nodeSet = new NodeSet(nodeNames.map((name, i) => NodeType.define({\n name: i >= this.minRepeatTerm ? undefined : name,\n id: i,\n props: nodeProps[i],\n top: topTerms.indexOf(i) > -1,\n error: i == 0,\n skipped: spec.skippedNodes && spec.skippedNodes.indexOf(i) > -1\n })));\n if (spec.propSources)\n this.nodeSet = this.nodeSet.extend(...spec.propSources);\n this.strict = false;\n this.bufferLength = DefaultBufferLength;\n let tokenArray = decodeArray(spec.tokenData);\n this.context = spec.context;\n this.specializerSpecs = spec.specialized || [];\n this.specialized = new Uint16Array(this.specializerSpecs.length);\n for (let i = 0; i < this.specializerSpecs.length; i++)\n this.specialized[i] = this.specializerSpecs[i].term;\n this.specializers = this.specializerSpecs.map(getSpecializer);\n this.states = decodeArray(spec.states, Uint32Array);\n this.data = decodeArray(spec.stateData);\n this.goto = decodeArray(spec.goto);\n this.maxTerm = spec.maxTerm;\n this.tokenizers = spec.tokenizers.map(value => typeof value == \"number\" ? new TokenGroup(tokenArray, value) : value);\n this.topRules = spec.topRules;\n this.dialects = spec.dialects || {};\n this.dynamicPrecedences = spec.dynamicPrecedences || null;\n this.tokenPrecTable = spec.tokenPrec;\n this.termNames = spec.termNames || null;\n this.maxNode = this.nodeSet.types.length - 1;\n this.dialect = this.parseDialect();\n this.top = this.topRules[Object.keys(this.topRules)[0]];\n }\n createParse(input, fragments, ranges) {\n let parse = new Parse(this, input, fragments, ranges);\n for (let w of this.wrappers)\n parse = w(parse, input, fragments, ranges);\n return parse;\n }\n /// Get a goto table entry @internal\n getGoto(state, term, loose = false) {\n let table = this.goto;\n if (term >= table[0])\n return -1;\n for (let pos = table[term + 1];;) {\n let groupTag = table[pos++], last = groupTag & 1;\n let target = table[pos++];\n if (last && loose)\n return target;\n for (let end = pos + (groupTag >> 1); pos < end; pos++)\n if (table[pos] == state)\n return target;\n if (last)\n return -1;\n }\n }\n /// Check if this state has an action for a given terminal @internal\n hasAction(state, terminal) {\n let data = this.data;\n for (let set = 0; set < 2; set++) {\n for (let i = this.stateSlot(state, set ? 2 /* ParseState.Skip */ : 1 /* ParseState.Actions */), next;; i += 3) {\n if ((next = data[i]) == 65535 /* Seq.End */) {\n if (data[i + 1] == 1 /* Seq.Next */)\n next = data[i = pair(data, i + 2)];\n else if (data[i + 1] == 2 /* Seq.Other */)\n return pair(data, i + 2);\n else\n break;\n }\n if (next == terminal || next == 0 /* Term.Err */)\n return pair(data, i + 1);\n }\n }\n return 0;\n }\n /// @internal\n stateSlot(state, slot) {\n return this.states[(state * 6 /* ParseState.Size */) + slot];\n }\n /// @internal\n stateFlag(state, flag) {\n return (this.stateSlot(state, 0 /* ParseState.Flags */) & flag) > 0;\n }\n /// @internal\n validAction(state, action) {\n return !!this.allActions(state, a => a == action ? true : null);\n }\n /// @internal\n allActions(state, action) {\n let deflt = this.stateSlot(state, 4 /* ParseState.DefaultReduce */);\n let result = deflt ? action(deflt) : undefined;\n for (let i = this.stateSlot(state, 1 /* ParseState.Actions */); result == null; i += 3) {\n if (this.data[i] == 65535 /* Seq.End */) {\n if (this.data[i + 1] == 1 /* Seq.Next */)\n i = pair(this.data, i + 2);\n else\n break;\n }\n result = action(pair(this.data, i + 1));\n }\n return result;\n }\n /// Get the states that can follow this one through shift actions or\n /// goto jumps. @internal\n nextStates(state) {\n let result = [];\n for (let i = this.stateSlot(state, 1 /* ParseState.Actions */);; i += 3) {\n if (this.data[i] == 65535 /* Seq.End */) {\n if (this.data[i + 1] == 1 /* Seq.Next */)\n i = pair(this.data, i + 2);\n else\n break;\n }\n if ((this.data[i + 2] & (65536 /* Action.ReduceFlag */ >> 16)) == 0) {\n let value = this.data[i + 1];\n if (!result.some((v, i) => (i & 1) && v == value))\n result.push(this.data[i], value);\n }\n }\n return result;\n }\n /// Configure the parser. Returns a new parser instance that has the\n /// given settings modified. Settings not provided in `config` are\n /// kept from the original parser.\n configure(config) {\n // Hideous reflection-based kludge to make it easy to create a\n // slightly modified copy of a parser.\n let copy = Object.assign(Object.create(LRParser.prototype), this);\n if (config.props)\n copy.nodeSet = this.nodeSet.extend(...config.props);\n if (config.top) {\n let info = this.topRules[config.top];\n if (!info)\n throw new RangeError(`Invalid top rule name ${config.top}`);\n copy.top = info;\n }\n if (config.tokenizers)\n copy.tokenizers = this.tokenizers.map(t => {\n let found = config.tokenizers.find(r => r.from == t);\n return found ? found.to : t;\n });\n if (config.specializers) {\n copy.specializers = this.specializers.slice();\n copy.specializerSpecs = this.specializerSpecs.map((s, i) => {\n let found = config.specializers.find(r => r.from == s.external);\n if (!found)\n return s;\n let spec = Object.assign(Object.assign({}, s), { external: found.to });\n copy.specializers[i] = getSpecializer(spec);\n return spec;\n });\n }\n if (config.contextTracker)\n copy.context = config.contextTracker;\n if (config.dialect)\n copy.dialect = this.parseDialect(config.dialect);\n if (config.strict != null)\n copy.strict = config.strict;\n if (config.wrap)\n copy.wrappers = copy.wrappers.concat(config.wrap);\n if (config.bufferLength != null)\n copy.bufferLength = config.bufferLength;\n return copy;\n }\n /// Tells you whether any [parse wrappers](#lr.ParserConfig.wrap)\n /// are registered for this parser.\n hasWrappers() {\n return this.wrappers.length > 0;\n }\n /// Returns the name associated with a given term. This will only\n /// work for all terms when the parser was generated with the\n /// `--names` option. By default, only the names of tagged terms are\n /// stored.\n getName(term) {\n return this.termNames ? this.termNames[term] : String(term <= this.maxNode && this.nodeSet.types[term].name || term);\n }\n /// The eof term id is always allocated directly after the node\n /// types. @internal\n get eofTerm() { return this.maxNode + 1; }\n /// The type of top node produced by the parser.\n get topNode() { return this.nodeSet.types[this.top[1]]; }\n /// @internal\n dynamicPrecedence(term) {\n let prec = this.dynamicPrecedences;\n return prec == null ? 0 : prec[term] || 0;\n }\n /// @internal\n parseDialect(dialect) {\n let values = Object.keys(this.dialects), flags = values.map(() => false);\n if (dialect)\n for (let part of dialect.split(\" \")) {\n let id = values.indexOf(part);\n if (id >= 0)\n flags[id] = true;\n }\n let disabled = null;\n for (let i = 0; i < values.length; i++)\n if (!flags[i]) {\n for (let j = this.dialects[values[i]], id; (id = this.data[j++]) != 65535 /* Seq.End */;)\n (disabled || (disabled = new Uint8Array(this.maxTerm + 1)))[id] = 1;\n }\n return new Dialect(dialect, flags, disabled);\n }\n /// Used by the output of the parser generator. Not available to\n /// user code. @hide\n static deserialize(spec) {\n return new LRParser(spec);\n }\n}\nfunction pair(data, off) { return data[off] | (data[off + 1] << 16); }\nfunction findFinished(stacks) {\n let best = null;\n for (let stack of stacks) {\n let stopped = stack.p.stoppedAt;\n if ((stack.pos == stack.p.stream.end || stopped != null && stack.pos > stopped) &&\n stack.p.parser.stateFlag(stack.state, 2 /* StateFlag.Accepting */) &&\n (!best || best.score < stack.score))\n best = stack;\n }\n return best;\n}\nfunction getSpecializer(spec) {\n if (spec.external) {\n let mask = spec.extend ? 1 /* Specialize.Extend */ : 0 /* Specialize.Specialize */;\n return (value, stack) => (spec.external(value, stack) << 1) | mask;\n }\n return spec.get;\n}\n\nexport { ContextTracker, ExternalTokenizer, InputStream, LRParser, LocalTokenGroup, Stack };\n", "// This file was generated by lezer-generator. You probably shouldn't edit it.\nimport { LRParser } from \"@lezer/lr\";\nexport const parser = LRParser.deserialize({\n version: 14,\n states: \"%QOVQPOOOOQO'#C_'#C_O_QQO'#C^OOQO'#DO'#DOOvQQO'#C|OOQO'#DR'#DROVQPO'#CuOOQO'#C}'#C}QOQPOOOOQO'#C`'#C`O!UQQO,58xO!dQPO,59VOVQPO,59]OVQPO,59_O!iQPO,59hO!nQQO,59aOOQO'#DQ'#DQOOQO1G.d1G.dO!UQQO1G.qO!yQQO1G.wOOQO1G.y1G.yOOQO'#Cw'#CwOOQO1G/S1G/SOOQO1G.{1G.{O#[QPO'#CnO#dQPO7+$]O!UQQO'#CxO#iQPO,59YOOQO<<Gw<<GwOOQO,59d,59dOOQO-E6v-E6v\",\n stateData: \"#q~OoOS~OsPOvUO~OTXOUXOVXOWXOXXOYXO`ZO~Of[Oh]Oj^OmpX~OZ`O[`O]`O^`O~OabO~OseO~Of[Oh]OwgO~Oh]Ofeijeimeiwei~OcjOdbX~OdlO~OcjOdba~O\",\n goto: \"#YvPPw}!TPPPPPPPPPPwPP!WPP!ZP!ZP!aP!g!jPPP!p!s!aP#P!aXROU[]XQOU[]RYQRibXTOU[]XVOU[]Rf^QkhRnkRWOQSOQ_UQc[Rd]QaYQhbRmj\",\n nodeNames: \"\u26A0 Filter ColumnValueExpression Column Operator Eq NotEq Gt Lt Starts Ends Number String True False ColumnSetExpression In LBrack Values Comma RBrack AndExpression And OrExpression Or ParenthesizedExpression As FilterName\",\n maxTerm: 39,\n skippedNodes: [0],\n repeatNodeCount: 1,\n tok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Y#o%nR-yU^QsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR.bWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#b%n#b#c.z#c#o%nR/RU`QsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR/jWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#f%n#f#g0S#g#o%nR0ZUhQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR0rWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#h%n#h#i1[#i#o%nR1aVsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#U1v#U#o%nR1{WsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#f%n#f#g2e#g#o%nR2jWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#h%n#h#i3S#i#o%nR3XWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#g%n#g#h3q#h#o%nR3xUXQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR4aWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#f%n#f#g4y#g#o%nR5OWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#i%n#i#j5h#j#o%nR5mWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#X%n#X#Y6V#Y#o%nR6^U]QsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%n\",\n tokenizers: [0, 1],\n topRules: {\"Filter\":[0,1]},\n tokenPrec: 0\n})\n", "import { Tree } from \"@lezer/common\";\nimport {\n Filter,\n FilterCombinatorOp,\n MultipleValueFilterClauseOp,\n SingleValueFilterClauseOp,\n} from \"@vuu-ui/vuu-filter-types\";\nimport {\n isMultiClauseFilter,\n isMultiValueFilter,\n isSingleValueFilter,\n} from \"@vuu-ui/vuu-utils\";\n\nclass FilterExpression {\n public name: string | undefined;\n #filter: Partial<Filter> | undefined = undefined;\n\n setFilterCombinatorOp(op: string, filter = this.#filter) {\n if (isMultiClauseFilter(filter) && filter.op === op) {\n return;\n } else {\n this.#filter = {\n op: op as FilterCombinatorOp,\n filters: [this.#filter as Filter],\n };\n }\n }\n\n add(filter: Partial<Filter>) {\n if (this.#filter === undefined) {\n this.#filter = filter;\n } else if (isMultiClauseFilter(this.#filter)) {\n this.#filter.filters.push(filter as Filter);\n } else {\n throw Error(`Invalid filter passed to FilterExpression`);\n }\n }\n\n setColumn(column: string, filter = this.#filter) {\n if (isMultiClauseFilter(filter)) {\n const target = filter.filters.at(-1);\n if (target) {\n this.setColumn(column, target);\n }\n } else if (filter) {\n filter.column = column;\n }\n }\n setOp(value: string, filter = this.#filter) {\n if (isMultiClauseFilter(filter)) {\n const target = filter.filters.at(-1);\n if (target) {\n this.setOp(value, target);\n }\n } else if (filter) {\n filter.op = value as\n | SingleValueFilterClauseOp\n | MultipleValueFilterClauseOp;\n }\n }\n setValue(value: string | number | boolean, filter = this.#filter) {\n if (isMultiClauseFilter(filter)) {\n const target = filter.filters.at(-1);\n if (target) {\n this.setValue(value, target);\n }\n } else if (isMultiValueFilter(filter)) {\n filter.values ??= [];\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n filter.values.push(value);\n } else if (isSingleValueFilter(filter)) {\n filter.value = value;\n }\n }\n\n toJSON(filter = this.#filter) {\n if (this.name) {\n return {\n ...filter,\n name: this.name,\n };\n } else {\n return filter;\n }\n }\n}\n\nexport const walkTree = (tree: Tree, source: string) => {\n const filterExpression = new FilterExpression();\n const cursor = tree.cursor();\n do {\n const { name, from, to } = cursor;\n switch (name) {\n case \"ColumnValueExpression\":\n filterExpression.add({});\n break;\n case \"ColumnSetExpression\":\n filterExpression.add({ op: \"in\" });\n break;\n\n case \"Or\":\n case \"And\":\n filterExpression.setFilterCombinatorOp(source.substring(from, to));\n break;\n\n case \"Column\":\n filterExpression.setColumn(source.substring(from, to));\n break;\n\n case \"Operator\":\n filterExpression.setOp(source.substring(from, to));\n break;\n\n case \"String\":\n filterExpression.setValue(source.substring(from + 1, to - 1));\n break;\n\n case \"Number\":\n filterExpression.setValue(parseFloat(source.substring(from, to)));\n break;\n\n case \"True\":\n filterExpression.setValue(true);\n break;\n\n case \"False\":\n filterExpression.setValue(false);\n break;\n\n case \"FilterName\":\n filterExpression.name = source.substring(from, to);\n break;\n\n default:\n }\n } while (cursor.next());\n\n return filterExpression.toJSON();\n};\n", "import { Filter } from \"@vuu-ui/vuu-filter-types\";\nimport { parser } from \"./generated/filter-parser\";\nimport { walkTree } from \"./FilterTreeWalker\";\n\nconst strictParser = parser.configure({ strict: true });\n\nexport const parseFilter = (filterQuery: string): Filter => {\n const parseTree = strictParser.parse(filterQuery);\n const filter = walkTree(parseTree, filterQuery) as Filter;\n return filter;\n};\n", "import {\n LanguageSupport,\n LRLanguage,\n styleTags,\n tags as tag,\n} from \"@vuu-ui/vuu-codemirror\";\nimport { parser } from \"@vuu-ui/vuu-filter-parser\";\n\nconst filterLanguage = LRLanguage.define({\n name: \"VuuFilterQuery\",\n parser: parser.configure({\n props: [\n styleTags({\n Identifier: tag.variableName,\n String: tag.string,\n Or: tag.emphasis,\n Operator: tag.operator,\n }),\n ],\n }),\n});\n\nexport const filterLanguageSupport = () => {\n return new LanguageSupport(filterLanguage);\n};\n", "import {\n HighlightStyle,\n syntaxHighlighting,\n tags,\n} from \"@vuu-ui/vuu-codemirror\";\n\nconst myHighlightStyle = HighlightStyle.define([\n { tag: tags.variableName, color: \"var(--vuuFilterEditor-variableColor)\" },\n { tag: tags.comment, color: \"green\", fontStyle: \"italic\" },\n]);\n\nexport const vuuHighlighting = syntaxHighlighting(myHighlightStyle);\n", "import { EditorView } from \"@vuu-ui/vuu-codemirror\";\n\nexport const vuuTheme = EditorView.theme(\n {\n \"&\": {\n color: \"var(--vuuFilterEditor-color)\",\n backgroundColor: \"var(--vuuFilterEditor-background)\",\n fontSize: \"var(--vuuFilterEditor-fontSize)\",\n },\n \".cm-content\": {\n caretColor: \"var(--vuuFilterEditor-cursorColor)\",\n padding: 0,\n },\n \".cm-line\": {\n lineHeight: \"var(--vuuFilterEditor-lineHeight)\",\n },\n \"&.cm-focused .cm-cursor\": {\n borderLeftColor: \"var(--vuuFilterEditor-cursorColor)\",\n },\n \"&.cm-focused .cm-selectionBackground, ::selection\": {\n backgroundColor: \"var(--vuuFilterEditor-selectionBackground)\",\n },\n \".cm-selectionBackground, ::selection\": {\n backgroundColor: \"var(--vuuFilterEditor-selectionBackground)\",\n },\n \".cm-scroller\": {\n fontFamily: \"var(--vuuFilterEditor-fontFamily)\",\n },\n \".cm-tooltip\": {\n background: \"var(--vuuFilterEditor-tooltipBackground)\",\n border: \"var(--vuuFilterEditor-tooltipBorder)\",\n borderRadius: \"4px\",\n boxShadow: \"var(--vuuFilterEditor-tooltipElevation)\",\n \"&.cm-tooltip-autocomplete > ul\": {\n fontFamily: \"var(--vuuFilterEditor-fontFamily)\",\n fontSize: \"var(--vuuFilterEditor-fontSize)\",\n maxHeight: \"240px\",\n },\n \"&.cm-tooltip-autocomplete > ul > li\": {\n alignItems: \"center\",\n display: \"flex\",\n height: \"var(--vuuFilterEditor-suggestion-height)\",\n padding: \"0 3px\",\n lineHeight: \"var(--vuuFilterEditor-suggestion-height)\",\n },\n \"&.cm-tooltip-autocomplete li[aria-selected]\": {\n background: \"var(--vuuFilterEditor-suggestion-selectedBackground)\",\n color: \"var(--vuuFilterEditor-suggestion-selectedColor)\",\n },\n },\n \".cm-completionIcon\": {\n height: \"18px\",\n flex: \"0 0 16px\",\n },\n \".cm-completionLabel\": {\n flex: \"1 1 auto\",\n },\n \".cm-completionIcon-filter\": {\n position: \"relative\",\n \"&:after\": {\n background: \"var(--salt-text-secondary-foreground)\",\n content: \"''\",\n \"-webkit-mask\": \"var(--svg-filter) center center/13px 13px\",\n \"-webkit-mask-repeat\": \"no-repeat\",\n position: \"absolute\",\n height: \"18px\",\n left: \"0px\",\n top: \"0px\",\n width: \"16px\",\n },\n },\n },\n { dark: false }\n);\n", "import {\n CompletionContext,\n CompletionSource,\n EditorState,\n getNodeByName,\n getValue,\n SyntaxNode,\n syntaxTree,\n} from \"@vuu-ui/vuu-codemirror\";\nimport { Filter } from \"@vuu-ui/vuu-filter-types\";\nimport { MutableRefObject, useCallback } from \"react\";\nimport {\n IFilterSuggestionProvider,\n SuggestionType,\n} from \"./useCodeMirrorEditor\";\n\nexport type FilterSubmissionMode = \"and\" | \"or\" | \"replace\" | \"tab\";\n\nexport type ApplyCompletion = (mode?: FilterSubmissionMode) => void;\n\nconst getOperator = (node: SyntaxNode, state: EditorState) => {\n let maybeColumnNode = node.prevSibling || node.parent;\n while (\n maybeColumnNode &&\n ![\"Column\", \"Operator\", \"In\"].includes(maybeColumnNode.name)\n ) {\n maybeColumnNode = maybeColumnNode.prevSibling || maybeColumnNode.parent;\n }\n if (maybeColumnNode?.name === \"In\" || maybeColumnNode?.name === \"Operator\") {\n return getValue(maybeColumnNode, state);\n } else {\n return undefined;\n }\n};\n\n// Operators that are more than a single character in length may incur partial matches\n// TODO need to check that previous token is a column\nconst getPartialOperator = (\n maybeOperatorNode: SyntaxNode,\n state: EditorState,\n columnName?: string\n) => {\n const value = getValue(maybeOperatorNode, state);\n if (columnName === undefined || value === columnName) {\n return;\n }\n if (\n [\"contains\", \"ends\", \"starts\"].some((val) =>\n val.startsWith(value.toLowerCase())\n )\n ) {\n return value;\n } else {\n return undefined;\n }\n};\n\nconst getClauseOperator = (node: SyntaxNode, state: EditorState) => {\n let maybeTargetNode = node.prevSibling || node.parent || node.lastChild;\n while (maybeTargetNode && maybeTargetNode.name === \"\u26A0\")\n maybeTargetNode = maybeTargetNode.prevSibling;\n if (maybeTargetNode && [\"As\", \"Or\", \"And\"].includes(maybeTargetNode.name)) {\n return getValue(maybeTargetNode, state);\n } else {\n return undefined;\n }\n};\n\nconst getFilterName = (node: SyntaxNode, state: EditorState) => {\n if (node.name === \"FilterName\") {\n return getValue(node, state);\n } else {\n let maybeTargetNode = node.prevSibling || node.parent || node.lastChild;\n while (maybeTargetNode && maybeTargetNode.name !== \"FilterName\")\n maybeTargetNode = maybeTargetNode.prevSibling;\n if (maybeTargetNode && maybeTargetNode.name === \"FilterName\") {\n return getValue(node, state);\n }\n }\n};\n\nconst getColumnName = (\n node: SyntaxNode,\n state: EditorState\n): string | undefined => {\n const prevNode = node.prevSibling;\n if (prevNode?.name === \"Column\") {\n return getValue(prevNode, state);\n } else if (prevNode?.name === \"Operator\") {\n return getColumnName(prevNode, state);\n }\n};\n\nconst getSetValues = (node: SyntaxNode, state: EditorState): string[] => {\n let maybeTargetNode = node.lastChild;\n const values: string[] = [];\n while (maybeTargetNode && maybeTargetNode.name !== \"In\") {\n const value = getValue(maybeTargetNode, state);\n if (value) {\n values.push(value);\n } else {\n break;\n }\n maybeTargetNode = maybeTargetNode.prevSibling;\n }\n return values;\n};\nexport const FilterlNamedTerms: readonly string[] = [\n \"Filter\",\n \"ParenthesizedExpression\",\n \"AndExpression\",\n \"OrExpression\",\n \"ColumnValueExpression\",\n \"ColumnSetExpression\",\n \"FilterName\",\n \"Column\",\n \"Operator\",\n \"Values\",\n \"Number\",\n \"String\",\n];\nexport const lastNamedChild = (node: SyntaxNode): SyntaxNode | null => {\n let { lastChild } = node;\n while (lastChild && !FilterlNamedTerms.includes(lastChild.name)) {\n lastChild = lastChild.prevSibling;\n console.log(lastChild?.name);\n }\n return lastChild;\n};\n\nexport const useAutoComplete = (\n suggestionProvider: IFilterSuggestionProvider,\n onSubmit: MutableRefObject<ApplyCompletion>,\n existingFilter?: Filter\n) => {\n const makeSuggestions = useCallback(\n async (\n context: CompletionContext,\n suggestionType: SuggestionType,\n optionalArgs: {\n columnName?: string;\n existingFilter?: Filter;\n filterName?: string;\n operator?: string;\n quoted?: boolean;\n onSubmit?: () => void;\n selection?: string[];\n startsWith?: string;\n } = {}\n ) => {\n const { startsWith = \"\" } = optionalArgs;\n const options = await suggestionProvider.getSuggestions(\n suggestionType,\n optionalArgs\n );\n return { from: context.pos - startsWith.length, options };\n },\n [suggestionProvider]\n );\n\n return useCallback(\n async (context: CompletionContext) => {\n const { state, pos } = context;\n const word = context.matchBefore(/\\w*/) ?? {\n from: 0,\n to: 0,\n text: undefined,\n };\n\n const tree = syntaxTree(state);\n const nodeBefore = tree.resolveInner(pos, -1);\n console.log({ nodeBeforeName: nodeBefore.name });\n\n switch (nodeBefore.name) {\n case \"Filter\":\n if (context.pos === 0) {\n return makeSuggestions(context, \"column\");\n } else {\n const clauseOperator = getClauseOperator(nodeBefore, state);\n if (clauseOperator === \"as\") {\n return makeSuggestions(context, \"name\");\n } else {\n const filterName = getFilterName(nodeBefore, state);\n return makeSuggestions(context, \"save\", {\n onSubmit: onSubmit.current,\n existingFilter,\n filterName,\n });\n }\n }\n\n case \"String\":\n {\n // we only encounter a string as the right hand operand of a conditional expression\n const operator = getOperator(nodeBefore, state);\n const columnName = getColumnName(nodeBefore, state);\n // are we inside the string or immediately after it\n const { from, to } = nodeBefore;\n if (to - from === 2 && context.pos === from + 1) {\n // We are in an empty string, i.e between two quotes\n if (columnName && operator) {\n return makeSuggestions(context, \"columnValue\", {\n columnName,\n operator,\n quoted: true,\n startsWith: word.text,\n });\n }\n } else {\n console.log(\n `we have a string, column is ${columnName} ${from} ${to}`\n );\n }\n }\n break;\n\n case \"As\":\n return makeSuggestions(context, \"name\");\n\n case \"FilterName\":\n return makeSuggestions(context, \"save\", {\n onSubmit: onSubmit.current,\n existingFilter,\n filterName: getFilterName(nodeBefore, state),\n });\n\n case \"Column\": {\n const columnName = getValue(nodeBefore, state);\n const isPartialMatch = await suggestionProvider.isPartialMatch(\n \"column\",\n undefined,\n columnName\n );\n if (isPartialMatch) {\n return makeSuggestions(context, \"column\", {\n startsWith: columnName,\n });\n } else {\n return makeSuggestions(context, \"operator\", { columnName });\n }\n }\n\n case \"\u26A0\": {\n const columnName = getNodeByName(nodeBefore, state);\n const operator = getOperator(nodeBefore, state);\n // TODO check if we're mnatching a partial jojn operator\n const partialOperator = operator\n ? undefined\n : getPartialOperator(nodeBefore, state, columnName);\n\n if (partialOperator) {\n return makeSuggestions(context, \"operator\", {\n columnName,\n startsWith: partialOperator,\n });\n } else {\n return makeSuggestions(context, \"columnValue\", {\n columnName,\n operator,\n startsWith: word.text,\n });\n }\n }\n\n case \"Identifier\":\n {\n const clauseOperator = getClauseOperator(nodeBefore, state);\n if (clauseOperator === \"as\") {\n return {\n from: context.pos,\n options: [\n {\n label: \"press ENTER to apply filter and save\",\n apply: () => onSubmit.current(),\n boost: 5,\n },\n ],\n };\n }\n }\n break;\n case \"ColumnSetExpression\":\n case \"Values\": {\n const columnName = getNodeByName(nodeBefore, state);\n const selection = getSetValues(nodeBefore, state);\n return makeSuggestions(context, \"columnValue\", {\n columnName,\n selection,\n });\n }\n case \"Comma\":\n case \"LBrack\": {\n const columnName = getNodeByName(nodeBefore, state) as string;\n return makeSuggestions(context, \"columnValue\", { columnName });\n }\n\n case \"ColumnValueExpression\":\n {\n const lastToken = nodeBefore.lastChild?.prevSibling;\n if (lastToken?.name === \"Column\") {\n return makeSuggestions(context, \"operator\", {\n columnName: getNodeByName(nodeBefore, state),\n });\n } else if (lastToken?.name === \"Operator\") {\n return makeSuggestions(context, \"columnValue\", {\n columnName: getNodeByName(lastToken, state),\n operator: getValue(lastToken, state),\n });\n }\n }\n break;\n\n case \"In\": {\n return {\n from: context.pos,\n options: [{ label: \"[\", apply: \" [\", type: \"text\" }],\n };\n }\n\n case \"Eq\": {\n return makeSuggestions(context, \"columnValue\", {\n columnName: getNodeByName(nodeBefore, state),\n });\n }\n\n case \"AndExpression\":\n case \"OrExpression\": {\n return makeSuggestions(context, \"column\");\n }\n\n default:\n }\n },\n [existingFilter, makeSuggestions, onSubmit, suggestionProvider]\n ) as CompletionSource;\n};\n", "import {\n asNameSuggestion,\n booleanJoinSuggestions,\n Completion,\n getNamePrompt,\n numericOperators,\n stringOperators,\n toSuggestions,\n} from \"@vuu-ui/vuu-codemirror\";\nimport {\n getTypeaheadParams,\n useTypeaheadSuggestions,\n} from \"@vuu-ui/vuu-data-react\";\nimport { SuggestionFetcher } from \"@vuu-ui/vuu-data-types\";\nimport { Filter } from \"@vuu-ui/vuu-filter-types\";\nimport { VuuTable } from \"@vuu-ui/vuu-protocol-types\";\nimport { ColumnDescriptor } from \"@vuu-ui/vuu-table-types\";\n// import { isMappedValueTypeRenderer, isTypeDescriptor } from \"@vuu-ui/vuu-utils\";\nimport { useCallback, useRef } from \"react\";\nimport { filterInfo } from \"./filterInfo\";\nimport {\n IFilterSuggestionProvider,\n SuggestionType,\n} from \"./useCodeMirrorEditor\";\nimport { ApplyCompletion } from \"./useFilterAutoComplete\";\n\nconst NO_NAMED_FILTERS = [] as Completion[];\nconst NONE = {};\n\nconst saveAsTab = (onSubmit: ApplyCompletion) => [\n {\n label: \"Press ENTER to create TAB\",\n apply: () => onSubmit(\"tab\"),\n boost: 6,\n },\n];\n\nconst makeSaveOrExtendSuggestions = (\n onSubmit: ApplyCompletion,\n existingFilter?: Filter,\n withJoinSuggestions = true\n) => {\n const result = existingFilter\n ? ([\n {\n label: \"REPLACE existing filter\",\n apply: () => onSubmit(\"replace\"),\n boost: 8,\n },\n {\n label: \"AND existing filter\",\n apply: () => onSubmit(\"and\"),\n boost: 7,\n },\n {\n label: \"OR existing filter\",\n apply: () => onSubmit(\"or\"),\n boost: 7,\n },\n ] as Completion[])\n : ([\n {\n label: \"Press ENTER to submit\",\n apply: () => onSubmit(),\n boost: 6,\n },\n ] as Completion[]);\n\n return withJoinSuggestions\n ? result.concat(booleanJoinSuggestions).concat(asNameSuggestion)\n : result;\n};\n\nconst promptToSaveOrExtend = (\n onSubmit: ApplyCompletion,\n existingFilter?: Filter\n) => makeSaveOrExtendSuggestions(onSubmit, existingFilter, true);\n\nconst promptToSave = (onSubmit: ApplyCompletion) =>\n makeSaveOrExtendSuggestions(onSubmit, undefined);\n\nconst getSaveSuggestions = ({\n existingFilter,\n filterName,\n onSubmit,\n saveOptions,\n}: {\n existingFilter?: Filter;\n filterName?: string;\n onSubmit: () => void;\n saveOptions: FilterSaveOptions;\n}) => {\n const includeTabSuggestion = filterName && saveOptions.allowSaveAsTab;\n const result = existingFilter\n ? promptToSaveOrExtend(onSubmit, existingFilter)\n : promptToSave(onSubmit);\n\n if (includeTabSuggestion) {\n return result.concat(saveAsTab(onSubmit));\n } else {\n return result;\n }\n};\n\nconst suggestColumns = (columns: ColumnDescriptor[]) =>\n columns.map((column) => ({\n boost: 5,\n label: column.name,\n }));\n\nconst suggestNamedFilters = (namedFilters?: Map<string, string>) =>\n namedFilters\n ? (Array.from(namedFilters.entries()).map(([filterName, filterQuery]) => ({\n info: () => filterInfo(filterName, filterQuery),\n label: filterName,\n type: \"filter\",\n })) as Completion[])\n : NO_NAMED_FILTERS;\n\nconst doneCommand: Completion = {\n label: \"Done\",\n apply: \"] \",\n type: \"keyword\",\n boost: 10,\n};\n\nconst withApplySpace = (\n suggestions: Completion[],\n startsWith = \"\"\n): Completion[] =>\n suggestions\n .filter((sugg) => startsWith === \"\" || sugg.label.startsWith(startsWith))\n .map((suggestion) => ({\n ...suggestion,\n apply: suggestion.label + \" \",\n }));\n\nexport type FilterSaveOptions = {\n allowSaveAsTab?: boolean;\n allowReplace?: boolean;\n};\nexport interface SuggestionProviderHookProps {\n columns: ColumnDescriptor[];\n namedFilters?: Map<string, string>;\n saveOptions?: FilterSaveOptions;\n table: VuuTable;\n typeaheadHook?: () => SuggestionFetcher;\n}\n\nconst defaultSaveOptions = {\n allowReplace: true,\n};\n\nexport const useFilterSuggestionProvider = ({\n columns,\n namedFilters,\n saveOptions = defaultSaveOptions,\n table,\n typeaheadHook: useTypeahead = useTypeaheadSuggestions,\n}: SuggestionProviderHookProps): IFilterSuggestionProvider => {\n const latestSuggestionsRef = useRef<Completion[]>();\n const getTypeaheadSuggestions = useTypeahead();\n const getSuggestions: IFilterSuggestionProvider[\"getSuggestions\"] =\n useCallback(\n async (suggestionType, options = NONE): Promise<Completion[]> => {\n const {\n columnName,\n existingFilter,\n filterName,\n operator,\n quoted: autoQuoted,\n onSubmit,\n startsWith,\n selection,\n } = options;\n\n switch (suggestionType) {\n case \"operator\":\n {\n const column = columns.find((col) => col.name === columnName);\n if (column) {\n switch (column.serverDataType) {\n case \"string\":\n case \"char\":\n return withApplySpace(stringOperators, startsWith);\n case \"int\":\n case \"long\":\n case \"double\":\n return withApplySpace(numericOperators);\n }\n } else {\n console.warn(`'${columnName}' does not match any column name`);\n }\n }\n break;\n case \"column\": {\n const columnSuggestions = await suggestColumns(columns);\n const filterSuggestions = await suggestNamedFilters(namedFilters);\n return (latestSuggestionsRef.current =\n withApplySpace(columnSuggestions)).concat(\n withApplySpace(filterSuggestions)\n );\n }\n case \"columnValue\":\n {\n if (columnName) {\n const column = columns.find((col) => col.name === columnName);\n if (!column) {\n throw Error(\n `useFilterSUggestionProvider no column ${columnName}`\n );\n }\n const prefix = Array.isArray(selection)\n ? selection.length === 0\n ? \"[\"\n : \",\"\n : \"\";\n const params = getTypeaheadParams(\n table,\n columnName,\n startsWith\n );\n const suggestions = await getTypeaheadSuggestions(params);\n // const { type } = column;\n // if (\n // isTypeDescriptor(type) &&\n // isMappedValueTypeRenderer(type?.renderer)\n // ) {\n // const { map } = type.renderer;\n // suggestions = suggestions.map((value) => map[value] ?? value);\n // }\n\n // prob don't want to save the prefix\n const isIllustration = operator === \"starts\";\n latestSuggestionsRef.current = toSuggestions(suggestions, {\n moveCursorToEnd: autoQuoted,\n quoted: column?.serverDataType === \"string\" && !autoQuoted,\n suffix: autoQuoted ? \"\" : \" \",\n prefix: isIllustration ? startsWith : prefix,\n isIllustration,\n });\n if (Array.isArray(selection) && selection?.length > 1) {\n return [doneCommand, ...latestSuggestionsRef.current];\n }\n return latestSuggestionsRef.current;\n }\n }\n break;\n case \"save\": {\n if (typeof onSubmit !== \"function\") {\n throw Error(\n \"useFilterSuggestionProvider, onSubmit must be supplied for 'save' suggestions\"\n );\n }\n return await getSaveSuggestions({\n existingFilter,\n filterName,\n onSubmit,\n saveOptions,\n });\n }\n case \"name\":\n return await getNamePrompt(\"filter\");\n default:\n }\n\n return [];\n },\n [columns, getTypeaheadSuggestions, namedFilters, saveOptions, table]\n );\n\n const isPartialMatch = useCallback(\n async (\n valueType: SuggestionType,\n columnName?: string,\n pattern?: string\n ) => {\n // const { current: latestSuggestions } = latestSuggestionsRef;\n const suggestions =\n // latestSuggestions && latestSuggestions.length > 0\n // ? latestSuggestions\n await getSuggestions(valueType, { columnName });\n\n if (pattern && suggestions) {\n for (const option of suggestions) {\n if (option.label === pattern) {\n return false;\n } else if (option.label.startsWith(pattern)) {\n return true;\n }\n }\n }\n return false;\n },\n [getSuggestions]\n );\n\n return {\n getSuggestions,\n isPartialMatch,\n };\n};\n", "import { createEl } from \"@vuu-ui/vuu-utils\";\n\nexport const filterInfo = (\n filterName: string,\n filterQuery: string\n // filter: Filter\n) => {\n const rootElement = createEl(\"div\", \"vuuFunctionDoc\");\n const headingElement = createEl(\"div\", \"function-heading\");\n\n const nameElement = createEl(\"span\", \"function-name\", filterName);\n // const paramElement = createEl(\"span\", \"param-list\", params.description);\n // const typeElement = createEl(\"span\", \"function-type\", type);\n\n headingElement.appendChild(nameElement);\n // headingElement.appendChild(paramElement);\n // headingElement.appendChild(typeElement);\n\n const child2 = createEl(\"p\", undefined, filterQuery);\n\n rootElement.appendChild(headingElement);\n rootElement.appendChild(child2);\n\n return rootElement;\n};\n", "export const getLocalEntity = <T>(url: string): T | undefined => {\n const data = localStorage.getItem(url);\n return data ? JSON.parse(data) : undefined;\n};\n\nexport const getAllLocalEntity = <T>(url: string): T[] =>\n Object.entries(localStorage)\n .filter(([key]) => key.includes(url))\n .map(([, value]) => JSON.parse(value) as T);\n\nexport const saveLocalEntity = <T>(url: string, data: T): T | undefined => {\n try {\n localStorage.setItem(url, JSON.stringify(data));\n return data;\n } catch {\n return undefined;\n }\n};\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AA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,QAAQ,YAAY,EACxB,OAAO,CAAC,CAAC,GAAG,MAAM,IAAI,SAAS,GAAG,CAAC,EACnC,IAAI,CAAC,CAAC,EAAE,KAAK,MAAM,KAAK,MAAM,KAAK,CAAM;AAEvC,IAAM,kBAAkB,CAAI,KAAa,SAA2B;AACzE,MAAI;AACF,iBAAa,QAAQ,KAAK,KAAK,UAAU,IAAI,CAAC;AAC9C,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;",
6
6
  "names": ["import_vuu_popups", "import_vuu_ui_controls", "import_core", "import_react", "ListProps", "Popup", "import_vuu_ui_controls", "import_react", "import_jsx_runtime", "classBase", "ExpandoCombobox", "defaultToString", "value", "text", "ListProps", "import_react", "import_vuu_utils", "import_react", "import_vuu_ui_controls", "import_vuu_utils", "import_jsx_runtime", "NumericInput", "value", "import_react", "import_vuu_ui_controls", "import_jsx_runtime", "module", "value", "_a", "import_vuu_utils", "import_react", "import_vuu_ui_controls", "import_vuu_utils", "import_jsx_runtime", "import_jsx_runtime", "classBase", "import_vuu_utils", "import_react", "value", "import_jsx_runtime", "classBase", "import_vuu_popups", "import_vuu_ui_controls", "import_vuu_utils", "import_react", "import_vuu_popups", "import_react", "import_jsx_runtime", "classBase", "import_vuu_utils", "import_vuu_utils", "import_vuu_utils", "import_jsx_runtime", "f", "import_jsx_runtime", "classBase", "import_vuu_popups", "import_jsx_runtime", "classBase", "import_vuu_utils", "import_react", "import_react", "import_vuu_ui_controls", "import_react", "import_vuu_utils", "import_jsx_runtime", "import_react", "classBase", "FilterClauseEditorProps", "getChildren", "filterClauses", "import_core", "import_vuu_codemirror", "IterMode", "r", "children", "positions", "node", "buffer", "data", "length", "lookAhead", "pair", "nodeSize", "from", "to", "r", "parser", "i", "Recover", "r", "Safety", "parser", "Rec", "r", "i", "import_vuu_utils", "import_react", "tag", "import_vuu_codemirror", "import_vuu_codemirror", "import_vuu_codemirror", "import_react", "parseFilter", "clearInput", "createState", "import_jsx_runtime", "classBase", "import_vuu_codemirror", "import_vuu_data_react", "import_react", "import_vuu_utils"]
7
7
  }